如果用户在某个年龄之间,则告诉笑话的代码

时间:2014-01-24 04:10:17

标签: python-2.7

age = 0

joke = 'What do you call a cow with no legs? Ground beef.'

myName = raw_input('Hello! What is your name?')

myAge = raw_input('Tell me your age, ' + myName + ', to hear a joke!')

if age < 6:
    print('You are too young to hear this joke.')

elif age > 12:
    print('You are too old to hear this joke.')

elif age == range(6, 12):
    print(joke)

代码运行时,只说我太小了,即使我把数字高于6甚至高于12,也听不到这个笑话。你能帮我解决这个问题吗?

2 个答案:

答案 0 :(得分:1)

最后elif没有必要。只需在没有条件的情况下使用else

如果age < 6age > 12评估为false,我们知道6≤a≤12。无需检查它。

BTW,range()返回可迭代的,而不是可以与数字进行比较的内容。比较将始终失败,因为您正在比较两个不兼容的事物。

答案 1 :(得分:1)

您将输入分配给变量“myAge”,并在if语句中测试变量“age”。

替换

myAge = raw_input('Tell me your age, ' + myName + ', to hear a joke!')

age = input('Tell me your age, ' + myName + ', to hear a joke!')