Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/jquery-ui/2.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和elif语句置于input或similiar下_Python - Fatal编程技术网

使用python将if和elif语句置于input或similiar下

使用python将if和elif语句置于input或similiar下,python,Python,我正在学习python(不知道这是不是一个学习python的好地方,但它看起来很好),我想知道它们是否类似于(这只是一个不识字的示例) x=input(“您的年龄\?”) 如果x>18: 打印(“不客气”) elif x18: 打印(“不客气”) elif x

我正在学习python(不知道这是不是一个学习python的好地方,但它看起来很好),我想知道它们是否类似于(这只是一个不识字的示例)

x=input(“您的年龄\?”)
如果x>18:
打印(“不客气”)
elif x<18:
打印(“您未成年,请稍后再试”)
如果我试着在空闲状态下运行它,似乎会给出一个无效语法的错误。有什么想法吗?

Python关心缩进。因此,在
if
else
语句中缩进块(所有块语句也是如此)

逃避事物
不需要转义,所以不要转义它<代码>\\需要在字符串文本中转义,如果您使用的是单引号(
)(三引号字符串文本不需要转义,除非您一行有三个,在这种情况下,转义一个就足够了;您不必在
文本中转义
,反之亦然)

输入 如果您使用的是Python2,那就太好了。如果您使用的是Python3,
input
会给出一个字符串,所以要将
x=int(input(“…”)
转换为int

如果……否则 除非在最后一次
elif
之后有更多的语句,否则只需使用
else
。另外,当
x==18
时会发生什么?
x<18
是假的,并且
x>18
因此不会发生任何事情。没有针对18岁用户的消息…:p

最后的代码如下所示:

x = input("What is your age?") # replace with `int(input(...))` in Python 3
if x > 18:
    print("You are welcome")
else:
    print("You are underaged, try again later")

您可能试图在此处将字符串与数字进行比较:

if x > 18:
要解决此问题,请尝试以下方法:

x = int(input("What is your age\?"))
if x > 18:
   print("You are welcome")
elif x < 18:
    print("You are underaged, try again later")
x=int(输入(“您的年龄\?”)
如果x>18:
打印(“不客气”)
elif x<18:
打印(“您未成年,请稍后再试”)

这将确保从输入中获取的数字始终是整数。

上面的代码看起来不错,但也取决于python版本。在python 2.x中,input()尝试将用户输入计算为适当的数据类型,但在python 3.x中,input()的工作方式与raw_input()类似在Python2.x中,也就是说,它接受字符串并以这种方式保持它。因此,如果您尝试将字符串与检查条件的int进行比较,它将失败


此外,请记住缩进非常重要,如果顺序不正确,可能会导致错误。请尝试使用其中一种方法,但不要同时使用这两种方法,以保持简单。

缩进打印语句。@DYZ缩进可能是问题所在;我不建议对OP进行修复,以防出现问题problem@HyperNeutrino可能吧。不正确地通过向函数键入的数据不是语法错误。
x = int(input("What is your age\?"))
if x > 18:
   print("You are welcome")
elif x < 18:
    print("You are underaged, try again later")