[英]Why is the while loop creating an infinite loop? Guessing 1 and 100
我創建了一個while循環,因此我將繼續詢問用戶問題,直到他們知道正確的數字為止。 但是,例如,當a做一個隨機數時,它要么無限地打印“選擇一個較高的數字”,要么“打印一個較低的數字”。 有人可以在這里幫我嗎。
from random import randint
answer = randint(1, 100)
print("Guess a number between 1 and 3.")
guess = int(input())
count = 0
while guess != answer:
if guess < answer:
print("Pick a higher number.")
count += 1
elif guess > answer:
print("Pick a lower number.")
count += 1
elif guess == answer:
print("You got it!")
print("It took you " + str(count) + " tries.")
嘗試這個。
while True:
guess = int(input("Guess a number between 1 and 3."))
if guess < answer:
print("Pick a higher number.")
count += 1
elif guess > answer:
print("Pick a lower number.")
count += 1
elif guess == answer:
print("You got it!")
break
讓我這樣說:您何時從用戶那里獲得輸入? 第二次循環運行會怎樣? guess
隨時更新嗎?
這些(建議性)問題的答案將帶您走正確的道路:
您必須在每次循環運行中向用戶請求輸入。
這將帶您了解如何開始循環。
from random import randint
answer = randint(1, 100)
count = 0
keep_loop = True
prompt = "Guess a number between 1 and 3."
while keep_loop:
print(prompt)
guess = int(input())
if guess < answer:
prompt = "Pick a higher number."
count += 1
elif guess > answer:
prompt = "Pick a lower number."
count += 1
elif guess == answer:
print("You got it!")
keep_loop = False
print("It took you " + str(count) + " tries.")
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.