所以这是我的代码,这段代码的目的是要求用户输入一个值:1,2或3,如果用户输入其他内容,它将显示"无效输入" 当用户输入1,2或3时,它将从0开始计数到用户输入的值。
def c():
while True:
i = input("Give me one of 1,2 or 3: ")
if len(i)==1 and i>="1"and i<="3":
return int(i)
else:
print("invalid input!")
for i in range(i+1):
print(i)
c()
一切正常,直到for循环,我是python中的新学习者,我不知道如何解决它。
答案 0 :(得分:0)
if块表示值1-3将立即返回。
然而,else块没有返回,它表示“无效输入”,但它继续到for循环,这与你需要发生的情况相反。返回应该在else块中。
答案 1 :(得分:0)
您的问题是:如果i
小于3且大于1,则该函数将退出,并且不运行for循环。
也许你想要这样的东西:
while True:
i = int(input("Give me one of 1,2 or 3: "))
# just put the int() funtion here, the input will be convert to integer.
if len(i) == 1 and i => 1 and i <= 3:
print(i)
else:
print("invalid input!")
continue
# use continue, this will skip the for loop because it's invalid input
for i in range(i+1):
print(i)