在我的代码的选项2部分中,我的循环无法正常运行,我不知道为什么。它不断要求再次输入。我尝试将输入移出循环,但这也不起作用。
Session.SignalWithType("signal", message, Session.Connection,true, out err);
用户使用计算机随机生成的数字,直到用户获取 正确答案。 输出用户的猜测和尝试次数,直到猜测正确为止
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: "))
选项2.,用户输入一个数字供计算机猜测。 计算机猜测给定范围内的数字。 输出计算机猜测和猜测数目,直到计算机获取 正确的数字。
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()
答案 0 :(得分:0)
您应该在循环之前 要求输入。 counter
也应在循环之前进行初始化。
if option == 2:
print("Computer guess my number")
print()
# these three lines will be run once before the loop
my_num = input("Enter a number between 1 and 10 for the computer to guess: ")
my_num = int(my_num)
counter = 0
while True:
try:
comp = random.randint(1,10)
counter += 1
print()
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
顺便说一句,您可以使用binary search(尝试次数有上限)来改善计算机的猜测,而不是随机猜测。