[英]How to make my while loop work in Python?
這是我的代碼:
import random
Random = random.randint(1, 10)
print("Number:" + str(Random))
Number = int(input("Guess the number I am thinking of from 1-10"))
while int(Random) != Number:
if(Random > Number):
Number = input("Too low. Guess again!")
elif(Number > Random):
Number = input("Too high. Guess again!")
print("You guessed it!")
當猜到正確的數字時,就會發生這種情況,這就是應該發生的事情。
Number:8
Guess the number I am thinking of from 1-10 8
You guessed it!
但是,當數字沒有被正確猜到時,它只通過 elif 語句循環。
Number:10
Guess the number I am thinking of from 1-10 6
Too low. Guess again! 7
Too high. Guess again! 6
Too high. Guess again! 5
Too high. Guess again! 4
Too high. Guess again! 3
Too high. Guess again! 2
Too high. Guess again! 1
Too high. Guess again! 10
Too high. Guess again! 9
Too high. Guess again! 8
您是否嘗試在 while 循環中的兩個輸入行中將 int 投射到輸入上? 當它像這樣時,它似乎對我有用:
if(Random > Number):
Number = int(input("Too low. Guess again!"))
elif(Number > Random):
Number = int(input("Too high. Guess again!"))
import random
number=random.randint(1,10)
guess=int(input("Guess the number I am thinking of from 1-10")
while guess !=number:
if guess < number:
print("Your answer was too low...")
else:
print("Your number was too high...")
guess= int(input("Please try again...")
print("Congratulations! Correct answer!")
你可以把它作為你的參考。 謝謝你...
這是您的代碼的改進版本:
import random
answer = random.randint(1, 10)
print("Number:" + str(answer))
guess = int(input("Guess the number I am thinking of from 1-10"))
while answer != guess:
if guess < answer:
guess = int(input("Too low. Guess again!"))
elif guess > answer:
guess = int(input("Too high. Guess again!"))
print("You guessed it!")
關於改動的一些說明:
input()
周圍的int()
input()
。 input()
您提供一個字符串值,但您想比較數字的值,而不是字符串。 例如'12' < '2'
但12 > 2
。Random
與您正在使用的模塊同名,因此很容易混淆, answer
似乎是一個更好的選擇。if guess < answer
正是您所說的:“太低了”。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.