python3的基礎練習題


1、 執行 Python 腳本的兩種方式

1)/usr/bin/python3  xx.py
2)python3 xx.py  #注xx.py需要在內容里面調用由什么解釋器執行

2、 簡述位、字節的關系

1Byte = 8bit
1bit 表示某個二進制 0 1

3、 簡述 ascii、unicode、utf-8、gbk 的關系

最初計算機是由美國發明的,計算機需要一套相應的字符編碼集ascii,來表示英文字符
后來中國也表示也用來計算機,也需要一套字符編碼集來表示漢字字符,也就是gbk
由於各國需要用計算機都需要一套相應的字符編碼,來表示自已國家的字符,
於是就出現統一的字符編碼的集也就是unicode,所有的字符都表示兩個字節,
原來英文字符只占用一個字節,存放英文字符文檔,會浪費一倍的空間,美國肯定不會同意
於是就出現了utf-8編碼,可變長的字符編碼,英文字符編碼表示1個字節,漢字表示3個字節
這下美國就開興了哈!

4、 請寫出 “你好” 分別用 utf-8 和 gbk 編碼所占的位數

你好  在utf-8中一個中文字符3個字節(Byte)  1字節 = 8位(bit) 你好就在utf-8表示24位
你好  在gbk中一個中文字符用2個字節(Byte)  1字節 = 8位(bit) 你好就在gbk中表示16位

5、 Pyhton 單行注釋和多行注釋分別用什么?

單行注釋:用 #注釋內容
多行注釋:用'''注釋內容'''    或者   """注釋內容"""

6、 聲明變量注意事項有那些?

1 變量名不能以數字開頭
2 變量名只能是數字,下划線,英文字母的組合
3 變量名不能有特殊符號
4 某些特定的字符不能用做變量名

7、 如何查看變量在內存中的地址?

id(變量名)

8、 執行 Python 程序時,自動生成的  .pyc文件的作用是什么?

當執行xx.py的python會 把編譯的結果會保存在位於內存中的Pycodeobject中,
python程序運行結束,python解釋器則將PyCodeObject寫回到pyc文件中。
當python再次執行xx.py時,首先程序會在硬盤中尋找pyc文件,直接載入,否則就重復上面的
過程
.pyc文件在_pycache_

注:自已理解,我也不是很了解

9、寫代碼

a.實現用戶輸入用戶名和密碼,當用戶名為seven且密碼為123時,
顯示登陸成功,否則登陸失敗!

代碼如下:

user  =  "seven"
passwd = 123
username = input("please the enter user:")
password = int(input("please the enter passwd:"))
if username == user and password == passwd:
    print("logon successfull")
else:
    print("logon failed")
注意:input()輸入的任何內容都是字符串
View Code

b.實現用戶輸入用戶名和密碼,當用戶名為 seven且密碼為 123 時,
顯示登陸成功,否則登陸失敗,失敗時允許重復輸入三次

代碼如下

user  =  "seven"
passwd =  123
for i in range(3):
    username = input("please the enter user:")
    password = input("please the enter passwd:")
    if password.isdigit():
        password = int(password)
        if username == user and passwd == password:
            print("logon successfull")
            break
        else:
            print("logon failed")
    else:
        print("logon failed")
View Code

c.實現用戶輸入用戶名和密碼,當用戶名為 seven 或 alex 且密碼為 123 時,
顯示登陸成功,否則登陸失敗,失敗時允許重復輸入三次

代碼如下:

user  =  ["seven","alex"]
passwd =  123
for i in range(3):
    username = input("please the enter user:")
    password = input("please the enter passwd:")
    if password.isdigit():
        password = int(password)
        if (username in user)  and passwd == password:
            print("logon successfull")
            break
        else:
            print("logon failed")
    else:
        print("logon failed")
View Code

10、寫代碼

a.使用 while 循環實現輸出 2-3+4­-5+6 ...+100 的和  

代碼如下:

even = 0
count = 1
while count<100:
    count+=1
    #方法1:得出偶數-奇數+偶數-奇數...
    #方法2:求出所有的偶數減去所有的奇數和 (跟小學的換位運算類似)
    if count % 2 == 0:
        print("2-100的偶數",count)
        even += count 
    else:
        print("2-100的奇數",count)
        even -= count 
print(even) #得出的結果
View Code

b.使用 for 循環和 range 實現輸出1-2+3-4+5-6....-98+99  的和

代碼如下:

uneven = 0  
for i in range(1,100):
    #方法1:得出的奇數-偶數+奇數-偶數....
    #方法2:求出奇數和,求出偶數和,用奇數和減偶數和
    if i % 2 == 1:
        print("1-99的奇數",i)
        uneven += i
    else:
        print("1-99的偶數",i)
        uneven -= i
print(uneven)   #得出結果
View Code

c.使用 while 循環實現輸出1,2,3,4,5,7,8,9,11,12

代碼如下:

count = 0
while count <12:
    count += 1
    if count == 6:
        continue
    elif count ==10:
        continue
    print(count)
View Code

d.使用 while 循環實現輸出 1-100 內的所有奇數

代碼如下:

count = 0
while count < 100:
    count += 1
    if count % 2 == 1:
        print("1-100的奇數",count)
View Code

e. 使用 while 循環實現輸出1-100內的所有偶數

代碼如下:

count = 0
while count < 100:
    count += 1
    if count % 2 == 0:
        print("1-100的偶數",count)
View Code

11、分別書寫數字5,10,32,7的二進制表示

在python解釋器中執行bin(number),把某個數字轉換成二進制
二進制的表示:0b (binary)
bin(5)    #0b101
bin(10)  #0b1010
bin(32)  #0b100000
bin(7)    #0b111
View Code

12、簡述對象和 類的關系(可用比喻的手法)

類:用來描述具有相同屬性和方法的對象集合,
它定義每個對象的屬性所共有的屬性和方法,對象是類的實例
對象:通過類定義的數據結構實例

假如:人是一個種類,我們自已本身就是類的對象
類是一張圖紙(該圖紙上畫了建築的模型,以及怎樣實現),實際高樓大夏就是圖紙
實現的對象,
類是抽象的,對象是實際存在的。

13、現有如下兩個變量,請簡述 n1 和 n2是什么關系?

n1=123
n2=123 

n1和n2關系是一樣 ,我們可以用id(n1),id(n2)在內存中的地址的表示

14、現有如下兩個變量,請簡述 n1 和 n2是什么關系?

n1 = 123456
n2 = 123456

n1和n2雖然在值是一樣的,在內存地址表示中是不一樣的

注:
(在python內部中,內存還有一個(小數字池,字符串池)緩存池,對於經常用的,
在python內部編譯有一個優化,在這個緩存池,如果重復使用,都是使用同一內存緩存池的內存(地址)空間
如果大於這個緩存池,則會在內存獨立開辟新的一個內存(地址)空間
例如
數字的緩存池 -5 至 256
可以用不相同的變量名,相同的值,用id(變量名),看它們的內存地址)

 

15、現有如下兩個變量,請簡述 n1 和 n2 是什么關系?
n1 = 123456
n2 = n1

n2 是 n1 值的引用   它們在內存的地址是一樣和內容也是一樣的,只是不同命名
變量的賦值:
賦值不會開辟新的內存空間,它只是復制了新對象的引用,如果n1的值發生改變,
n2還是原來的改變之前值

16、如有一下變量 n1 =5,請使用 int 的提供的方法,
得到該變量最少可以用多少個二進制位表示?

n1= 5
print(n1.bit_length())
#結果
3

 17、布爾值分別有什么?

True  False

18、閱讀代碼,請寫出執行結果
a = "alex"
b = a.capitalize()
print(a)
print(b)
請寫出輸出結果:

alex    #a
Alex    #b

19、寫代碼,有如下變量,請按照要求實現每個功能
name = " aleX"

a. 移除 name 變量對應的值兩邊的空格,並輸入移除有的內容

print(name.strip())
#結果
aleX
View Code

b.判斷 name 變量對應的值是否以 "al" 開頭,並輸出結果

print(name.startswith("al"))
#結果
False
View Code

c.判斷 name 變量對應的值是否以 "X" 結尾,並輸出結果

print(name.endswith("X"))
#結果
True
View Code

d.將 name 變量對應的值中的 “ l” 替換為 “ p”,並輸出結果

print(name.replace("l","p"))
#結果
    apeX
View Code

