python入門的120個基礎練習,小白入門必看??!

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

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

01-Hello World

python的語法邏輯完全靠縮進,建議縮進4個空格。 如果是頂級代碼,那么必須頂格書寫,哪怕只有一個空格也會有語法錯誤。 下面示例中,滿足if條件要輸出兩行內容,這兩行內容必須都縮進,而且具有相同的縮進級別。

print('hello world!')

if 3 > 0:

print('OK')

print('yes')

x = 3; y = 4 # 不推薦,還是應該寫成兩行

print(x + y)

02-print

print('hello world!')

print('hello', 'world!') # 逗號自動添加默認的分隔符:空格

print('hello' + 'world!') # 加號表示字符拼接

print('hello', 'world', sep='') # 單詞間用分隔

print('#' * 50) # *號表示重復50遍

print('how are you?', end='') # 默認print會打印回車,end=''表示不要回車

03-基本運算

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

print(5 / 2) # 2.5

print(5 // 2) # 丟棄余數(shù),只保留商

print(5 % 2) # 求余數(shù)

print(5 ** 3) # 5的3次方

print(5 > 3) # 返回True

print(3 > 5) # 返回False

print(20 > 10 > 5) # python支持連續(xù)比較

print(20 > 10 and 10 > 5) # 與上面相同含義

print(not 20 > 10) # False

04-input

number = input("請輸入數(shù)字: ") # input用于獲取鍵盤輸入

print(number)

print(type(number)) # input獲得的數(shù)據(jù)是字符型

print(number + 10) # 報錯,不能把字符和數(shù)字做運算

print(int(number) + 10) # int可將字符串10轉換成數(shù)字10

print(number + str(10)) # str將10轉換為字符串后實現(xiàn)字符串拼接

05-輸入輸出基礎練習

username = input('username: ')

print('welcome', username) # print各項間默認以空格作為分隔符

print('welcome ' + username) # 注意引號內最后的空格

06-字符串使用基礎

python中,單雙引號沒有區(qū)別,表示一樣的含義

sentence = 'tom's pet is a cat' # 單引號中間還有單引號,可以轉義

sentence2 = "tom's pet is a cat" # 也可以用雙引號包含單引號

sentence3 = "tom said:"hello world!""

sentence4 = 'tom said:"hello world"'

三個連續(xù)的單引號或雙引號,可以保存輸入格式,允許輸入多行字符串

words = """

hello

world

abcd"""

print(words)

py_str = 'python'

len(py_str) # 取長度

py_str[0] # 第一個字符

'python'[0]

py_str[-1] # 最后一個字符

py_str[6] # 錯誤,下標超出范圍

py_str[2:4] # 切片,起始下標包含,結束下標不包含

py_str[2:] # 從下標為2的字符取到結尾

py_str[:2] # 從開頭取到下標是2之前的字符

py_str[:] # 取全部

py_str[::2] # 步長值為2,默認是1

py_str[1::2] # 取出yhn

py_str[::-1] # 步長為負,表示自右向左取

py_str + ' is good' # 簡單的拼接到一起

py_str * 3 # 把字符串重復3遍

't' in py_str # True

'th' in py_str # True

'to' in py_str # False

'to' not in py_str # True

07-列表基礎

列表也是序列對象,但它是容器類型,列表中可以包含各種數(shù)據(jù)

**alist = [10, 20, 30, 'bob', 'alice', [1,2,3]]

len(alist)

alist[-1] # 取出最后一項

alist[-1][-1] # 因為最后一項是列表,列表還可以繼續(xù)取下標

[1,2,3][-1] # [1,2,3]是列表,[-1]表示列表最后一項

alist[-2][2] # 列表倒數(shù)第2項是字符串,再取出字符下標為2的字符

alist[3:5] # ['bob', 'alice']

10 in alist # True

'o' in alist # False

100 not in alist # True

alist[-1] = 100 # 修改最后一項的值

alist.append(200) # 向**列表中追加一項

08-元組基礎

元組與列表基本上是一樣的,只是元組不可變,列表可變。

atuple = (10, 20, 30, 'bob', 'alice', [1,2,3])

len(atuple)

10 in atuple

atuple[2]

atuple[3:5]

atuple[-1] = 100 # 錯誤,元組是不可變的

09-字典基礎

字典是key-value(鍵-值)對形式的,沒有順序,通過鍵取出值

adict = {'name': 'bob', 'age': 23}

len(adict)

'bob' in adict # False

'name' in adict # True

adict['email'] = 'bob@tedu.cn' # 字典中沒有key,則添加新項目

adict['age'] = 25 # 字典中已有key,修改對應的value

10-基本判斷

單個的數(shù)據(jù)也可作為判斷條件。 任何值為0的數(shù)字、空對象都是False,任何非0數(shù)字、非空對象都是True。

if 3 > 0:

print('yes')

print('ok')

if 10 in [10, 20, 30]:

print('ok')

if -0.0:

print('yes')  # 任何值為0的數(shù)字都是False

if [1, 2]:

print('yes')  # 非空對象都是True

if ' ':

print('yes')  # 空格字符也是字符,條件為True

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

a = 10

b = 20

if a < b:

smaller = a

else:

smaller = b

print(smaller)

s = a if a < b else b # 和上面的if-else語句等價

print(s)

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

import getpass # 導入模塊

username = input('username: ')

getpass模塊中,有一個方法也叫getpass

password = getpass.getpass('password: ')

if username == 'bob' and password == '123456':

print('Login successful')

else:

print('Login incorrect')

13-猜數(shù):基礎實現(xiàn)

import random

num = random.randint(1, 10) # 隨機生成1-10之間的數(shù)字

answer = int(input('guess a number: ')) # 將用戶輸入的字符轉成整數(shù)

if answer > num:

print('猜大了')

elif answer < num:

print('猜小了')

else:

print('猜對了')

print('the number:', num)

14-成績分類1

score = int(input('分數(shù): '))

if score >= 90:

print('優(yōu)秀')

elif score >= 80:

print('好')

elif score >= 70:

print('良')

elif score >= 60:

print('及格')

else:

print('你要努力了')

15-成績分類2

score = int(input('分數(shù): '))

if score >= 60 and score < 70:

print('及格')

elif 70 <= score < 80:

print('良')

elif 80 <= score < 90:

print('好')

elif score >= 90:

print('優(yōu)秀')

else:

print('你要努力了')

16-石頭剪刀布

import random

all_choices = ['石頭', '剪刀', '布']

computer = random.choice(all_choices)

player = input('請出拳: ')

print('Your choice:', player, "Computer's choice:", computer)

print("Your choice: %s, Computer's choice: %s" % (player, computer))

if player == '石頭':

if computer == '石頭':

    print('平局')

elif computer == '剪刀':

    print('You WIN!!!')

else:

    print('You LOSE!!!')

elif player == '剪刀':

if computer == '石頭':

    print('You LOSE!!!')

elif computer == '剪刀':

    print('平局')

else:

    print('You WIN!!!')

else:

if computer == '石頭':

    print('You WIN!!!')

elif computer == '剪刀':

    print('You LOSE!!!')

else:

    print('平局')

17-改進的石頭剪刀布

import random

all_choices = ['石頭', '剪刀', '布']

win_list = [['石頭', '剪刀'], ['剪刀', '布'], ['布', '石頭']]

prompt = """(0) 石頭

(1) 剪刀

(2) 布

請選擇(0/1/2): """

computer = random.choice(all_choices)

ind = int(input(prompt))

player = all_choices[ind]

print("Your choice: %s, Computer's choice: %s" % (player, computer))

if player == computer:

print('\033[32;1m平局\033[0m')

elif [player, computer] in win_list:

print('\033[31;1mYou WIN!!!\033[0m')

else:

print('\033[31;1mYou LOSE!!!\033[0m')

18-猜數(shù),直到猜對

import random

num = random.randint(1, 10)

running = True

while running:

answer = int(input('guess the number: '))

if answer > num:

    print('猜大了')

elif answer < num:

    print('猜小了')

else:

    print('猜對了')

    running = False

19-猜數(shù),5次機會

import random

num = random.randint(1, 10)

counter = 0

while counter < 5:

answer = int(input('guess the number: '))

if answer > num:

    print('猜大了')

elif answer < num:

    print('猜小了')

else:

    print('猜對了')

    break

counter += 1

else: # 循環(huán)被break就不執(zhí)行了,沒有被break才執(zhí)行

print('the number is:', num)

20-while循環(huán),累加至100

因為循環(huán)次數(shù)是已知的,實際使用時,建議用for循環(huán)

sum100 = 0

counter = 1

while counter < 101:

sum100 += counter

counter += 1

print(sum100)

21-while-break

break是結束循環(huán),break之后、循環(huán)體內代碼不再執(zhí)行。

while True:

yn = input('Continue(y/n): ')

if yn in ['n', 'N']:

    break

print('running...')

22-while-continue

計算100以內偶數(shù)之和。 continue是跳過本次循環(huán)剩余部分,回到循環(huán)條件處。

sum100 = 0

counter = 0

while counter < 100:

counter += 1

# if counter % 2:

if counter % 2 == 1:

    continue

sum100 += counter

print(sum100)

23-for循環(huán)遍歷數(shù)據(jù)對象

astr = 'hello'

alist = [10, 20, 30]

atuple = ('bob', 'tom', 'alice')

adict = {'name': 'john', 'age': 23}

for ch in astr:

print(ch)

for i in alist:

print(i)

for name in atuple:

print(name)

for key in adict:

print('%s: %s' % (key, adict[key]))

24-range用法及數(shù)字累加

range(10) # [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

>>> list(range(10))

range(6, 11) # [6, 7, 8, 9, 10]

range(1, 10, 2) # [1, 3, 5, 7, 9]

range(10, 0, -1) # [10, 9, 8, 7, 6, 5, 4, 3, 2, 1]

sum100 = 0

for i in range(1, 101):

sum100 += i

print(sum100)

25-列表實現(xiàn)斐波那契數(shù)列

列表中先給定兩個數(shù)字,后面的數(shù)字總是前兩個數(shù)字之和。

fib = [0, 1]

for i in range(8):

fib.append(fib[-1] + fib[-2])

print(fib)

26-九九乘法表

for i in range(1, 10):

for j in range(1, i + 1):

    print('%s*%s=%s' % (j, i, i * j), end=' ')

print()

i=1 ->j: [1]

i=2 ->j: [1,2]

i=3 ->j: [1,2,3]

#由用戶指定相乘到多少

n = int(input('number: '))

for i in range(1, n + 1):

for j in range(1, i + 1):

    print('%s*%s=%s' % (j, i, i * j), end=' ')

print()

27-逐步實現(xiàn)列表解析

10+5的結果放到列表中

[10 + 5]

10+5這個表達式計算10次

[10 + 5 for i in range(10)]

10+i的i來自于循環(huán)

[10 + i for i in range(10)]

[10 + i for i in range(1, 11)]

通過if過濾,滿足if條件的才參與10+i的運算

[10 + i for i in range(1, 11) if i % 2 == 1]

[10 + i for i in range(1, 11) if i % 2]

生成IP地址列表

['192.168.1.%s' % i for i in range(1, 255)]

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

import random

all_choices = ['石頭', '剪刀', '布']

win_list = [['石頭', '剪刀'], ['剪刀', '布'], ['布', '石頭']]

prompt = """(0) 石頭

(1) 剪刀

(2) 布

請選擇(0/1/2): """

cwin = 0

pwin = 0

while cwin < 2 and pwin < 2:

computer = random.choice(all_choices)

ind = int(input(prompt))

player = all_choices[ind]

print("Your choice: %s, Computer's choice: %s" % (player, computer))

if player == computer:

    print('\033[32;1m平局\033[0m')

elif [player, computer] in win_list:

    pwin += 1

    print('\033[31;1mYou WIN!!!\033[0m')

else:

    cwin += 1

    print('\033[31;1mYou LOSE!!!\033[0m')

29-文件對象基礎操作

文件操作的三個步驟:打開、讀寫、關閉

cp /etc/passwd /tmp

f = open('/tmp/passwd') # 默認以r的方式打開純文本文件

data = f.read() # read()把所有內容讀取出來

print(data)

data = f.read() # 隨著讀寫的進行,文件指針向后移動。

因為第一個f.read()已經(jīng)把文件指針移動到結尾了,所以再讀就沒有數(shù)據(jù)了

所以data是空字符串

f.close()

f = open('/tmp/passwd')

data = f.read(4) # 讀4字節(jié)

f.readline() # 讀到換行符\n結束

f.readlines() # 把每一行數(shù)據(jù)讀出來放到列表中

f.close()

################################

f = open('/tmp/passwd')

for line in f:

print(line, end='')

f.close()

##############################

f = open('圖片地址', 'rb') # 打開非文本文件要加參數(shù)b

f.read(4096)

f.close()

##################################

f = open('/tmp/myfile', 'w') # 'w'打開文件,如果文件不存在則創(chuàng)建

f.write('hello world!\n')

f.flush() # 立即將緩存中的數(shù)據(jù)同步到磁盤

f.writelines(['2nd line.\n', 'new line.\n'])

f.close() # 關閉文件的時候,數(shù)據(jù)保存到磁盤

##############################

with open('/tmp/passwd') as f:

print(f.readline())

#########################

f = open('/tmp/passwd')

f.tell() # 查看文件指針的位置

f.readline()

f.tell()

f.seek(0, 0) # 第一個數(shù)字是偏移量,第2位是數(shù)字是相對位置。

          # 相對位置0表示開頭,1表示當前,2表示結尾

f.tell()

f.close()

30-拷貝文件

拷貝文件就是以r的方式打開源文件,以w的方式打開目標文件,將源文件數(shù)據(jù)讀出后,寫到目標文件。 以下是【不推薦】的方式,但是可以工作:

f1 = open('/bin/ls', 'rb')

f2 = open('/root/ls', 'wb')

data = f1.read()

f2.write(data)

f1.close()

f2.close()

31-拷貝文件

每次讀取4K,讀完為止:

src_fname = '/bin/ls'

dst_fname = '/root/ls'

src_fobj = open(src_fname, 'rb')

dst_fobj = open(dst_fname, 'wb')

while True:

data = src_fobj.read(4096)

if not data:

    break

dst_fobj.write(data)

src_fobj.close()

dst_fobj.close()

32-位置參數(shù)

注意:位置參數(shù)中的數(shù)字是字符形式的

import sys

print(sys.argv) # sys.argv是sys模塊里的argv列表

python3 position_args.py

python3 position_args.py 10

python3 position_args.py 10 bob

33-函數(shù)應用-斐波那契數(shù)列

def gen_fib(l):

fib = [0, 1]

for i in range(l - len(fib)):

    fib.append(fib[-1] + fib[-2])

return fib  # 返回列表,不返回變量fib

a = gen_fib(10)

print(a)

print('-' * 50)

n = int(input("length: "))

print(gen_fib(n)) # 不會把變量n傳入,是把n代表的值賦值給形參

34-函數(shù)-拷貝文件

import sys

def copy(src_fname, dst_fname):

src_fobj = open(src_fname, 'rb')

dst_fobj = open(dst_fname, 'wb')

while True:

    data = src_fobj.read(4096)

    if not data:

        break

    dst_fobj.write(data)

src_fobj.close()

dst_fobj.close()

copy(sys.argv[1], sys.argv[2])

執(zhí)行方式

cp_func.py /etc/hosts /tmp/zhuji.txt

35-函數(shù)-九九乘法表

def mtable(n):

for i in range(1, n + 1):

    for j in range(1, i + 1):

        print('%s*%s=%s' % (j, i, i * j), end=' ')

    print()

mtable(6)

mtable(9)

36-模塊基礎

每一個以py作為擴展名的文件都是一個模塊。

star.py:

hi = 'hello world!'

def pstar(n=50):

print('*' * n)

if name == 'main':

pstar()

pstar(30)

在call_star.py中調用star模塊:

import star

print(star.hi)

star.pstar()

star.pstar(30)

37-生成密碼/驗證碼

此文件名為:randpass.py 思路: 1、設置一個用于隨機取出字符的基礎字符串,本例使用大小寫字母加數(shù)字 2、循環(huán)n次,每次隨機取出一個字符 3、將各個字符拼接起來,保存到變量result中

from random import choice

import string

all_chs = string.ascii_letters + string.digits # 大小寫字母加數(shù)字

def gen_pass(n=8):

result = ''

for i in range(n):

    ch = choice(all_chs)

    result += ch

return result

if name == 'main':

print(gen_pass())

print(gen_pass(4))

print(gen_pass(10))

38-序列對象方法

from random import randint

alist = list() # []

list('hello') # ['h', 'e', 'l', 'l', 'o']

list((10, 20, 30)) # [10, 20, 30] 元組轉列表

astr = str() # ''

str(10) # '10'

str(['h', 'e', 'l', 'l', 'o']) # 將列表轉成字符串

atuple = tuple() # ()

tuple('hello') # ('h', 'e', 'l', 'l', 'o')

num_list = [randint(1, 100) for i in range(10)]

max(num_list)

min(num_list)

39-序列對象方法2

alist = [10, 'john']

list(enumerate(alist)) # [(0, 10), (1, 'john')]

a, b = 0, 10 # a->0 ->10

for ind in range(len(alist)):

print('%s: %s' % (ind, alist[ind]))

for item in enumerate(alist):

print('%s: %s' % (item[0], item[1]))

for ind, val in enumerate(alist):

print('%s: %s' % (ind, val))

atuple = (96, 97, 40, 75, 58, 34, 69, 29, 66, 90)

sorted(atuple)

sorted('hello')

for i in reversed(atuple):

print(i, end=',')

40-字符串方法

py_str = 'hello world!'

py_str.capitalize()

py_str.title()

py_str.center(50)

py_str.center(50, '#')

py_str.ljust(50, '*')

py_str.rjust(50, '*')

py_str.count('l') # 統(tǒng)計l出現(xiàn)的次數(shù)

py_str.count('lo')

py_str.endswith('!') # 以!結尾嗎?

py_str.endswith('d!')

py_str.startswith('a') # 以a開頭嗎?

py_str.islower() # 字母都是小寫的?其他字符不考慮

py_str.isupper() # 字母都是大寫的?其他字符不考慮

'Hao123'.isdigit() # 所有字符都是數(shù)字嗎?

'Hao123'.isalnum() # 所有字符都是字母數(shù)字?

' hello\t '.strip() # 去除兩端空白字符,常用

' hello\t '.lstrip()

' hello\t '.rstrip()

'how are you?'.split()

'hello.tar.gz'.split('.')

'.'.join(['hello', 'tar', 'gz'])

'-'.join(['hello', 'tar', 'gz'])

還有一些題可點贊關注,下期在分享哦!

————————————————

作者:ChiefZHG

原文鏈接:https://blog.csdn.net/weixin_45

?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
【社區(qū)內容提示】社區(qū)部分內容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內容

友情鏈接更多精彩內容