今天就來做一個猜數字遊戲吧
首先要先做出要被猜的數字,我們使用random的模組來做出數字
import random
answer = random.randint(1,100)
print(answer)
再來把你猜的數字輸入
guess = input()
再來設定一個布林值還有迴圈以及判斷式
b = True
while (b):
guess = int(input())
if(answer == guess):
print("猜到了")
b= False
else:
print("猜錯了")
guess = int(input())
這樣猜對的話就會結束迴圈,猜錯的話就會繼續執行迴圈
接下來來做猜錯時的提示
import random
answer = random.randint(1,100)
print(answer)
b = True
while (b):
guess = int(input())
if(answer == guess):
print("猜到了")
b= False
elif(answer< guess):
print("猜錯了,比較小")
elif(answer>guess):
print("猜錯了,比較大")
如果要再進一步的比對答案的範圍的話,可以在加兩個變數
import random
answer = random.randint(1,100)
print(answer)
l=1
h=100
b = True
while (b):
print("請輸入要猜的數字,在", l , "到",h ,"之間")
guess = int(input())
if(answer == guess):
print("猜到了")
b= False
elif(answer< guess):
print("猜錯了,比較小")
h = guess
elif(answer>guess):
print("猜錯了,比較大")
l = guess
這樣每一次猜錯答案的範圍會縮小