所以我正在猜测Python 3中的数字游戏
在整个过程之后,我希望我的while循环生成另一个数字,以便我可以再次开始游戏而无需再次运行该程序。 请让我知道我做错了什么,如果您能为我提供一些有关while循环使用方法的见解,将不胜感激。
这是代码:
import random
while True:
number = random.randint(1, 1000)
count = 0
guessed = input("Enter the number you guessed: ")
count += 1
if int(guessed) < number:
print("You guessed too low")
elif int(guessed) > number:
print("You guessed too high")
elif int(guessed) == number:
print(f'You guessed right and it took you {count} guesses to the right number which is {number}')
答案 0 :(得分:0)
不确定您粘贴的代码是否是错字(缩进),但是我可能不小心更改了您的实现。
无论如何,您应该只添加另一个while
循环,并在用户正确使用它时添加一个中断条件。
import random
while True:
number = random.randint(1, 1000)
count = 0
while True: # Added, and added another layer of indentation
guessed = input("Enter the number you guessed: ")
count += 1
if int(guessed) < number:
print("You guessed too low")
elif int(guessed) > number:
print("You guessed too high")
elif int(guessed) == number:
print(f'You guessed right and it took you {count} guesses to the right number which is {number}')
break # Added
这样做,代码将不断循环以猜测正确的数字,直到正确为止。然后生成一个新的数字进行猜测。但是,除非添加其他中断条件(例如,设置标志while
循环将检查是否突破外循环),否则该代码永远不会结束。
答案 1 :(得分:0)
我编写了一些快速代码,提示用户是否要继续玩,然后循环浏览并根据需要继续使用新号码继续游戏。我还修复了一些小错误。您的计数一直在循环中重置,因此它总是会说您在1次尝试中发现了它。
import random
def promptUser():
user_continue = input("Do you want to continue playing? y/n")
if (user_continue == 'y'):
number = random.randint(1, 10)
game(0, number)
def game(count, number):
while True:
guessed = input("Enter the number you guessed: ")
count += 1
if int(guessed) < number:
print("You guessed too low")
elif int(guessed) > number:
print("You guessed too high")
elif int(guessed) == number:
print(f'You guessed right and it took you {count} guesses to the right number which is {number}')
promptUser()
break
promptUser()