Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/287.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 单行if语句中的语法错误_Python - Fatal编程技术网

Python 单行if语句中的语法错误

Python 单行if语句中的语法错误,python,Python,我不熟悉UNIX上的python脚本。 我正在尝试创建目录,但它导致以下错误: >>> import os, sys >>> path = "/u/home/user/exist" >>> if not os.path.exists(path):os.mkdir(path) ... print "Directory does not exists. created one" File "<stdin>", line 2

我不熟悉UNIX上的python脚本。 我正在尝试创建目录,但它导致以下错误:

>>> import os, sys
>>> path = "/u/home/user/exist"
>>> if not os.path.exists(path):os.mkdir(path)
... print "Directory does not exists. created one"



File "<stdin>", line 2
    print "Directory does not exists. created one";
        ^
SyntaxError: invalid syntax
>>>
导入操作系统,系统 >>>path=“/u/home/user/exist” >>>如果不存在os.path.exists(path):os.mkdir(path) ... 打印“目录不存在。已创建一个” 文件“”,第2行 打印“目录不存在,已创建一个”; ^ SyntaxError:无效语法 >>>
错误是您需要在打印前退出辅助提示

>>> if not os.path.exists(path):os.mkdir(path) # press an enter here!!!
...
>>> print "Directory does not exists. created one"
Directory does not exists. created one
这就是Python神总是要求避免使用单行
if
条件的原因。使用

>>> if not os.path.exists(path):
...    os.mkdir(path) # Indent here!!!
...
>>> print "Directory does not exists. created one"
Directory does not exists. created one
这是更具可读性的方法

注意:从代码读取时,
打印
必须是
if
块的一部分。所以请,请使用:

>>> if not os.path.exists(path):
...    os.mkdir(path) # Indent here!!!
...    print "Directory does not exists. created one"
...
>>>   

@EdChum OP需要在键入下一个命令之前按enter键statement@EdChum在交互式shell中键入
if 1:pass
,按return,然后在仍处于
提示的情况下,键入
a=1
并按return。给出了相同的错误。@matsjoyce好的,理解代码对我来说有点可笑,所以我认为这是一些有趣的终端输出