number = random.choice(range(1,100)) tries = 0 而True: 尝试: guess =输入(''输入介于1和100之间的数字:'') break 除了NameError: print''无效的数字\ n'' 继续 而True: 尝试+ = 1 尝试: 如果猜= =数字: 打印''恭喜!你得到它'',尝试','猜测。'' 休息 elif guess<数字: guess =输入('太低。再试一次:'') elif guess>数字: guess =输入('太高。再试一次:'') 除了NameError: print''无效的数字\\ n'' 继续 raw_input()This might help:import randomnumber = random.choice(range(1, 100))tries = 0while True:try:guess = input(''Enter a number between 1 and 100: '')breakexcept NameError:print ''Invalid number\n''continuewhile True:tries += 1try:if guess == number:print ''Congratulations! You got it in'', tries, ''guess(es).''breakelif guess < number:guess = input(''Too low. Try again: '')elif guess > number:guess = input(''Too high. Try again: '')except NameError:print ''Invalid number\n''continueraw_input() 这是另一个相关的问题:: 年= raw_input(''输入年份(或其他退出的角色):'') 尝试: 年= int(年) 除了NameError: break 如果(年%4 == 0)和(年%100!= 0或年%400 == 0): 打印年份,''是闰年。\ n'' else: 打印年份,''不是闰年。\ n'' raw_input() 这是按预期工作的,除非你输入任何其他字符 而不是数字,程序刚退出。为什么它还没有执行 raw_input函数并暂停?我认为这也是 其他练习中发生的事情,但我不知道为什么。如果你突破循环, 它是否仍然会在raw_input暂停?Here''s another question that is related:while True:year = raw_input(''Enter year (or other character to quit): '')try:year = int(year)except NameError:breakif (year % 4 == 0) and (year % 100 != 0 or year % 400 == 0):print year, ''is a leap year.\n''else:print year, ''is not a leap year.\n''raw_input()This works as expected, except that if you enter any character otherthan a number, the program just quits. Why doesn''t it still execute theraw_input function and pause? I think this is what is happening in theother exercise too, but I don''t know why. If you break out of the loop,should it still pause at raw_input? 这篇关于我想,循环问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!
09-11 16:28