【发布时间】:2015-09-16 22:13:00
【问题描述】:
在我的计算机科学入门课程中,我被分配编写一个程序,该程序将打印出要求用户输入的数字 (20-99)。我已经能够做到这一点,并且如果用户没有在此范围内输入数字,则会创建一条错误消息。我遇到的问题是当输入超出范围的数字时,会显示错误消息,但由于某种原因程序继续运行并仍打印出英文数字。我一直在试图弄清楚如何让程序在错误消息处停止,但我无法弄清楚。这是我目前拥有的。
a=int(input('Pick a number between 20 through 99:'))
b=a//10
c=a%10
while a<20 or a>99:
print('Error, enter number between 20 and 99:')
break
while a>20 or a<99:
if b==2:
print('The number is Twenty',end=' ')
elif b==3:
print('The number is Thirty',end=' ')
elif b==4:
print('The number is Fourty',end=' ')
elif b==5:
print('The number is Fifty',end=' ')
elif b==6:
print('The number is Sixty',end=' ')
elif b==7:
print('The number is Seventy',end=' ')
elif b==8:
print('The number is Eighty',end=' ')
else:
print('The number is Ninety',end=' ')
if c==1:
print('One')
elif c==2:
print('Two')
elif c==3:
print('Three')
elif c==4:
print('Four')
elif c==5:
print('Five')
elif c==6:
print('Six')
elif c==7:
print('Seven')
elif c==8:
print('Eight')
else:
print('Nine')
break
【问题讨论】:
-
首先,感谢您诚实地说这是家庭作业。您可以使用条件
if语句来测试输入的变量是否在 20 到 99 之间而不是循环。 -
您有一个带有无条件
break的循环。这基本上只是一个if声明。如果你真的想继续要求一个新号码,你需要在循环中这样做。看来您需要查看教科书中有关循环和输入检查的部分。
标签: python if-statement while-loop