Python3.1中的问题;否则:“;在我的代码中
您好,我是新来的编码,在这里我写了一个简单的代码基于用户的输入。我可以得到每个if和elif响应,但当输入不是整数时,我的程序失败Python3.1中的问题;否则:“;在我的代码中,python,Python,您好,我是新来的编码,在这里我写了一个简单的代码基于用户的输入。我可以得到每个if和elif响应,但当输入不是整数时,我的程序失败 def tables_bussed(): tables = input("How many tables can you bus per hour? (I can only read numbers.)") if int(tables) > 80: print ("That\'s rediculous, you lying tw
def tables_bussed():
tables = input("How many tables can you bus per hour? (I can only read numbers.)")
if int(tables) > 80:
print ("That\'s rediculous, you lying twit.")
tables_bussed()
elif int(tables) > 60:
print ("If what you are saying is true then you have quite a talent!")
elif int(tables) > 30:
print ("Impressive! Yet there\'s always room for improvement, now isn\'t there.")
elif int(tables) > 0:
print ("How sad.")
else:
print ("Are you dumb or just daft.")
tables_bussed()
tables_bussed()
我的else子句中缺少什么吗?您需要一个try-except子句,我不想重做您的程序,但这里是一般概念
def tables_bussed():
tables = input("How many tables can you bus per hour? (I can only read numbers.)")
try:
tables = int(tables)
except ValueError:
print ('Sorry dude, you must input a number that is an integer')
tables_bussed()
因为我在try子句中将表定义为整数,所以不必重复使用int(tables)语句,只需测试值即可
因此,请在定义表之后立即放置(注意,您有一些缩进问题,但代码中可能没有)
程序将尝试将表解析为整数,如果不成功,将提示用户重试
关于try-except子句有很多,它们对于捕捉用户输入问题或您可能遇到的其他问题非常有用
def tables_bussed():
while True:
tables = input("How many tables can you bus per hour? (I can only read numbers.)")
if tables.isdigit():
if int(tables) > 80:
print ("That\'s rediculous, you lying twit.")
continue
elif int(tables) > 60:
print ("If what you are saying is true then you have quite a talent!")
elif int(tables) > 30:
print ("Impressive! Yet there\'s always room for improvement, now isn\'t there.")
elif int(tables) > 0:
print ("How sad.")
break
else:
print ("Are you dumb or just daft.")
tables_bussed()
您得到的确切错误是什么?您的最终打印没有缩进,但我认为这只是一个复制粘贴问题?缩进丢失您的缩进在else语句中似乎不正确。错误消息的最后一行是ValueError:invalid literal for int(),以10为基数:“”请编辑缩进,使其与代码完全匹配。我认为这对
Python
language很重要好的,谢谢你,我会检查这是否有效!永远不要使用try子句,这是我第三天自学的lol,虽然它有效地是递归的,但是while循环是一个更好的选择。在这种情况下,为什么你不在你的答案中解释为什么你认为它更好,而不是在我的答案下面发表评论。断言对于新程序员来说不是很有用。你应该清楚地说明这一点。你有一个例子,我一般不喜欢while循环,因此如果你帮助用户了解发生了什么,用户将得到最大的好处。@PyNEwbie答案已经被接受,我只是想展示一个替代方法,但是因为你问我,我觉得不必要的递归比简单的循环更糟糕-事实上你“不喜欢while循环”这似乎也是一个奇怪的断言。本例中的while循环提供了一种明确的方法,可以强制输入正确,而不会由于递归而导致任何堆栈溢出的可能性。我只是说,另一个答案通常对我们这些新手没有帮助,除非他们解释了为什么它更好、更有效。等等,我不是一个经过培训的程序员,所以这只是一个对我来说更好的断言。。为了让答案持续下去,他们应该有一个解释,而不仅仅是一个代码转储。我的解释并不详细,“尝试将表解析为整数,如果不成功,它将提示用户重试”。当我查看您的代码时,我想知道它在开始时是否为真-为什么在开始时不能为假?