# python if 嵌套語法 ###### tags: `python` `if` `縮排` --- # if 嵌套語法 if 條件1: 條件1成立執行程式1 條件1成立執行程式2 ........ if 條件2: 條件2成立執行程式3 條件2成立執行程式4 ........ **重點提示:條件2的if源於條件1,因此也要一起縮排!** ![](https://i.imgur.com/TPJjDO9.png) --- # 案例1: ## 需求分析 - [ ] 搭高鐵自由座 - [ ] 如果有票可以上車,沒有則不行。 - [ ] 上車如果有座位,可以坐下,沒有就站著。 - [ ] 變數:票,座位 - [ ] 條件判斷: * 有票 : 上車 * 有座位 :坐下 ## 先判斷車票與否 --- ticket = 1 seat = 1 if ticket == 1: print('乘客,請上車') else: print('請先購票再請上車') ![](https://i.imgur.com/BrQtW27.png) --- ## 再判斷座位與否 --- if ticket == 1: print('乘客,請上車') if seat == 1: #判斷是否有位置 print('請坐') else: print('請站著') else: print('請先購票再請上車') ![](https://i.imgur.com/NXcEbI9.png) --- --- ![](https://i.imgur.com/u3Yx9Hf.png) --- # 案例2:猜拳遊戲 ## 需求分析 - [ ] 角色 : * 玩家 : 手動出拳 * 電腦 : * 1.固定 2隨機出拳 - [ ] 條件判斷 : * 玩家獲勝 | 玩家 | 電腦 | | ---- | ---- | | 石頭 | 剪刀 | | 剪刀 | 布 | | 布 | 石頭 | * 平手 玩家和電腦出拳相同 * 電腦獲勝 * ## 電腦固定出拳 --- 出拳 - [ ] 玩家 手動出拳 player = int(input('請出拳: 0:石頭 , 1:剪刀 ,2:布')) - [ ] 電腦 固定出拳 設定 1.剪刀 computer = 1 - [ ] 判斷 - [ ] 玩家獲勝 if ((player == 0)and computer == 1) or ((player == 1)and computer == 2) or ((player == 2)and computer == 0): print('玩家獲勝') - [ ] 平手 elif player == computer: print('平手') else: print('電腦獲勝') --- ![](https://i.imgur.com/IBG8uME.png) --- ## 電腦隨機出拳 ### 使用random 模組 --- - [ ] 導出 random 模組 * 語法 import random - [ ] * 使用 random 模組中的隨機整數功能 * 語法 random.randint(開始,結束) --- --- import random num = random.randint(0, 2) print(num) ![](https://i.imgur.com/g8JSFlU.png) --- import random player = int(input('請出拳: 0:石頭 , 1:剪刀 ,2:布')) computer = random.randint(0, 2) if ((player == 0)and computer == 1) or ((player == 1)and computer == 2) or((player == 2)and computer == 0): print('玩家獲勝') elif player == computer: print('平手') else: print('電腦獲勝') --- ![](https://i.imgur.com/YquhEVi.png)