python入門的120個基礎練習


學習永遠都是“理論”與“實踐”相結合效果最好。

這里有python入門的120個基礎練習(1~40),希望對你有用。

01-Hello World

python的語法邏輯完全靠縮進,建議縮進4個空格。 如果是頂級代碼,那么必須頂格書寫,哪怕只有一個空格也會有語法錯誤。 下面示例中,滿足if條件要輸出兩行內容,這兩行內容必須都縮進,而且具有相同的縮進級別。
1     print('hello world!')
2     
3     if 3 > 0:
4         print('OK')
5         print('yes')
6     
7     x = 3; y = 4   # 不推薦,還是應該寫成兩行
8     print(x + y)

 

 

02-print

1     print('hello world!')
2     print('hello', 'world!')  # 逗號自動添加默認的分隔符:空格
3     print('hello' + 'world!')  # 加號表示字符拼接
4     print('hello', 'world', sep='***')  # 單詞間用***分隔
5     print('#' * 50)  # *號表示重復50遍
6     print('how are you?', end='') # 默認print會打印回車,end=''表示不要回車

 

 

03-基本運算

運算符可以分為:算術運算符、比較運算符和邏輯運算符。優先級是:算術運算符>比較運算符>邏輯運算符。最好使用括號,增加了代碼的可讀性。

1     print(5 / 2)  # 2.5
2     print(5 // 2)  # 丟棄余數,只保留商
3     print(5 % 2)  # 求余數
4     print(5 ** 3)  # 5的3次方
5     print(5 > 3)  # 返回True
6     print(3 > 5)  # 返回False
7     print(20 > 10 > 5)  # python支持連續比較
8     print(20 > 10 and 10 > 5)  # 與上面相同含義
9     print(not 20 > 10)  # False

 

 

04-input

1     number = input("請輸入數字: ")  # input用於獲取鍵盤輸入
2     print(number)
3     print(type(number))  # input獲得的數據是字符型
4     
5     print(number + 10)  # 報錯,不能把字符和數字做運算
6     print(int(number) + 10)  # int可將字符串10轉換成數字10
7     print(number + str(10))  # str將10轉換為字符串后實現字符串拼接

 

 

05-輸入輸出基礎練習

1     username = input('username: ')
2     print('welcome', username)   # print各項間默認以空格作為分隔符
3     print('welcome ' + username)  # 注意引號內最后的空格

 

 

06-字符串使用基礎

python中,單雙引號沒有區別,表示一樣的含義
 1     sentence = 'tom\'s pet is a cat'  # 單引號中間還有單引號,可以轉義
 2     sentence2 = "tom's pet is a cat"  # 也可以用雙引號包含單引號
 3     sentence3 = "tom said:\"hello world!\""
 4     sentence4 = 'tom said:"hello world"'
 5     # 三個連續的單引號或雙引號,可以保存輸入格式,允許輸入多行字符串
 6     words = """
 7     hello
 8     world
 9     abcd"""
10     print(words)
11     
12     py_str = 'python'
13     len(py_str)  # 取長度
14     py_str[0]  # 第一個字符
15     'python'[0]
16     py_str[-1]  # 最后一個字符
17     # py_str[6]  # 錯誤,下標超出范圍
18     py_str[2:4]  # 切片,起始下標包含,結束下標不包含
19     py_str[2:]  # 從下標為2的字符取到結尾
20     py_str[:2]  # 從開頭取到下標是2之前的字符
21     py_str[:]  # 取全部
22     py_str[::2]  # 步長值為2,默認是1
23     py_str[1::2]  # 取出yhn
24     py_str[::-1]  # 步長為負,表示自右向左取
25     
26     py_str + ' is good'  # 簡單的拼接到一起
27     py_str * 3  # 把字符串重復3遍
28     
29     't' in py_str  # True
30     'th' in py_str  # True
31     'to' in py_str  # False
32     'to' not in py_str  # True

 

 

07-列表基礎

列表也是序列對象,但它是容器類型,列表中可以包含各種數據
 1     **alist = [10, 20, 30, 'bob', 'alice', [1,2,3]]
 2     len(alist)
 3     alist[-1]  # 取出最后一項
 4     alist[-1][-1]  # 因為最后一項是列表,列表還可以繼續取下標
 5     [1,2,3][-1]  # [1,2,3]是列表,[-1]表示列表最后一項
 6     alist[-2][2]  # 列表倒數第2項是字符串,再取出字符下標為2的字符
 7     alist[3:5]   # ['bob', 'alice']
 8     10 in alist  # True
 9     'o' in alist  # False
10     100 not in alist # True
11     alist[-1] = 100  # 修改最后一項的值
12     alist.append(200)  # 向**列表中追加一項

 

 

08-元組基礎

元組與列表基本上是一樣的,只是元組不可變,列表可變。
1     atuple = (10, 20, 30, 'bob', 'alice', [1,2,3])
2     len(atuple)
3     10 in atuple
4     atuple[2]
5     atuple[3:5]
6     # atuple[-1] = 100  # 錯誤,元組是不可變的

 

 

09-字典基礎

1     # 字典是key-value(鍵-值)對形式的,沒有順序,通過鍵取出值
2     adict = {'name': 'bob', 'age': 23}
3     len(adict)
4     'bob' in adict  # False
5     'name' in adict  # True
6     adict['email'] = 'bob@tedu.cn'  # 字典中沒有key,則添加新項目
7     adict['age'] = 25  # 字典中已有key,修改對應的value

 

 

10-基本判斷

單個的數據也可作為判斷條件。 任何值為0的數字、空對象都是False,任何非0數字、非空對象都是True。
 1     if 3 > 0:
 2         print('yes')
 3         print('ok')
 4     
 5     if 10 in [10, 20, 30]:
 6         print('ok')
 7     
 8     if -0.0:
 9         print('yes')  # 任何值為0的數字都是False
10     
11     if [1, 2]:
12         print('yes')  # 非空對象都是True
13     
14     if ' ':
15         print('yes')  # 空格字符也是字符,條件為True

 

 

11-條件表達式、三元運算符

 1     a = 10
 2     b = 20
 3     
 4     if a < b:
 5         smaller = a
 6     else:
 7         smaller = b
 8     
 9     print(smaller)
10     
11     s = a if a < b else b  # 和上面的if-else語句等價
12     
13     print(s)

 

 

12-判斷練習:用戶名和密碼是否正確

 1     import getpass  # 導入模塊
 2     
 3     username = input('username: ')
 4     # getpass模塊中,有一個方法也叫getpass
 5     password = getpass.getpass('password: ')
 6     
 7     if username == 'bob' and password == '123456':
 8         print('Login successful')
 9     else:
10         print('Login incorrect')

 

 

13-猜數:基礎實現

 1     import random
 2     
 3     num = random.randint(1, 10) # 隨機生成1-10之間的數字
 4     answer = int(input('guess a number: '))  # 將用戶輸入的字符轉成整數
 5     if answer > num:
 6         print('猜大了')
 7     elif answer < num:
 8         print('猜小了')
 9     else:
10         print('猜對了')
11     
12     print('the number:', num)

 

 

14-成績分類1

 1     score = int(input('分數: '))
 2     
 3     if score >= 90:
 4         print('優秀')
 5     elif score >= 80:
 6         print('')
 7     elif score >= 70:
 8         print('')
 9     elif score >= 60:
10         print('及格')
11     else:
12         print('你要努力了')

 

 

15-成績分類2

 1     score = int(input('分數: '))
 2     
 3     if score >= 60 and score < 70:
 4         print('及格')
 5     elif 70 <= score < 80:
 6         print('')
 7     elif 80 <= score < 90:
 8         print('')
 9     elif score >= 90:
10         print('優秀')
11     else:
12         print('你要努力了')

 

 

16-石頭剪刀布

 1     import random
 2     
 3     all_choices = ['石頭', '剪刀', '']
 4     computer = random.choice(all_choices)
 5     player = input('請出拳: ')
 6     
 7     # print('Your choice:', player, "Computer's choice:", computer)
 8     print("Your choice: %s, Computer's choice: %s" % (player, computer))
 9     if player == '石頭':
10         if computer == '石頭':
11             print('平局')
12         elif computer == '剪刀':
13             print('You WIN!!!')
14         else:
15             print('You LOSE!!!')
16     elif player == '剪刀':
17         if computer == '石頭':
18             print('You LOSE!!!')
19         elif computer == '剪刀':
20             print('平局')
21         else:
22             print('You WIN!!!')
23     else:
24         if computer == '石頭':
25             print('You WIN!!!')
26         elif computer == '剪刀':
27             print('You LOSE!!!')
28         else:
29             print('平局')

 

 

17-改進的石頭剪刀布

 1     import random
 2     
 3     all_choices = ['石頭', '剪刀', '']
 4     win_list = [['石頭', '剪刀'], ['剪刀', ''], ['', '石頭']]
 5     prompt = """(0) 石頭
 6     (1) 剪刀
 7     (2) 布
 8     請選擇(0/1/2): """
 9     computer = random.choice(all_choices)
10     ind = int(input(prompt))
11     player = all_choices[ind]
12     
13     print("Your choice: %s, Computer's choice: %s" % (player, computer))
14     if player == computer:
15         print('\033[32;1m平局\033[0m')
16     elif [player, computer] in win_list:
17         print('\033[31;1mYou WIN!!!\033[0m')
18     else:
19         print('\033[31;1mYou LOSE!!!\033[0m')

 

 

18-猜數,直到猜對

 1     import random
 2     
 3     num = random.randint(1, 10)
 4     running = True
 5     
 6     while running:
 7         answer = int(input('guess the number: '))
 8         if answer > num:
 9             print('猜大了')
10         elif answer < num:
11             print('猜小了')
12         else:
13             print('猜對了')
14             running = False

 

 

19-猜數,5次機會

 1     import random
 2     
 3     num = random.randint(1, 10)
 4     counter = 0
 5     
 6     while counter < 5:
 7         answer = int(input('guess the number: '))
 8         if answer > num:
 9             print('猜大了')
10         elif answer < num:
11             print('猜小了')
12         else:
13             print('猜對了')
14             break
15         counter += 1
16     else:  # 循環被break就不執行了,沒有被break才執行
17         print('the number is:', num)

 

 

20-while循環,累加至100

因為循環次數是已知的,實際使用時,建議用for循環
1     sum100 = 0
2     counter = 1
3     
4     while counter < 101:
5         sum100 += counter
6         counter += 1
7     
8     print(sum100)

 

 

21-while-break

break是結束循環,break之后、循環體內代碼不再執行。
1     while True:
2         yn = input('Continue(y/n): ')
3         if yn in ['n', 'N']:
4             break
5         print('running...')

 

 

22-while-continue

計算100以內偶數之和。
continue是跳過本次循環剩余部分,回到循環條件處。
    sum100 = 0
    counter = 0
    
    while counter < 100:
        counter += 1
        # if counter % 2:
        if counter % 2 == 1:
            continue
        sum100 += counter
    
    print(sum100)

 

 

23-for循環遍歷數據對象

 1     astr = 'hello'
 2     alist = [10, 20, 30]
 3     atuple = ('bob', 'tom', 'alice')
 4     adict = {'name': 'john', 'age': 23}
 5     
 6     for ch in astr:
 7         print(ch)
 8     
 9     for i in alist:
10         print(i)
11     
12     for name in atuple:
13         print(name)
14     
15     for key in adict:
16         print('%s: %s' % (key, adict[key]))

 

 

24-range用法及數字累加

 1     # range(10)  # [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
 2     # >>> list(range(10))
 3     # range(6, 11)  # [6, 7, 8, 9, 10]
 4     # range(1, 10, 2)  # [1, 3, 5, 7, 9]
 5     # range(10, 0, -1)  # [10, 9, 8, 7, 6, 5, 4, 3, 2, 1]
 6     sum100 = 0
 7     
 8     for i in range(1, 101):
 9         sum100 += i
10     
11     print(sum100)

 

 

25-列表實現斐波那契數列

列表中先給定兩個數字,后面的數字總是前兩個數字之和。
1     fib = [0, 1]
2     
3     for i in range(8):
4         fib.append(fib[-1] + fib[-2])
5     
6     print(fib)

 

 

26-九九乘法表

 1     for i in range(1, 10):
 2         for j in range(1, i + 1):
 3             print('%s*%s=%s' % (j, i, i * j), end=' ')
 4         print()
 5     
 6     # i=1 ->j: [1]
 7     # i=2 ->j: [1,2]
 8     # i=3 ->j: [1,2,3]
 9     #由用戶指定相乘到多少
10     n = int(input('number: '))
11     
12     for i in range(1, n + 1):
13         for j in range(1, i + 1):
14             print('%s*%s=%s' % (j, i, i * j), end=' ')
15         print()

 

 

27-逐步實現列表解析

 1     # 10+5的結果放到列表中
 2     [10 + 5]
 3     # 10+5這個表達式計算10次
 4     [10 + 5 for i in range(10)]
 5     # 10+i的i來自於循環
 6     [10 + i for i in range(10)]
 7     [10 + i for i in range(1, 11)]
 8     # 通過if過濾,滿足if條件的才參與10+i的運算
 9     [10 + i for i in range(1, 11) if i % 2 == 1]
10     [10 + i for i in range(1, 11) if i % 2]
11     # 生成IP地址列表
12     ['192.168.1.%s' % i for i in range(1, 255)]

 

 

28-三局兩勝的石頭剪刀布

 1     import random
 2     
 3     all_choices = ['石頭', '剪刀', '']
 4     win_list = [['石頭', '剪刀'], ['剪刀', ''], ['', '石頭']]
 5     prompt = """(0) 石頭
 6     (1) 剪刀
 7     (2) 布
 8     請選擇(0/1/2): """
 9     cwin = 0
10     pwin = 0
11     
12     while cwin < 2 and pwin < 2:
13         computer = random.choice(all_choices)
14         ind = int(input(prompt))
15         player = all_choices[ind]
16     
17         print("Your choice: %s, Computer's choice: %s" % (player, computer))
18         if player == computer:
19             print('\033[32;1m平局\033[0m')
20         elif [player, computer] in win_list:
21             pwin += 1
22             print('\033[31;1mYou WIN!!!\033[0m')
23         else:
24             cwin += 1
25             print('\033[31;1mYou LOSE!!!\033[0m')

 

 

29-文件對象基礎操作

 1     # 文件操作的三個步驟:打開、讀寫、關閉
 2     # cp /etc/passwd /tmp
 3     f = open('/tmp/passwd')  # 默認以r的方式打開純文本文件
 4     data = f.read()  # read()把所有內容讀取出來
 5     print(data)
 6     data = f.read()  # 隨着讀寫的進行,文件指針向后移動。
 7     # 因為第一個f.read()已經把文件指針移動到結尾了,所以再讀就沒有數據了
 8     # 所以data是空字符串
 9     f.close()
10     
11     f = open('/tmp/passwd')
12     data = f.read(4)  # 讀4字節
13     f.readline()  # 讀到換行符\n結束
14     f.readlines()  # 把每一行數據讀出來放到列表中
15     f.close()
16     
17     ################################
18     f = open('/tmp/passwd')
19     for line in f:
20         print(line, end='')
21     f.close()
22     
23     ##############################
24     f = open('圖片地址', 'rb')  # 打開非文本文件要加參數b
25     f.read(4096)
26     f.close()
27     
28     ##################################
29     f = open('/tmp/myfile', 'w')  # 'w'打開文件,如果文件不存在則創建
30     f.write('hello world!\n')
31     f.flush()  # 立即將緩存中的數據同步到磁盤
32     f.writelines(['2nd line.\n', 'new line.\n'])
33     f.close()  # 關閉文件的時候,數據保存到磁盤
34     
35     ##############################
36     with open('/tmp/passwd') as f:
37         print(f.readline())
38     
39     #########################
40     f = open('/tmp/passwd')
41     f.tell()  # 查看文件指針的位置
42     f.readline()
43     f.tell()
44     f.seek(0, 0)  # 第一個數字是偏移量,第2位是數字是相對位置。
45                   # 相對位置0表示開頭,1表示當前,2表示結尾
46     f.tell()
47     f.close()

 

 

30-拷貝文件

拷貝文件就是以r的方式打開源文件,以w的方式打開目標文件,將源文件數據讀出后,寫到目標文件。
以下是【不推薦】的方式,但是可以工作:
1     f1 = open('/bin/ls', 'rb')
2     f2 = open('/root/ls', 'wb')
3     
4     data = f1.read()
5     f2.write(data)
6     
7     f1.close()
8     f2.close()

 

 

31-拷貝文件

每次讀取4K,讀完為止:
 1     src_fname = '/bin/ls'
 2     dst_fname = '/root/ls'
 3     
 4     src_fobj = open(src_fname, 'rb')
 5     dst_fobj = open(dst_fname, 'wb')
 6     
 7     while True:
 8         data = src_fobj.read(4096)
 9         if not data:
10             break
11         dst_fobj.write(data)
12     
13     src_fobj.close()
14     dst_fobj.close()

 

 

32-位置參數

注意:位置參數中的數字是字符形式的
1     import sys
2     
3     print(sys.argv)  # sys.argv是sys模塊里的argv列表
4     
5     # python3 position_args.py
6     # python3 position_args.py 10
7     # python3 position_args.py 10 bob

 

 

33-函數應用-斐波那契數列

 1     def gen_fib(l):
 2         fib = [0, 1]
 3     
 4         for i in range(l - len(fib)):
 5             fib.append(fib[-1] + fib[-2])
 6     
 7         return fib  # 返回列表,不返回變量fib
 8     
 9     a = gen_fib(10)
10     print(a)
11     print('-' * 50)
12     n = int(input("length: "))
13     print(gen_fib(n))  # 不會把變量n傳入,是把n代表的值賦值給形參

 

 

34-函數-拷貝文件

 1     import sys
 2     
 3     def copy(src_fname, dst_fname):
 4         src_fobj = open(src_fname, 'rb')
 5         dst_fobj = open(dst_fname, 'wb')
 6     
 7         while True:
 8             data = src_fobj.read(4096)
 9             if not data:
10                 break
11             dst_fobj.write(data)
12     
13         src_fobj.close()
14         dst_fobj.close()
15     
16     copy(sys.argv[1], sys.argv[2])
17     # 執行方式
18     # cp_func.py /etc/hosts /tmp/zhuji.txt

 

 

35-函數-九九乘法表

1     def mtable(n):
2         for i in range(1, n + 1):
3             for j in range(1, i + 1):
4                 print('%s*%s=%s' % (j, i, i * j), end=' ')
5             print()
6     
7     mtable(6)
8     mtable(9)

 

 

36-模塊基礎

每一個以py作為擴展名的文件都是一個模塊。
 1 star.py:
 2 
 3 
 4     hi = 'hello world!'
 5     
 6     def pstar(n=50):
 7         print('*' * n)
 8     
 9     if __name__ == '__main__':
10         pstar()
11         pstar(30)
12     在call_star.py中調用star模塊:
13     
14     import star
15     
16     print(star.hi)
17     star.pstar()
18     star.pstar(30)

 

 

37-生成密碼/驗證碼

此文件名為: randpass.py
思路:
1、設置一個用於隨機取出字符的基礎字符串,本例使用大小寫字母加數字
2、循環n次,每次隨機取出一個字符
3、將各個字符拼接起來,保存到變量result中
 1     from random import choice
 2     import string
 3     
 4     all_chs = string.ascii_letters + string.digits  # 大小寫字母加數字
 5     
 6     def gen_pass(n=8):
 7         result = ''
 8     
 9         for i in range(n):
10             ch = choice(all_chs)
11             result += ch
12     
13         return result
14     
15     if __name__ == '__main__':
16         print(gen_pass())
17         print(gen_pass(4))
18         print(gen_pass(10))

 

 

38-序列對象方法

 1     from random import randint
 2     
 3     alist = list()  # []
 4     list('hello')  # ['h', 'e', 'l', 'l', 'o']
 5     list((10, 20, 30))  # [10, 20, 30]  元組轉列表
 6     astr = str()  # ''
 7     str(10)  # '10'
 8     str(['h', 'e', 'l', 'l', 'o'])  # 將列表轉成字符串
 9     atuple = tuple()  # ()
10     tuple('hello')  # ('h', 'e', 'l', 'l', 'o')
11     num_list = [randint(1, 100) for i in range(10)]
12     max(num_list)
13     min(num_list)

 

 

39-序列對象方法2

 1     alist = [10, 'john']
 2     # list(enumerate(alist))  # [(0, 10), (1, 'john')]
 3     # a, b = 0, 10   # a->0  ->10
 4     
 5     for ind in range(len(alist)):
 6         print('%s: %s' % (ind, alist[ind]))
 7     
 8     for item in enumerate(alist):
 9         print('%s: %s' % (item[0], item[1]))
10     
11     for ind, val in enumerate(alist):
12         print('%s: %s' % (ind, val))
13     
14     atuple = (96, 97, 40, 75, 58, 34, 69, 29, 66, 90)
15     sorted(atuple)
16     sorted('hello')
17     for i in reversed(atuple):
18         print(i, end=',')

 

 

40-字符串方法

 1     py_str = 'hello world!'
 2     py_str.capitalize()
 3     py_str.title()
 4     py_str.center(50)
 5     py_str.center(50, '#')
 6     py_str.ljust(50, '*')
 7     py_str.rjust(50, '*')
 8     py_str.count('l')  # 統計l出現的次數
 9     py_str.count('lo')
10     py_str.endswith('!')  # 以!結尾嗎?
11     py_str.endswith('d!')
12     py_str.startswith('a')  # 以a開頭嗎?
13     py_str.islower()  # 字母都是小寫的?其他字符不考慮
14     py_str.isupper()  # 字母都是大寫的?其他字符不考慮
15     'Hao123'.isdigit()  # 所有字符都是數字嗎?
16     'Hao123'.isalnum()  # 所有字符都是字母數字?
17     '  hello\t    '.strip()  # 去除兩端空白字符,常用
18     '  hello\t    '.lstrip()
19     '  hello\t    '.rstrip()
20     'how are you?'.split()
21     'hello.tar.gz'.split('.')
22     '.'.join(['hello', 'tar', 'gz'])
23     '-'.join(['hello', 'tar', 'gz'])

 

41-字符串格式化

 1     "%s is %s years old" % ('bob', 23)  # 常用
 2     "%s is %d years old" % ('bob', 23)  # 常用
 3     "%s is %d years old" % ('bob', 23.5)  # %d是整數 常用
 4     "%s is %f years old" % ('bob', 23.5)
 5     "%s is %5.2f years old" % ('bob', 23.5)  # %5.2f是寬度為5,2位小數
 6     "97 is %c" % 97
 7     "11 is %#o" % 11  # %#o表示有前綴的8進制
 8     "11 is %#x" % 11
 9     "%10s%5s" % ('name', 'age')  # %10s表示總寬度為10,右對齊, 常用
10     "%10s%5s" % ('bob', 25)
11     "%10s%5s" % ('alice', 23)
12     "%-10s%-5s" % ('name', 'age')  # %-10s表示左對齊, 常用
13     "%-10s%-5s" % ('bob', 25)
14     "%10d" % 123
15     "%010d" % 123
16     
17     "{} is {} years old".format('bob', 25)
18     "{1} is {0} years old".format(25, 'bob')
19     "{:<10}{:<8}".format('name', 'age')

 

 

42-shutil模塊常用方法

 1     import shutil
 2     
 3     with open('/etc/passwd', 'rb') as sfobj:
 4         with open('/tmp/mima.txt', 'wb') as dfobj:
 5             shutil.copyfileobj(sfobj, dfobj) # 拷貝文件對象
 6     
 7     shutil.copyfile('/etc/passwd', '/tmp/mima2.txt')
 8     shutil.copy('/etc/shadow', '/tmp/')  # cp /etc/shadow /tmp/
 9     shutil.copy2('/etc/shadow', '/tmp/')  # cp -p /etc/shadow /tmp/
10     shutil.move('/tmp/mima.txt', '/var/tmp/')  # mv /tmp/mima.txt /var/tmp/
11     shutil.copytree('/etc/security', '/tmp/anquan') # cp -r /etc/security /tmp/anquan
12     shutil.rmtree('/tmp/anquan')  # rm -rf /tmp/anquan
13     # 將mima2.txt的權限設置成與/etc/shadow一樣
14     shutil.copymode('/etc/shadow', '/tmp/mima2.txt')
15     # 將mima2.txt的元數據設置成與/etc/shadow一樣
16     # 元數據使用stat /etc/shadow查看
17     shutil.copystat('/etc/shadow', '/tmp/mima2.txt')
18     shutil.chown('/tmp/mima2.txt', user='zhangsan', group='zhangsan')

 

 

43-練習:生成文本文件

 1     import os
 2     
 3     def get_fname():
 4         while True:
 5             fname = input('filename: ')
 6             if not os.path.exists(fname):
 7                 break
 8             print('%s already exists. Try again' % fname)
 9     
10         return fname
11     
12     def get_content():
13         content = []
14         print('輸入數據,輸入end結束')
15         while True:
16             line = input('> ')
17             if line == 'end':
18                 break
19             content.append(line)
20     
21         return content
22     
23     def wfile(fname, content):
24         with open(fname, 'w') as fobj:
25             fobj.writelines(content)
26     
27     if __name__ == '__main__':
28         fname = get_fname()
29         content = get_content()
30         content = ['%s\n' % line for line in content]
31         wfile(fname, content)

 

 

44-列表方法

 1     alist = [1, 2, 3, 'bob', 'alice']
 2     alist[0] = 10
 3     alist[1:3] = [20, 30]
 4     alist[2:2] = [22, 24, 26, 28]
 5     alist.append(100)
 6     alist.remove(24)  # 刪除第一個24
 7     alist.index('bob')  # 返回下標
 8     blist = alist.copy()  # 相當於blist = alist[:]
 9     alist.insert(1, 15)  # 向下標為1的位置插入數字15
10     alist.pop()  # 默認彈出最后一項
11     alist.pop(2) # 彈出下標為2的項目
12     alist.pop(alist.index('bob'))
13     alist.sort()
14     alist.reverse()
15     alist.count(20)  # 統計20在列表中出現的次數
16     alist.clear()  # 清空
17     alist.append('new')
18     alist.extend('new')
19     alist.extend(['hello', 'world', 'hehe'])

 

 

45-檢查合法標識符

    import sys
    import keyword
    import string
    
    first_chs = string.ascii_letters + '_'
    all_chs = first_chs + string.digits
    
    def check_id(idt):
        if keyword.iskeyword(idt):
            return "%s is keyword" % idt
    
        if idt[0] not in first_chs:
            return "1st invalid"
    
        for ind, ch in enumerate(idt[1:]):
            if ch not in all_chs:
                return "char in postion #%s invalid" % (ind + 2)
    
        return "%s is valid" % idt
    
    
    if __name__ == '__main__':
        print(check_id(sys.argv[1]))  # python3 checkid.py abc@123

 

 

46-創建用戶,設置隨機密碼

randpass模塊參見《37-生成密碼/驗證碼》
 1     import subprocess
 2     import sys
 3     from randpass import gen_pass
 4     
 5     def adduser(username, password, fname):
 6         data = """user information:
 7     %s: %s
 8     """
 9         subprocess.call('useradd %s' % username, shell=True)
10         subprocess.call(
11             'echo %s | passwd --stdin %s' % (password, username),
12             shell=True
13         )
14         with open(fname, 'a') as fobj:
15             fobj.write(data % (username, password))
16     
17     if __name__ == '__main__':
18         username = sys.argv[1]
19         password = gen_pass()
20         adduser(username, password, '/tmp/user.txt')
21     # python3 adduser.py john

 

 

 

47-列表練習:模擬棧操作

 1     stack = []
 2     
 3     def push_it():
 4         item = input('item to push: ')
 5         stack.append(item)
 6     
 7     def pop_it():
 8         if stack:
 9             print("from stack popped %s" % stack.pop())
10     
11     def view_it():
12         print(stack)
13     
14     def show_menu():
15         cmds = {'0': push_it, '1': pop_it, '2': view_it}  # 將函數存入字典
16         prompt = """(0) push it
17     (1) pop it
18     (2) view it
19     (3) exit
20     Please input your choice(0/1/2/3): """
21     
22         while True:
23             # input()得到字符串,用strip()去除兩端空白,再取下標為0的字符
24             choice = input(prompt).strip()[0]
25             if choice not in '0123':
26                 print('Invalid input. Try again.')
27                 continue
28     
29             if choice == '3':
30                 break
31     
32             cmds[choice]()
33     
34     
35     if __name__ == '__main__':
36         show_menu()

 

 

48-實現Linux系統中unix2dos功能

 1     import sys
 2     
 3     def unix2dos(fname):
 4         dst_fname = fname + '.txt'
 5     
 6         with open(fname) as src_fobj:
 7             with open(dst_fname, 'w') as dst_fobj:
 8                 for line in src_fobj:
 9                     line = line.rstrip() + '\r\n'
10                     dst_fobj.write(line)
11     
12     
13     if __name__ == '__main__':
14         unix2dos(sys.argv[1])

 

 

49-動畫程序:@從一行#中穿過

\r是回車不換行
 1     import time
 2     
 3     length = 19
 4     count = 0
 5     
 6     while True:
 7         print('\r%s@%s' % ('#' * count, '#' * (length - count)), end='')
 8         try:
 9             time.sleep(0.3)
10         except KeyboardInterrupt:
11             print('\nBye-bye')
12             break
13         if count == length:
14             count = 0
15         count += 1

 

 

 

50-字典基礎用法

 1     adict = dict()  # {}
 2     dict(['ab', 'cd'])
 3     bdict = dict([('name', 'bob'),('age', 25)])
 4     {}.fromkeys(['zhangsan', 'lisi', 'wangwu'], 11)
 5     
 6     for key in bdict:
 7         print('%s: %s' % (key, bdict[key]))
 8     
 9     print("%(name)s: %(age)s" % bdict)
10     
11     bdict['name'] = 'tom'
12     bdict['email'] = 'tom@tedu.cn'
13     
14     del bdict['email']
15     bdict.pop('age')
16     bdict.clear()

 

 

51-字典常用方法

 1     adict = dict([('name', 'bob'),('age', 25)])
 2     len(adict)
 3     hash(10)  # 判斷給定的數據是不是不可變的,不可變數據才能作為key
 4     adict.keys()
 5     adict.values()
 6     adict.items()
 7     # get方法常用,重要
 8     adict.get('name')  # 取出字典中name對應的value,如果沒有返回None
 9     print(adict.get('qq'))  # None
10     print(adict.get('qq', 'not found'))  # 沒有qq,返回指定內容
11     print(adict.get('age', 'not found'))
12     adict.update({'phone': '13455667788'})

 

 

52-集合常用方法

 1 # 集合相當於是無值的字典,所以也用{}表示
 2     myset = set('hello')
 3     len(myset)
 4     for ch in myset:
 5         print(ch)
 6     
 7     aset = set('abc')
 8     bset = set('cde')
 9     aset & bset  # 交集
10     aset.intersection(bset)  # 交集
11     aset | bset  # 並集
12     aset.union(bset)  # 並集
13     aset - bset  # 差補
14     aset.difference(bset)  # 差補
15     aset.add('new')
16     aset.update(['aaa', 'bbb'])
17     aset.remove('bbb')
18     cset = set('abcde')
19     dset = set('bcd')
20     cset.issuperset(dset)  # cset是dset的超集么?
21     cset.issubset(dset)  # cset是dset的子集么?

 

 

53-集合實例:取出第二個文件有,第一個文件沒有的行

 1     # cp /etc/passwd .
 2     # cp /etc/passwd mima
 3     # vim mima  -> 修改,與passwd有些區別
 4     
 5     with open('passwd') as fobj:
 6         aset = set(fobj)
 7     
 8     with open('mima') as fobj:
 9         bset = set(fobj)
10     
11     with open('diff.txt', 'w') as fobj:
12         fobj.writelines(bset - aset)

 

 

 

54-字典練習:模擬注冊/登陸

 1     import getpass
 2     
 3     userdb = {}
 4     
 5     def register():
 6         username = input('username: ')
 7         if username in userdb:
 8             print('%s already exists.' % username)
 9         else:
10             password = input('password: ')
11             userdb[username] = password
12     
13     def login():
14         username = input('username: ')
15         password = getpass.getpass("password: ")
16         if userdb.get(username) != password:
17             print('login failed')
18         else:
19             print('login successful')
20     
21     
22     def show_menu():
23         cmds = {'0': register, '1': login}
24         prompt = """(0) register
25     (1) login
26     (2) exit
27     Please input your choice(0/1/2): """
28     
29         while True:
30             choice = input(prompt).strip()[0]
31             if choice not in '012':
32                 print('Invalid inupt. Try again.')
33                 continue
34             if choice == '2':
35                 break
36     
37             cmds[choice]()
38     
39     if __name__ == '__main__':
40         show_menu()

 

 

 

55-計算千萬次加法運算時間

1     import time
2     
3     result = 0
4     start = time.time()  # 返回運算前時間戳
5     for i in range(10000000):
6         result += i
7     end = time.time()   # 返回運算后時間戳
8     print(result)
9     print(end - start)

 

 

56-時間相關模塊常用方法

 1     import time
 2     
 3     t = time.localtime()  # 返回當前時間的九元組
 4     time.gmtime()  # 返回格林威治0時區當前時間的九元組
 5     time.time()  # 常用,與1970-1-1 8:00之間的秒數,時間戳
 6     time.mktime(t)  # 把九元組時間轉成時間戳
 7     time.sleep(1)
 8     time.asctime()  # 如果有參數,是九元組形式
 9     time.ctime()  # 返回當前時間,參數是時間戳,常用
10     time.strftime("%Y-%m-%d") # 常用
11     time.strptime('2018-07-20', "%Y-%m-%d")  # 返回九元組時間格式
12     time.strftime('%H:%M:%S')
13     
14     ###########################################
15     from datetime import datetime
16     from datetime import timedelta
17     datetime.today()  # 返回當前時間的datetime對象
18     datetime.now()  # 同上,可以用時區作參數
19     datetime.strptime('2018/06/30', '%Y/%m/%d')  # 返回datetime對象
20     dt = datetime.today()
21     datetime.ctime(dt)
22     datetime.strftime(dt, "%Y%m%d")
23     
24     days = timedelta(days=90, hours=3)  # 常用
25     dt2 = dt + days
26     dt2.year
27     dt2.month
28     dt2.day
29     dt2.hour

 

57-os模塊常用方法

 1     import os
 2     
 3     os.getcwd()  # 顯示當前路徑
 4     os.listdir()  # ls -a
 5     os.listdir('/tmp')  # ls -a /tmp
 6     os.mkdir('/tmp/mydemo')  # mkdir /tmp/mydemo
 7     os.chdir('/tmp/mydemo')  # cd /tmp/mydemo
 8     os.listdir()
 9     os.mknod('test.txt')  # touch test.txt
10     os.symlink('/etc/hosts', 'zhuji')  # ln -s /etc/hosts zhuji
11     os.path.isfile('test.txt')  # 判斷test.txt是不是文件
12     os.path.islink('zhuji')  # 判斷zhuji是不是軟鏈接
13     os.path.isdir('/etc')
14     os.path.exists('/tmp')  # 判斷是否存在
15     os.path.basename('/tmp/abc/aaa.txt')
16     os.path.dirname('/tmp/abc/aaa.txt')
17     os.path.split('/tmp/abc/aaa.txt')
18     os.path.join('/home/tom', 'xyz.txt')
19     os.path.abspath('test.txt')  # 返回當前目錄test.txt的絕對路徑

 

 

58-pickle存儲器

 1     import pickle
 2     """以前的文件寫入,只能寫入字符串,如果希望把任意數據對象(數字、列表等)寫入文件,
 3     取出來的時候數據類型不變,就用到pickle了
 4     """
 5     
 6     # shop_list = ["eggs", "apple", "peach"]
 7     # with open('/tmp/shop.data', 'wb') as fobj:
 8     #     pickle.dump(shop_list, fobj)
 9     
10     with open('/tmp/shop.data', 'rb') as fobj:
11         mylist = pickle.load(fobj)
12     
13     print(mylist[0], mylist[1], mylist[2])

 

 

59-異常處理基礎

 1     try:   # 把有可能發生異常的語句放到try里執行
 2         n = int(input("number: "))
 3         result = 100 / n
 4         print(result)
 5     except ValueError:
 6         print('invalid number')
 7     except ZeroDivisionError:
 8         print('0 not allowed')
 9     except KeyboardInterrupt:
10         print('Bye-bye')
11     except EOFError:
12         print('Bye-bye')
13     
14     print('Done')

 

 

60-異常處理完整語法

 1     try:
 2         n = int(input("number: "))
 3         result = 100 / n
 4     except (ValueError, ZeroDivisionError):
 5         print('invalid number')
 6     except (KeyboardInterrupt, EOFError):
 7         print('\nBye-bye')
 8     else:
 9         print(result)  # 異常不發生時才執行else子句
10     finally:
11         print('Done')  # 不管異常是否發生都必須執行的語句
12     
13     # 常用形式有try-except和try-finally

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM