Python基礎之分支語句

If語句

If表達式:

表達式成立執行的代碼

需求:擲骰子

1~3 輸出小

4~6 輸出大

import random
# 得到1到6範圍內的隨機數,包括1,6
num = random.randint(1,6)
print(num)
if 1<=num<=3:
    print("小")
if 6>=num>=4:
    print("大")

if 2:
    print("2打印")
if 1:
    print("1打印")
if 0:
    print("0不打印")

比較與邏輯運算符

比較運算符

>

<

>=

<=

==

!=

比較結果:

Bool值

True 、yes、非0

False、no、0

邏輯運算符

And

Or

Not

需求:輸入用戶名密碼,當輸入都正確時,給出成功提示

acc='root'
pwd='123'

aaccount=input("請輸入用戶名")
password=input("請輸入密碼")

if(aaccount==acc and password == pwd):
    print("登錄成功")

if(aaccount!=acc or password != pwd):
    print("用戶名或密碼錯誤")

猜拳遊戲(多分支)

分支語句:

1、單分支

表達式成立執行的代碼

2、雙分支(二選一)

if 表達式:

表達式成立執行的代碼

else:

表達

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章