【Python3】條件語句與循環語句

1 條件語句

  • 例1:
if 條件:
    ...
else:
    ...
  • 應用
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Author:Chuncheng.Fan <xmzncc@gmail.com>

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


if username  == 'fcc' and password == '123':
    print("歡迎登錄!")
else:
    print("用戶名或密碼錯誤!")
  • 例2:
if 條件:
    ...
elif 條件:
    ...
else:
    ...
  • 應用:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Author:Chuncheng.Fan <xmzncc@gmail.com>

sex = input("請輸入你的性別:")

if sex == "男":
    print("傻x,本身性別都忘了!")
elif sex == "女":
    print("...你在想一想,你忘了你已經作了手術了嗎...")
else:
    print("人妖.......")

2 循環語句

  • while
while 條件:
    continue # 開始下一次循環
    break # 跳出全部循環
  • 例:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Author:Chuncheng.Fan <xmzncc@gmail.com>

i = 0
while i < 3:
    username = input("請輸入用戶名:")
    password = input("請輸入密碼:")
    if username == 'fcc' and password == '123':
        print("歡迎登錄!")
        break
    else:
        print('用戶名或密碼錯誤')
        i += 1

3 練習

    1. 使用while循環輸入 1 2 3 4 5 6 8 9 10
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Author:Chuncheng.Fan <xmzncc@gmail.com>

i = 1
while True:
    if i == 7:
        i += 1
        continue
    print(i)
    i += 1
    if i == 11:
        break
    1. 求1-100的全部數的和
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Author:Chuncheng.Fan <xmzncc@gmail.com>

value = 0
i = 1
while i < 101:
    value = value + i
    i += 1
print(value)
    1. 輸出 1-100 內的全部奇數
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Author:Chuncheng.Fan <xmzncc@gmail.com>

i = 1

while i < 101:
    if i % 2 == 1:
        print(i)
    i += 1
    1. 輸出 1-100 內的全部偶數
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Author:Chuncheng.Fan <xmzncc@gmail.com>

i = 1

while i < 101:
    if i % 2 == 0:
        print(i)
    i += 1
    1. 求1-2+3-4+5 ... 99的全部數的和
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Author:Chuncheng.Fan <xmzncc@gmail.com>

value = 0
i = 1

while i < 100:
    if i % 2 == 1:
        value = value + i
        i += 1
    elif i % 2 == 0:
        value = value - i
        i +=1
print(value)
    1. 用戶登錄(三次機會重試)
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Author:Chuncheng.Fan <xmzncc@gmail.com>

i = 0

while i < 3:
    username = input("請輸入用戶名:")
    password = input("請輸入密碼:")
    if username == 'fcc' and password == '123':
        print("歡迎登錄!")
        break
    else:
        print("用戶名或密碼錯誤")
        i += 1
相關文章
相關標籤/搜索