1. 程式人生 > >Python入門小程序(一)

Python入門小程序(一)

while 條件 循環條件 次數 ima http post nba random

學習了FishC的Python零基礎入門第4節,本次的內容是Python的while循環語句和條件語句。

1. 用一個條件語句實現猜數字的小程序

程序設定一個數字,用戶輸入一個數字,判斷是否猜對。

temp=input("猜猜我心中的數字:")
guess=int(temp)
if guess==8:
    print("猜對!")
else:
    print("猜錯了!")
print("遊戲結束!")

###運行結果:
技術分享圖片

2. 改進程序猜隨機數字

上一個程序中,用戶猜錯要重新運行程序,嵌套while循環讓用戶可以一直猜,知道猜對。另外,系統設定的數字不能是靜態的,要改為隨機生成。

#改進
import random
temp = input("猜猜我心中的數字:")
guess=int(temp)
secret=random.randint(1,10)
while guess!=secret:
if (guess<secret):
print("猜小了!")
else:
print("猜大了!")
temp=input("猜猜我心中的數字:")
guess = int(temp)
print("猜對!遊戲結束!")

###運行結果:
技術分享圖片

3. 改進程序限定用戶的機會

現在,用戶只能有三次機會來猜數字。我們可以修改循環的條件,當用戶沒猜中並且機會還沒用完,就一直執行這個循環體。


import random
temp = input("猜猜我心中的數字:")
guess = int(temp)
secret = random.randint(1,10)
i = 2
while (guess!=secret)and(i):
if (guess < secret):
print("猜小了!")
print("剩余機會次數:",i)
else:
print("猜大了!")
print("剩余機會次數:", i)
temp = input("猜猜我心中的數字:")
guess = int(temp)
i = i - 1

else:
if(i>0):
print("猜對!遊戲結束!")

else:
print("你的機會用完!")



###運行結果:
![image](https://raw.githubusercontent.com/wangshujuan/PostImage/master/PythonBasic1/%E6%8D%95%E8%8E%B73.PNG)

## 4. 總結一下要點
*  在 python 中,while … else 在循環條件為 false 時執行 else 語句塊。
*  Python中的and邏輯運算操作符可以將任意表達式連接在一起,並得到一個布爾類型的值。

Python入門小程序(一)