自学的Python出了一本书印刷3层不同的反应根据年龄和我卡在这个练习中:根据一个人的年龄 一个电影院费用不同票价。如果一个人年龄在3岁以下,那么机票是免费的;如果他们在3到12之间,票价是10美元;如果他们超过12岁,票价是15美元。写一个你问用户年龄的循环,然后告诉他们他们的电影票的成本。初学者的Python - 使用while循环
我知道如何在不使用循环的情况下工作,但我不确定如何使用while循环使其工作。任何建议或例子将不胜感激。
自学的Python出了一本书印刷3层不同的反应根据年龄和我卡在这个练习中:根据一个人的年龄 一个电影院费用不同票价。如果一个人年龄在3岁以下,那么机票是免费的;如果他们在3到12之间,票价是10美元;如果他们超过12岁,票价是15美元。写一个你问用户年龄的循环,然后告诉他们他们的电影票的成本。初学者的Python - 使用while循环
我知道如何在不使用循环的情况下工作,但我不确定如何使用while循环使其工作。任何建议或例子将不胜感激。
做到这一点的一种方法是无限循环。不要忘记包括一个休息条件,否则你将无法优雅地退出你的程序。
while True:
userinput = int(input())
if userinput < 0:
break
# your if logic goes here
我能弄明白我自己做想这样来创建一个无限循环的
prompt = "\nEnter 'quit' when you are finished."
prompt += "\nPlease enter your age: "
while True:
age = input(prompt)
age = int(age)
if age == 'quit':
break
elif age <= 3:
print("Your ticket is free")
elif age <= 10:
print("Your ticket is $10")
else:
print("Your ticket is $15")
实际上这并没有工作100%... quit函数将不起作用,因为它不是一个整数。因此,这引出了一个新问题:如何让它与整数答案和字符串答案一起工作? – iriejams
方式一:
price = -1
while price == -1:
try:
age=int(raw_input('Age: '))
except ValueError:
print "Not a number, try again."
continue
if age <= 3:
price = 0
elif age > 3 and age < 12:
price = 10
else:
price = 15
print "The price will be "+str(price)+"$."
注: 重命名的raw_input ()输入()如果您使用Python 3.
没有工作 - 回溯(最近通话最后一个): 4号线,在
你在使用Python 3吗?在Python 3中raw_input()被重命名为input() –
我知道这是一个老问题,但没有一个答案似乎很棒。所以这是我的解决方案7-5/7-6
loop = True
#while loop = true run 'while loop'
while loop:
#Print message
print ('Please enter your age.')
#receive input from user
age = raw_input()
#check if the user input "quit" if so end loop. Break ends program but should be replaceable by
#if age == 'quit':
# loop = False
#resulting the the same effect (ending loop)
if age == 'quit':
break
#Convert age input by user to int so it is recognized as a number by python
age = int(age)
#If/ elif pretty self explanatory
if age < 3:
price = 5
elif age < 12:
price = 10
elif age > 12:
price = 15
else:
print('Input not recognized')
break
#Print ticket price based on age and ask user if they need another price/inform them how to exit program
print('Your ticked price is $' + str(price) + '.')
print('\n If you would like to check the price for another person please enter their age now or type "quit" to exit')
格式化可能有点关闭,因为它粘贴奇怪。我试图解释一切。此外,我用2.7而不是3,所以如果你使用Python 3替换raw_input()与输入()
希望这个答案对一些有帮助。 GL编程。
显示您尝试过的内容,并且您可能会获得更多帮助,您可能只需要包含一个永久循环,例如, '而真:'。 – AChampion