e.將 name 變量對應的值根據 “ l” 分割,並輸出結果。

print(name.split("l"))
#結果
['\ta', 'eX']  #\t 表示使用了tab
View Code

f.請問,上一題 e分割之后得到值是什么類型?

print(type(name.split("l")))
#結果
<class 'list'> #列表
View Code

g.將 name 變量對應的值變大寫,並輸出結果

print(name.upper())
    ALEX
View Code

h.將 name 變量對應的值變小寫,並輸出結果

print(name.lower())
#結果
    alex
    
View Code

i.請輸出 name 變量對應的值的第 2 個字符?

print(name[2])
#結果
l
View Code

j. 請輸出 name 變量對應的值的前 3 個字符?

print(name[:3])
#結果
    al
View Code

k. 請輸出 name 變量對應的值的后 2 個字符?

print(name[-2:])
#結果
eX
View Code

l.請輸出 name 變量對應的值中 “ e” 所在索引位置?

print(name.index('e'))
#結果
3
View Code

 20、字符串是否可迭代?如可以請使用 for 循環每一個元素?

字符串可以迭代
代碼如下:
hobby = "一條龍"
for i in hobby:
    print(i)
顯示結果如下:
一
條
龍
View Code

21、請用代碼實現:利用下划線將列表的每一個元素拼接成字符串,
li = ['alex', 'eric', 'rain']

print("_".join(li))
#結果
alex_eric_rain
View Code

22、寫代碼,有如下列表,按照要求實現每一個功能

li = ['alex','eric','rain']

a.計算列表長度並輸出

print(len(li))
#結果
3
View Code

b.列表中追加元素 “seven”,並輸出添加后的列表

li.append("seven")
print(li)
#結果
['alex', 'eric', 'rain', 'seven']
View Code

c.請在列表的第1個位置插入元素 “Tony”,並輸出添加后的列表

li.insert(0,"Tony")
print(li)
#結果
['Tony', 'alex', 'eric', 'rain']
View Code

d.請修改列表第2個位置的元素為 “Kelly”,並輸出修改后的列表

li[1] = "Kelly"
print(li)
#結果
['alex', 'Kelly', 'rain']
View Code

e.請刪除列表中的元素 “eric”,並輸出修改后的列表

第一種:得出“eric”索引,通過索引來刪除該值
第二種:直接刪除"eric"
1)
del li[1];print(li)   #結果['alex', 'rain']   
li.pop(1);print(li)   #結果['alex', 'rain']
2)
li.remove("eric")
print(li)
#結果
['alex', 'rain']     
View Code

f.請刪除列表中的第2個元素,並輸出刪除的元素的值和刪除元素后的列表

print(li.pop(1));print(li)
#結果
eric
['alex', 'rain']
View Code

g.請刪除列表中的第3個元素,並輸出刪除元素后的列表

print(li.pop(2));print(li)
#結果
rain
['alex', 'eric']
View Code

h.請刪除列表中的第2至4個元素並輸出刪除元素后的列表

del li[1:3]
print(li)
#結果
['alex']
View Code

i.請將列表所有的元素反轉,並輸出反轉后的列表

li.reverse()
print(li)
#結果
['rain', 'eric', 'alex']
View Code

j.請使用 for、len、range 輸出列表的索引

#3種方法,建議用第三種
1)for
for i in li:
    #list.index()列表有相同元素的,只是的獲取(相同元素中的第一個元素)的索引
    print(li.index(i),i)  #如果列表內有相同的元素,不建議使用此方法
#結果
0 alex
1 eric
2 rain

2)len
zero = []
for i in li:
    print(len(zero),i)
    zero.append(i)
#結果
0 alex
1 eric
2 rain

3)range
for i in range(len(li)):
    print(i,li[i])
#結果
0 alex
1 eric
2 rain
View Code

 k.請使用 enumrate 輸出列表元素和序號(序號從 100 開始)

for index,i in enumerate(li,start=100):
    print(index,i)
#結果
100 alex
101 eric
102 rain
View Code

l.請使用 for 循環輸出列表的所有元素

for i in li:
    print(i)
#結果
alex
eric
rain
View Code

 

23、寫代碼,有如下列表,請按照功能要求實現每一個功能
li=["hello",'seven',["mon",["h","kelly"],'all'],123,446]

