实施GuessNumber游戏。在这个游戏中,电脑 - 想想0-50范围内的随机数。 (提示:使用随机模块。) - 反复提示用户猜出神秘数字。 - 如果猜测正确,请祝贺用户获胜。如果猜测不正确,请让用户知道猜测是太高还是太低。 - 经过5次错误的猜测后,告诉用户正确的答案。
以下是正确输入和输出的示例。
I’m thinking of a number in the range 0-50. You have five tries to
guess it.
Guess 1? 32
32 is too high
Guess 2? 18
18 is too low
Guess 3? 24
You are right! I was thinking of 24!
这是我到目前为止所得到的:
import random
randomNumber = random.randrange(0,50)
print("I’m thinking of a number in the range 0-50. You have five tries to guess it.")
guessed = False
while guessed == False:
userInput = int(input("Guess 1?"))
if userInput == randomNumber:
guessed = True
print("You are right! I was thinking of" + randomNumber + "!")
elif userInput>randomNumber:
print(randomNumber + "is too high.")
elif userInput < randomNumber:
print(randomNumber + "is too low.")
elif userInput > 5:
print("Your guess is incorrect. The right answer is" + randomNumber)
print("End of program")
我一直在收到语法错误,当用户输入错误的答案时,我不知道如何将猜测增加一,例如,猜猜1?,猜猜2?,猜猜3?猜猜4?,猜5?等等......
答案 0 :(得分:2)
由于你知道你经历循环的次数,并想要计算它们,所以使用for
循环来控制那个部分。
for guess_num in range(1, 6):
userInput = int(input("Guess " + str(guess_num) + "?"))
if userInput == randomNumber:
# insert "winner" logic here
break
# insert "still didn't guess it" logic here
你看到它是如何运作的吗?
答案 1 :(得分:2)
您忘记缩进属于while
循环的代码。此外,您希望跟踪您猜测的次数,使用建议的变量或循环。此外,在给出提示时,您可能想要打印玩家猜测的数字,而不是实际的数字。如,
import random
randomNumber = random.randrange(0,50)
print("I’m thinking of a number in the range 0-50. You have five tries to guess it.")
guessed = False
count = 0
while guessed is False and count < 5:
userInput = int(input("Guess 1?"))
count += 1
if userInput == randomNumber:
guessed = True
print("You are right! I was thinking of" + randomNumber + "!")
elif userInput > randomNumber:
print(str(userInput) + " is too high.")
elif userInput < randomNumber:
print(str(userInput) + " is too low.")
if count == 5:
print("Your guess is incorrect. The right answer is" + str(randomNumber))
print("End of program")
答案 2 :(得分:1)
您正面临语法错误,因为您正在尝试向字符串添加整数。这是不可能的。要执行您想要的操作,您需要在每个打印语句中转换randomNumber
。
import random
randomNumber = random.randrange(0,50)
print("I’m thinking of a number in the range 0-50. You have five tries to guess it.")
guessed = False
while guessed == False:
userInput = int(input("Guess 1?"))
if userInput == randomNumber:
guessed = True
print("You are right! I was thinking of" + str(randomNumber) + "!")
elif userInput>randomNumber:
print(str(randomNumber) + "is too high.")
elif userInput < randomNumber:
print(str(randomNumber) + "is too low.")
elif userInput > 5:
print("Your guess is incorrect. The right answer is" + randomNumber)
print("End of program")