【发布时间】:2019-09-09 11:06:18
【问题描述】:
在我的代码的选项 2 部分中,我的循环无法正常运行,我无法弄清楚原因。它不断要求再次输入。我尝试将输入移到循环之外,但这也不起作用。
import random
def display_menu():
print("Welcome to my Guess the Number Program!")
print("1. You guess the number")
print("2. You type a number for the computer to guess.")
print("3. Exit")
print()
def main():
display_menu()
option = int(input("Enter a menu option: "))
用户对计算机随机生成的数字进行拍照,直到用户得到 正确答案。 输出用户猜测和尝试次数,直到猜测正确
if option == 1:
number = random.randint(1,10)
counter = 0
while True:
try:
guess = input("Guess a number between 1 and 10: ")
guess = int(guess)
print()
if guess < 1 or guess > 10:
raise ValueError()
counter += 1
if guess > number:
print("Too high.")
print()
elif guess < number:
print("Too low.")
print()
else:
print("You guessed it!")
print("You guessed the number in", counter, "attempts!")
break
except ValueError:
print(guess, "is not a valid guess")
print()
选项 2.,用户输入一个数字供计算机猜测。 计算机猜测给定范围内的数字。 输出计算机猜测和猜测次数,直到计算机得到 正确的数字。
if option == 2:
print("Computer guess my number")
print()
while True:
try:
my_num = input("Enter a number between 1 and 10 for the computer to guess: ")
my_num = int(my_num)
counter = 0
counter += 1
print()
comp = random.randint(1,10)
if my_num < 1 or my_num > 10:
raise ValueError()
if comp > my_num:
print("Computer guessed", comp,"to High")
elif comp < my_num:
print("Computer guessed", comp,"to Low")
else:
print("Computer guessed the right number!" , comp)
print("Computer guessed the right number in", counter, "attempts!")
break
except ValueError:
print(my_num, "is not a valid entry")
print()
continue
"""
Ends game
"""
if option == 3:
print("Goodbye")
if __name__ == '__main__':
main()
【问题讨论】: