[英]Python - output not as expected
我的代码如下:
prompt = '\nPlease tell us your age'
prompt += "\n(Enter 'quit' when you are finished)"
while True:
age = input(prompt)
if age == 'quit':
break
elif int(age) < 3:
print ('Your admission is free')
elif int(age) > 3 < 12:
print ('Your admission charge is $10')
else:
print ('Your admission charge is $15')
break
可能是一个简单的答案,但是如果年龄大于12岁,则返回“您的入场费为10美元”,而预期为“您的入场费为15美元”-为什么?
如果您的elif
语句后有多个条件,则语法略有不同:
while True:
age = input(prompt)
if age == 'quit':
break
elif int(age) < 3:
print ('Your admission is free')
elif (int(age) > 3) and (int(age) < 12):
# Annother possibility :
#elif 3 < int(age) < 6 :
print ('Your admission charge is $10')
else:
print ('Your admission charge is $15')
break
它的,因为它goint到别的条件比如我把13,第一个条件是不正确要去第二, 13 < 3
假 ,去第三, 13 > 3
这里真正的< 12
此处假的,条件是假的 ,现在要else
和使您想要的else
在您的情况下print
。
这种情况的一个很好的例子是使用assert :
assert 13 > 3 and 13 < 12
可能您必须使用AND运算子。
elif int(age) > 3 and int(age) < 12:
...
我还建议您在阅读输入后立即转换输入-您不必每次都写int(age):)
age = int(input(prompt))
尝试3 <年龄<12
您的int(age)> 3 <12被解释为int(age)> 3 && 3 <12,适用于3岁以上的所有年龄段
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.