【发布时间】:2021-02-01 00:18:18
【问题描述】:
为什么我的函数不能根据用户输入正确执行?以下是我的完整脚本,包括描述。底部 play_again() 定义的函数似乎出现故障。每次我输入“是”或“否”时,它都会再次显示用户输入提示。
"""Task 5:
Write a script that plays “guess the number.” Choose the number to be guessed by selecting a random integer in the range 1 to 1000.
Do not reveal this number to the user. Display the prompt "Guess my number between 1 and 1000 with the fewest guesses:". The player inputs a first guess. If the guess is incorrect,
display "Too high. Try again." or "Too low. Try again." as appropriate to help the player “zero in” on the correct answer, then prompt the user for the next guess.
When the user enters the correct answer, display "Congratulations. You guessed the number!", and allow the user to choose whether to play again. (10 points).
"""
import random
def guessing_game():
number = random.randrange(1, 1001)
guess = int(input('Guess my number between 1 and 1000 with the fewest guesses:'))
while guess != number:
if guess >= 1001:
print("Please enter a number less than or equal to 1000")
guess = int(input('Guess my number between 1 and 1000 with the fewest guesses:'))
elif guess < 1:
print("Please enter a number greater than or equal to 1")
guess = int(input('Guess my number between 1 and 1000 with the fewest guesses:'))
elif guess > number:
print("Too high Try again.")
guess = int(input('Guess my number between 1 and 1000 with the fewest guesses:'))
elif guess < number:
print("Too low. Try again")
guess = int(input('Guess my number between 1 and 1000 with the fewest guesses:'))
print("Congratulations. You guessed the number", end= " ")
play_again()
def play_again():
while True:
play = input("Would you like to play again? Enter yes or no.")
if play == 'yes':
guessing_game()
elif play == 'no':
exit()
【问题讨论】:
-
运行此代码时,在第 9 行出现错误:未定义变量号。