a. 請輸出 “Kelly”

print(li[2][1][1])
#結果
kelly
View Code

b.請使用索引找到 'all'元素並將其修改為 “ALL”

li[2][2] = "ALL"
print(li)
#結果
['hello', 'seven', ['mon', ['h', 'kelly'], 'ALL'], 123, 446]
View Code

24、寫代碼,有如下元組,按照要求實現每一個功能
tu=('alex','eric','rain')

a.計算元組長度並輸出

print(len(tu))
#結果
3
View Code

b.獲取元組的第2個元素,並輸出

print(tu[1])
#結果
eric
View Code

c.獲取元組的第 1-2個元素,並輸出

print(tu[0:2])
#結果
('alex', 'eric')
View Code

d.請使用 for 輸出元組的元素

for i in tu:
    print(i)
#結果
alex
eric
rain
View Code

e.請使用 for、len、range 輸出元組的索引

#跟22題j列表用法類似
for i in range(len(tu)):
    print(i,tu[i])
#結果
0 alex
1 eric
2 rain
View Code

f.請使用 enumrate 輸出元祖元素和序號(序號從 10 開始)

for index,i in enumerate(tu,start=10):
    print(index,i)
#結果
10 alex
11 eric
12 rain
View Code

25、有如下變量,請實現要求的功能
tu=("alex",[11,22,{"k1":'v1',"k2":["age","name"],"k3":(11,22,33)},44])

a.講述元祖的特性

元祖和列表類似都是有序的從0開始
不同的是元祖的元素是不能修改的

b.請問 tu 變量中的第一個元素 “alex” 是否可被修改?

不能修改

c.請問tu變量中的"k2"對應的值是什么類型?是否可以被修改?
如果可以,請在其中添加一個元素 “Seven”

print(type(tu[1][2]["k2"]))
#結果
<class 'list'>
列表類型可以修改
tu[1][2]["k2"].append("seven")
print(tu)
#結果
('alex', [11, 22, {'k2': ['age', 'name', 'seven'], 'k3': (11, 22, 33), 'k1': 'v1'}, 44])
注:表面上看,tuple的元素確實變了,但其實變的不是tuple的元素,而是list的元素。
tuple一開始指向的list並沒有改成別的list,所以,tuple所謂的“不變”是說,
tuple的每個元素,指向永遠不變。但指向的這個list本身是可變的!
View Code

d.請問 tu 變量中的"k3"對應的值是什么類型?是否可以被修改?
如果可以,請在其中添加一個元素 “Seven”

print(type(tu[1][2]["k3"]))
#結果
<class 'tuple'>
#對應值是元祖,不能修改
View Code

 

26、字典
dic ={'k1':"v1","k2":"v2","k3":[11,22,33]}

a.請循環輸出所有的 key

for i in dic:
    print(i)
#結果
k1
k3
k2
注:字典是無序的
View Code

b.請循環輸出所有的value

for i in dic:
    print(dic[i])
#結果
[11, 22, 33]
v2
v1
View Code

c.請循環輸出所有的 key 和 value

for i in dic:
    print(i,dic[i])
#結果
k2 v2
k3 [11, 22, 33]
k1 v1
View Code

d.請在字典中添加一個鍵值對,"k4":"v4",輸出添加后的字典

dic["k4"] = "v4"
print(dic)
#結果
{'k4': 'v4', 'k2': 'v2', 'k3': [11, 22, 33], 'k1': 'v1'}
View Code

e.請在修改字典中 “k1” 對應的值為 “alex”,輸出修改后的字典

dic['k1'] = "alex"
print(dic)
#結果
{'k3': [11, 22, 33], 'k1': 'alex', 'k2': 'v2'}
View Code

f.請在 k3 對應的值中追加一個元素44,輸出修改后的字典

dic["k3"].append(44)
print(dic)
#結果
{'k2': 'v2', 'k3': [11, 22, 33, 44], 'k1': 'v1'}
View Code

g.請在 k3 對應的值的第1個位置插入個元素18,輸出修改后的字典

dic["k3"].insert(0,18)
print(dic)
#結果
{'k1': 'v1', 'k2': 'v2', 'k3': [18, 11, 22, 33]}
View Code

 27、轉換

a.將字符串 s="alex" 轉換成列表

print(list(s))
#結果
['a', 'l', 'e', 'x']
View Code

b.將字符串 s="alex" 轉換成元祖

print(tuple(s))
#結果
('a', 'l', 'e', 'x')
View Code

c.將列表 li =["alex","seven"]轉換成元組

print(tuple(li))
#結果
('alex', 'seven')
View Code

d.將元祖 tu =('Alex',"seven")轉換成列表

print(list(tu))
#結果
['Alex', 'seven']
View Code

e.將列表 li=["alex","seven"]轉換成字典且字典的key按照10開始向后遞增

dic1 = {}
for key,value in enumerate(li,start=10):
    dic1[key] = value
print(dic1)
#結果
{10: 'alex', 11: 'seven'}
View Code

 28、轉碼

n="老男孩"

a.將字符串轉換成 utf-8 編碼的字節,並輸出,然后將該字節再轉換成 utf-8 編碼字符串,再輸出

print(n.encode("utf-8"))
#結果
b'\xe8\x80\x81\xe7\x94\xb7\xe5\xad\xa9'

print(n.encode("utf-8").decode("utf-8"))
#結果
老男孩
View Code

b.將字符串轉換成 gbk 編碼的字節,並輸出,然后將該字節再轉換成 gbk 編碼字符串,再輸出

print(n.encode("gbk"))
#結果
b'\xc0\xcf\xc4\xd0\xba\xa2'

print(n.encode("gbk").decode("gbk"))
#結果
老男孩
View Code

 29、求1-100內的所有數的和

#3種方法
1)
print(sum(range(1,101)))
#結果
5050

2)
SUM = 0
for i in range(1,101):
    SUM += i
print(SUM)
#結果
5050

3)
SUM = 0
count = 1
while count <= 100:
    SUM += count
    count += 1
print(SUM)
#結果
5050
View Code

30、元素分類

有如下值集合 [11,22,33,44,55,66,77,88,99,90],
將所有大於66的值保存至字典的第一個 key中,
將小於66的值保存至第二個 key 的值中。

即:{'k1':大於 66 的所有值,'k2':小於66 的所有值}

dic = {"k1":[],
       "k2":[]}
aa = set([11,22,33,44,55,66,77,88,99,90])
for i in aa:
    if i>= 66:
        dic["k1"].append(i)
    else:
        dic["k2"].append(i)
print(dic)
結果
{'k1': [66, 99, 77, 88, 90], 'k2': [33, 11, 44, 22, 55]}
View Code

31、購物車
功能要求:
要求用戶輸入總資產,例如: 2000
顯示商品列表,讓用戶根據序號選擇商品,加入購物車
購買,如果商品總額大於總資產,提示賬戶余額不足,否則,購買成功。
goods = [
{"name":"電腦","price":1999},
{"name":"鼠標","price":10},
{"name":"游艇","price":20},
{"name":"美女","price":98},
]

shop_cart = []
goods    =    [
{"name":"電腦","price":1999},
{"name":"鼠標","price":10},
{"name":"游艇","price":20},
{"name":"美女","price":98},
]
while True:
    salary = input("請輸入用戶余額[quit]:")
    if salary.isdigit():
        salary = int(salary)
        break
    elif salary == "quit":
        exit("不想購買")
    else:
        print("please the enter number")
while True:
    print("shop list".center(50, '*'))
    for index,i in enumerate(goods):
        print(index,i)
    choose_number = input("請輸入購買商品編號[quit]:")
    if choose_number.isdigit():
        choose_number = int(choose_number)
        product_list = []
        if 0 <= choose_number <= len(goods):
            product_list.append(goods[choose_number])
            if salary >= product_list[0]["price"]:
              shop_cart.append(goods[choose_number])
              salary -= product_list[0]['price']
              print("當前購買的商品",product_list,"當前用戶余額\033[1;31m{salary}\033[0m".format(salary=salary))
            else:
                print("余額不足")
        else:
            print("無效的商品編號")
    elif choose_number.lower() == 'quit':

        print("購買的商品".center(50,"*"))
        for y in shop_cart:
            print(y)
        exit()
    else:
        print("無效的輸入")
#注:簡易的購物車,還能繼續優化
View Code

 


免責聲明!

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



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