我想重復詢問數字程序,而guess 與 TrueNum 不相等,但是當我將它放入 while 回圈時,它只是重復列印它的“if”我該怎么辦?
import random
# Defining True Num:
DataRange = list(range(0, 11))
TrueNum = int(random.choice(DataRange))
print("it`s in range from o to 10")
# Getting Guesses From User:
Guess = int(input("Input your number: "))
# Checking Guess:3
while Guess != TrueNum:
if Guess > TrueNum:
print("You Are Getting Far...")
elif Guess < TrueNum:
print("It`s bigger than you think :)")
break
if Guess == TrueNum:
print("yeah that`s it")
uj5u.com熱心網友回復:
你需要把輸入放在while里面,也可以去掉一些不必要的條件:
import random
# Defining True Num:
DataRange = list(range(0, 11))
TrueNum = int(random.choice(DataRange))
print("it`s in range from o to 10")
# Getting Guesses From User:
Guess = int(input("Input your number: "))
# Checking Guess:3
while Guess != TrueNum:
if Guess > TrueNum:
print("You Are Getting Far...")
else:
print("It`s bigger than you think :)")
Guess = int(input("Input your number: "))
print("yeah that`s it")
uj5u.com熱心網友回復:
使用 Try/Except 可以解決無效選擇,同時保持可讀性。
import random
# Defining True Num:
DataRange = list(range(0, 11))
TrueNum = int(random.choice(DataRange))
print("it`s in range from o to 10")
# Getting Guesses From User:
while True:
try:
Guess = int(input("Input your number: "))
if Guess > TrueNum:
print("You Are Getting Far...")
elif Guess < TrueNum:
print("It`s bigger than you think :)")
elif Guess == TrueNum:
print("yeah that`s it")
break
except ValueError:
print("Invalid Choice")
uj5u.com熱心網友回復:
變數 Guess 定義在回圈外,您應該將輸入并檢查回圈內的值。
import random
datarange = list(range(0, 11))
trueNum = int(random.choice(datarange))
print("Guess the number! It`s in range from o to 10")
while True:
Guess = int(input("Input your number: "))
if Guess == trueNum:
print("Yeah that`s it")
break
elif Guess > trueNum:
print("You Are Getting Far...")
else:
print("It`s bigger than you think :)")
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/449696.html
上一篇:使用批處理回圈,直到按下任何鍵
