简体   繁体   English

Python-输出不符合预期

[英]Python - output not as expected

My code is as follows: 我的代码如下:

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

Probably a simple answer, but when age entered greater than 12, returns 'Your admission charge is $10' when 'Your admission charge is $15' is expected - Why ? 可能是一个简单的答案,但是如果年龄大于12岁,则返回“您的入场费为10美元”,而预期为“您的入场费为15美元”-为什么?

When you have several condition after your elif statement, the syntax is a bit different : 如果您的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

Its because its goint to else condition for example i put 13 , first condition is incorrect going to second, 13 < 3 false , going to third, 13 > 3 here true < 12 here false, the condition is false , now going to else and make the stuff you want on this else in your case the print . 它的,因为它goint到别的条件比如我把13,第一个条件是不正确要去第二, 13 < 3 ,去第三, 13 > 3这里真正的< 12此处假的,条件是假的 ,现在要else和使您想要的else在您的情况下print

Good example of this situation is use of assert : 这种情况的一个很好的例子是使用assert

assert 13 > 3 and 13 < 12

Probably you have to use AND operator. 可能您必须使用AND运算子。

elif int(age) > 3 and int(age) < 12:
...

I also recommend casting the input right after you read it - you don't have to write int(age) every time :) 我还建议您在阅读输入后立即转换输入-您不必每次都写int(age):)

age = int(input(prompt))

Try 3 < age < 12 尝试3 <年龄<12

Your int(age) > 3 < 12 is interpreted as int(age) > 3 && 3 < 12 which is true for all ages over 3 您的int(age)> 3 <12被解释为int(age)> 3 && 3 <12,适用于3岁以上的所有年龄段

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM