Python語法

if判斷

if 條件:
    如果條件爲真執行的語句塊
  • 判斷條件:數據類型也可以當作判斷條件。任何值爲0的數字都是假,非0爲真;任何空對象都是假,非空爲真;關鍵字None也表示假
if 'th' in 'python':
    print('yes')

if -0.0:
    print('值爲0表示False')

if 100:
    print('值非0表示真')

if ' ':
    print('空格也是一個字符,爲真')

if '':
    print('長度爲0的字符串,爲假')

if []:
    print('空列表爲假')

if not None:
    print('None爲假,取反爲真')
  • 三元運算符,也叫條件表達式
a = 10
b = 20
# if a < b:
#     s = a
# else:
#     s = b
# print(s)

s = a if a < b else b   # 它是以上註釋部分的簡寫
print(s)
# 模擬登錄腳本
print('plz input your username and password')
user = input('username: ')
passwd = input('password: ')
if user == 'bob' and passwd == '123456':
    print('Login successful!')
else:
    print('Login inorrect!')

擴展if語句

  • 擴展if語句:它是多分支結構,只會執行一個分支
if 條件1:
    條件1爲真才執行的語句
elif 條件2:
    條件2爲真才執行的語句
elif 條件3:
    條件3爲真才執行的語句
... ...
else:
    所有條件都不滿足才執行的語句
# 石頭剪刀布腳本
import random

computer = random.choice(['石頭', '剪刀', '布'])
player = input('請出拳(石頭、剪刀、布): ')
print('你出了%s,計算機出了%s' % (player, computer))

if player == '石頭':
   if computer == '石頭':
       print('平局')
   elif computer == '剪刀':
       print('You Win!!!')
   else:
       print('You Lose!!!')
elif player == '剪刀':
    if computer == '石頭':
        print('平局')
    elif computer == '剪刀':
        print('平局')
    else:
        print('You Win!!!')
else:
    if computer == '石頭':
        print('You Win!!!')
    elif computer == '剪刀':
        print('You Lose!!!')
    else:
        print('平局')

優化:

import random

computer = random.choice(['石頭', '剪刀', '布'])
player = input('請出拳(石頭、剪刀、布): ')
print('你出了%s,電腦出了%s' % (player,computer))
if (computer == '石頭' and player == '布') or (computer == '剪刀' and player == '石頭') or (computer == '布' and player == '剪刀'):
    print('You Win!!!')
elif computer == player:
    print('平局')
else:
    print('You Lose!!!')

再優化:

import random

option = ['石頭', '剪刀', '布']
computer = random.choice(option)
player = int(input('''請出拳:
(0)石頭
(1)剪刀
(2)布'''))
loses = [['石頭', '布'], ['剪刀', '石頭'], ['布', '剪刀']]
print('你出了%s,電腦出了%s' % (option[player],computer))

if [option[player], computer] in loses:
    print('\033[31;1mYou Lose!!!\033[0m')
elif computer == player:
    print('\033[32;1m平局\033[0m')
else:
    print('\033[31;1mYou Win!!!\033[0m')
  • 終端顏色
[root@localhost python01] echo -e "OK"
[root@localhost python01] echo -e "\033[31;1mOK\033[0m"  # 紅色的OK
[root@localhost python01] echo -e "\033[32;1mOK\033[0m"  # 綠色的OK
# 3x是前景色,4x是背景色
[root@localhost python01] echo -e "\033[32;44;1mOK\033[0m"
[root@localhost python01] echo -e "\033[32;5mOK\033[0m"   # 5m文字閃

循環

  • 一組被重複執行的語句稱之爲循環體,能否繼續重複, 決定循環的終止條件
  • Pythonwhile中的循環有循環和for循環
  • 循環次數未知的情況下,建議採用 while循環
  • 循環次數可以預知的情況下,建議採用for循環

1)while

while 條件:
    條件爲真時,執行的語句塊

使用while循環優化石頭剪刀布腳本爲三局兩勝:

import random

option = ['石頭', '剪刀', '布']
pwin = 0
cwin = 0
loses = [['石頭', '布'], ['剪刀', '石頭'], ['布', '剪刀']]

while pwin < 2 and cwin < 2:
    computer = random.choice(option)
    player = int(input('''請出拳:
    (0)石頭
    (1)剪刀
    (2)布'''))

    print('你出了%s,電腦出了%s' % (option[player],computer))

    if [option[player], computer] in loses:
        print('\033[31;1mYou Lose!!!\033[0m')
        cwin += 1
    elif computer == player:
        print('\033[32;1m平局\033[0m')
    else:
        print('\033[31;1mYou Win!!!\033[0m')
        pwin += 1
else:
    if pwin == 2:
        print('\033[32;1mYou won the game!\033[0m')
    else:
        print('\033[31;1mYou lost the game!\033[0m')

循環語句進階

break

  • break語句可以結束循環體然後跳轉到循環之後得語句
  • 寫程序的時候,應儘量避免重複的代碼,在這種情況下可以使用whle- break結構

continue

  • 當遇到continue語句時,程序會終止當前循環,並忽略剩餘的語句,然後開始下一次循環
  • 如果仍然滿足循環條件,循環體內語句繼續執行,否則退出循環
# 求1 - 100 中偶數的和
result = 0
i = 0
while i < 100:
    i += 1
    if i % 2:
        continue
    result += i
print(result)

else

  • python中的 while語句也支持else子句
  • else子句只在循環完成後執行
  • break語句也會跳過else塊
import random

num = random.randint(1, 100)
i = 5

while i > 0:
    c = int(input('請猜數字(1-100): '))
    if 1 <= c <= 100:
        i -= 1
        if c == num:
            print('猜對了')
            break
        elif c > num:
            print('猜大了,你還有%s次機會' % i)
        else:
            print('猜小了,你還有%s次機會' % i)
    else:
        print('輸入有誤')
else:
    print('正確數字爲:%s' % (num))

2)for循環

for 變量 in 對象:
    語句
  • for循環也有break / else / continue,用法與while一樣

range函數

  • 用於產生數字
  • 默認生成一個range對象,取值時它會臨時生成一個數字
>>> range(10)
range(0, 10)
>>> for i in range(10):
>>> list(range(10))   # 10是結束數字,結束數字不包含
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> list(range(6, 10))  # 起始數字從6開始
[6, 7, 8, 9]
>>> list(range(1, 11, 2))
[1, 3, 5, 7, 9]
>>> list(range(10, 0, -1))
[10, 9, 8, 7, 6, 5, 4, 3, 2, 1]

列表解析

  • 生成列表的一種方式
>>> [10]
[10]
>>> [5 + 5]   # 將表達式計算結果放到列表中
[10]
>>> [5 + 5 for i in range(1, 11)]  # 5 + 5計算10次,每次結果放到列表>中
[10, 10, 10, 10, 10, 10, 10, 10, 10, 10]
>>> [5 + i for i in range(1, 11)]  # 表達式可以使用for循環的變量
[6, 7, 8, 9, 10, 11, 12, 13, 14, 15]
# 使用if作爲過濾條件,條件爲真計算表達式
>>> [5 + i for i in range(1, 11) if i % 2 == 0]
[7, 9, 11, 13, 15]
# 生成192.168.1.0網段所有的IP地址
>>> ['192.168.1.%s' % i for i in range(1, 255)]
>>> ['192.168.1.' + str(i) for i in range(1, 255)]
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章