我正在尝试制作一个随机数游戏,你必须猜测Python从1-10中得到哪个随机数。同时,如果你写了11、104等,它会要求你再次尝试写一个有效的输入。
这是我迄今为止所尝试的,但我似乎不明白我做错了什么。非常感谢您的帮助:(很抱歉,如果这是一个简单的问题,我对Python 还相当陌生
while True:
try:
number_in = int(input("Please insert a number between 1-10: "))
except ValueError:
print("Sorry. Try again to insert a number from 1 to 10")
continue
if 1 < number <10:
print("Your input was invalid. Please insert a number from 1 to 6")
continue
else:
break
game_1 = randint(1,10)
if number_in == game_1:
print(f"The result was {game_1}. Your guess was correct, congratulations!")
else:
print(f"The result was {game_1}. Your guess was NOT correct. Try again")
很多小错误,这里有一个有效的解决方案。我试着和你谈谈:
import random
while True:
try:
number_in = int(input("Please insert a number between 1-10: "))
if 1 <= number_in <= 10:
break
else:
print("Your input was invalid. Please insert a number from 1 to 10")
except ValueError:
print("Sorry. Try again to insert a number from 1 to 10")
game_1 = random.randint(1, 10)
if number_in == game_1:
print(f"The result was {game_1}. Your guess was correct, congratulations!")
else:
print(f"The result was {game_1}. Your guess was NOT correct. Try again")
- 当满足正确的输入时,您需要中断循环
- 在
except
块中继续是多余的——尽管如此,它仍将继续到下一次迭代 break
和continue
是仅在循环中使用的关键字- Conditional应在循环内
- 条件具有错误的变量名称(
number_in != number
( - 条件性是颠倒的(数字在1和10之间-"错误输入"(
- 条件中使用了错误的比较。您希望包含1和10作为猜测,因此
<=
而不是<
- 示例代码中缺少
import random
- 请注意:continue和break仅在循环语句中使用
如果这是你想要的,试试这个:
from random import randint
def validateNumber():
valid = False
if 1 < number_in <10:
valid = True
return valid
game_1 = randint(1,10)
while True:
try:
number_in = int(input("Please insert a number between 1-10: "))
is_valid = validateNumber()
if not is_valid:
number_in = int(input("Please insert a number between 1-10: "))
if number_in == game_1:
print(f"The result was {game_1}. Your guess was correct, congratulations!")
else:
print(f"The result was {game_1}. Your guess was NOT correct. Try again")
except ValueError:
break