簡體   English   中英

如何讓我的 while 循環在 Python 中工作?

[英]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
  • 您的變量名稱中包含大寫字母,這在 Python 中是個壞主意,因為這向編輯器和其他程序員表明它們是類而不是變量。
  • 您的變量Random與您正在使用的模塊同名,因此很容易混淆, answer似乎是一個更好的選擇。
  • 您的代碼縮進了 2 個空格,但大多數編輯器默認為 4,這也符合標准 Python 樣式指南。
  • 與其改變變量的順序,通常最好讓你的代碼盡可能接近它的含義; 例如, if guess < answer正是您所說的:“太低了”。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM