【发布时间】:2022-01-06 12:53:40
【问题描述】:
我正在尝试创建一个可重复的函数,该函数使用 while 循环重复尝试 try-except 循环,但我在某些部分遇到了问题。 这是我当前的功能:
def trytrytryagain(input):
ValueError
while ValueError:
try:
input() = int(input())
except ValueError:
print("You must enter a number")
input = int(input())
当我运行代码并输入“a”(以测试它是否反复要求用户输入数字)时,它总是在第一次迭代后显示此错误消息。
Traceback (most recent call last):
File "main.py", line 7, in trytrytryagain
int(input())
ValueError: invalid literal for int() with base 10: 'a'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "main.py", line 16, in <module>
trytrytryagain (times_table)
File "main.py", line 10, in trytrytryagain
int(input())
ValueError: invalid literal for int() with base 10: 'a'
因此,我发现创建此功能非常困难。它意味着一直运行直到用户输入一个数字,并在每次迭代后显示消息“您必须输入一个数字”。我完全糊涂了,所以这是上下文的完整代码(它是一个时间表生成器)。
from time import sleep
def trytrytryagain(input):
ValueError
while ValueError:
try:
int(input())
except ValueError:
print("You must enter a number")
int(input())
print("Please input the times table you wish to complete (1, 2, 3, etc.).")
times_table = input
trytrytryagain (times_table)
print("Would you like to go up to another times table (do the 1 to 12 times tables)? yes/no")
try:
othertables = str(input()).lower()
except ValueError:
print("You must enter either yes or no")
othertables = str(input()).lower()
if othertables == "yes":
print("Enter which time table you want to go up to.")
try:
other_times_table = int(input())
except ValueError:
print("You must enter a number")
other_times_table = int(input())
print("Enter the maximum table you would like to go up to. (if you do the 3 to 5 times tables, what times table would you like to finish on - type 12 for 5 x 12, 13 for 5 x 13, etc.)")
try:
max_value = int(input())
except ValueError:
print("You must enter a number")
max_value = int(input())
for x2 in range(times_table, other_times_table + 1):
for x in range(max_value + 1):
print(f"{x} x {x2} =")
input()
sleep(0.1)
else:
print("Okay.")
print("Enter the maximum table you would like to go up to. (if you do the 3 to 5 times tables, what times table would you like to finish on (type 12 for 5 x 12, etc.))")
try:
max_value = int(input())
except ValueError:
print("You must enter a number")
max_value = int(input())
for x in range(times_table, max_value + 1):
answer = x * times_table
print(f"{x} times {times_table} is {answer}")
sleep(0.1)
【问题讨论】:
-
在您的第一个示例中,错误位于 `int(input())` 行...但该行不在示例中。最好发布一个完全运行的测试脚本(包括对 trytrytryagain 的调用),以便我们可以运行它并看到相同的错误。就像你在第二个例子中所做的那样。
标签: python function variables input try-except