所以我是編程新手,我正在嘗試撰寫一個程式,我腦子里有一個數字,計算機必須猜它,直到我說它猜對了!計算機應該選擇一個1到99之間的亂數顯示給我,如果數字正確我應該輸入“c”來證明它是正確的,如果我腦海中的數字更小我應該寫“s”來使范圍更小,如果我腦海中的數字更大,我應該寫“b”以使范圍更小,讓計算機更容易猜測數字。這是我想出的代碼,但是我找不到它的問題。
import random
first=1
second=99
guess=random.randint(first,second)
print(guess)
answer=input("what is the number in your head(don't enter it, just compare it with the number on the screen)? print c for correct, b for bigger and s for smaller! \n")
while answer!="c":
if answer=="b":
first==guess 1
guess=random.randint(first,second)
print(guess)
elif answer=="s":
second==guess-1
guess=random.randint(first,second)
print(guess)
answer=input("what do you think about the new number? ")
print("you did it!")
uj5u.com熱心網友回復:
您有兩個錯誤:==在您應該使用=(賦值)的地方使用(測驗相等性),以及錯誤的縮進:
import random
first = 1
second = 99
guess = random.randint(first, second)
print(guess)
answer = input("what is the number in your head(don't enter it, just compare it with the number on the screen)? print c for correct, b for bigger and s for smaller! \n")
while answer != "c":
if answer == "b":
first = guess 1 # <-- this line
guess = random.randint(first, second)
print(guess)
elif answer == "s":
second = guess - 1 # <-- this line
guess = random.randint(first, second)
print(guess)
answer = input("what do you think about the new number? ") # <-- and this line
print("you did it!")
最后一行只會在回圈結束后運行,而不是按照您撰寫的方式在每個回圈中運行一次。
看看我添加的空格如何讓每一行的內容更清楚
uj5u.com熱心網友回復:
您應該縮進第二個輸入行,使其屬于 while 回圈。這樣每次猜測后都會請求新的輸入。
uj5u.com熱心網友回復:
您的程式是正確的,它只需要在 while 回圈中進行一些修改。它應該如下所示:
while answer != "c":
if answer == "b":
first = guess 1
guess = random.randint(first, second)
print(guess)
elif answer == "s":
second = guess-1
guess = random.randint(first, second)
print(guess)
answer = input("what do you think about the new number? ")
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/487571.html
上一篇:如何減少if陳述句Python?
下一篇:Excel上的嵌套IF陳述句
