[英]Random number game in python, with according messages
I am trying to make a random-number game, where you have to guess which random number Python gets from 1-10.我正在尝试制作一个随机数游戏,您必须在其中猜测 Python 从 1-10 中得到哪个随机数。 And also do so that if you write eg 11, 104 etc. it will ask you to try again to write a valid input.
并且还要这样做,如果您写入例如 11、104 等,它会要求您再次尝试写入有效输入。
This is what I have tried so far, but I cant seem to figure out what I have done wrong.到目前为止,这是我尝试过的方法,但我似乎无法弄清楚我做错了什么。 All help is greatly appreciated:) Sorry if it is an easy question, I am still fairly new to Python
非常感谢所有帮助:)抱歉,如果这是一个简单的问题,我对 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")
try this if this is your expected one:如果这是你期望的,试试这个:
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
Lots of small mistakes, here is a working solution.很多小错误,这是一个可行的解决方案。 I'll try to talk you through it:
我会试着和你谈谈:
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
block is redundant - it will continue to the next iteration neverthelessexcept
块内继续是多余的 - 尽管如此,它仍将继续下一次迭代break
and continue
are keywords used only inside a loop break
和continue
是仅在循环内使用的关键字number_in != number
)number_in != number
)<=
instead of <
<=
而不是<
import random
was missing from the example codeimport random
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.