Python输出不符合预期

2024-04-19 04:04:33 发布

您现在位置:Python中文网/ 问答频道 /正文

我的代码如下:

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美元”是 预期-为什么?你知道吗


Tags: 代码ageyourispromptquitintus
3条回答

当您在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

因为它指向else条件,例如我把13,第一个条件不正确转到第二个,13 < 3false,转到第三个,13 > 3这里是true < 12这里是false,条件是false,现在去else把你想要的东西放在这个else上。你知道吗

这种情况的一个很好的例子是使用断言:

assert 13 > 3 and 13 < 12

可能你必须使用AND运算符。你知道吗

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

我还建议您在阅读输入之后立即转换它—您不必每次都编写int(age):)

age = int(input(prompt))

相关问题 更多 >