1. 程式人生 > 其它 >控制流程之if判斷與while、for迴圈

控制流程之if判斷與while、for迴圈

一、if判斷

1.什麼是if判斷?

接收使用者輸入的名字

接受使用者輸入的密碼

如果使用者輸入的名字=正確的名字 並且 使用者輸入的密碼=正確的密碼

告訴使用者登入成功

否則,

告訴使用者登入失敗

2.為何要有if判斷?

為了讓計算機像人一樣去判斷

3.如何用if判斷?

完整的語法:

   4、if判斷基本執行原理解析(同上圖)
5、分支結構
5.1.單分支
age=19
is_beautiful=True
gender="male"
if gender=="male" and 18<age<27 and is_beautiful:
    
print("我喜歡你")

5.2.雙分支

age=19
is_beautiful=True
gender="male"
if gender=="male" and 18<age<27 and is_beautiful:
    print("我喜歡你")
else:
    print("我們不合適")
age=19
is_beautiful=True
gender="male"
if gender=="male" and 18<age<27 and is_beautiful:
    print("我喜歡你")
else:
    print("我們不合適")

案列

inp_user = input("請輸入您的使用者名稱:")
inp_pwd = input("請輸入您的密碼:")
if inp_user == "egon" and inp_pwd == "123":
    print("登入成功")
else:
    print("登入失敗")

5.3.多分支

如果:成績>=90,那麼:優秀
如果成績>=80且<90,那麼:良好
如果成績>=70且<80,那麼:普通
其他情況:很差
score = input("請輸入您的分數")
score = int(score)
if score >= 90:
    
print("優秀") elif score >= 80: print("良好") elif score >= 70: print("普通") else: print("很差")
二、while迴圈語法:
 while 條件:
        程式碼1
        程式碼2
        程式碼3

1.基本用法

print('start...')
i = 1
while i <= 5:
     print(i)
     i += 1
print('end...')

2.死迴圈:永不結束的迴圈



while True:
      print(1)


while True:  
    name = input(">> ")
    print(name)

3.結束while迴圈有兩種方式
方式一:把條件改為False, 必須要等到下一次迴圈判斷條件時才能結束迴圈

print('start...')
i = 1

tag = True
while tag:
    if i == 5:
        tag = False
    print(i)
    i += 1
 方式二:break終止本層迴圈,會立即結束while迴圈,根本沒有下一次
print('start...')
i = 1

tag = True
while tag:
    if i == 5:
        break
    print(i)
    i += 1

案例1.

方法一:

tag = True
while tag:
    inp_user = input("請輸入您的使用者名稱:")
    inp_pwd = input("請輸入您的密碼:")

    if inp_user == "egon" and inp_pwd == "123":
        print("登入成功")
        tag = False
    else:
        print("登入失敗")

方法二:

while True:
     inp_user = input("請輸入您的使用者名稱:")
     inp_pwd = input("請輸入您的密碼:")

     if inp_user == "egon" and inp_pwd == "123":
         print("登入成功")
         break
     else:
         print("登入失敗")
案例2
i = 0
while True:
    inp_user = input("請輸入您的使用者名稱:")
    inp_pwd = input("請輸入您的密碼:")
    if inp_user == "egon" and inp_pwd == "123":
        print("登入成功")
        break
    else:
        print("登入失敗")
        i += 1
    if i == 3:
        print("嘗試次數超過了3次,結束")
        break

補充;

while True:
    while True:
        while True:
            break
        break
    break



tag = True
while tag:
    while tag:
        while tag:
            tag = False

4.while+continue: continue終止本次直接進入下一次

i = 1
while i <= 5:
    if i == 3:
        i += 1
        continue
    print(i)
    i += 1
強調:
1、不要在continue後加與continue同級的程式碼,加了就永遠執行不了了
2、迴圈體程式碼的最後一步不要寫continue