001_02-python基礎習題答案
python 基礎習題
-
執行 Python 指令碼的兩種方式
如:指令碼/python/test.py
第一種方式:python /python/test.py
第二中方式:在test.py中宣告:/usr/bin/env pythonàchmod +x test.pyà/python/test.py
2、簡述位、位元組的關係
1Byte = 8bits
- 簡述 ascii、unicode、utf-8、gbk 的關係?
ASCII(American Standard Code for Information Interchange,美國標準資訊交換程式碼)是基於拉丁字母的一套電腦編碼系統,主要用於顯示現代英語和其他西歐語言,其最多隻能用 8 位來表示(一個位元組),即:2**8 = 256,所以,ASCII碼最多隻能表示 256 個符號。顯然ASCII碼無法將世界上的各種文字和符號全部表示,所以,就需要新出一種可以代表所有字元和符號的編碼,即:Unicode
Unicode(統一碼、萬國碼、單一碼)是一種在計算機上使用的字元編碼。Unicode 是為了解決傳統的字元編碼方案的侷限而產生的,它為每種語言中的每個字元設定了統一併且唯一的二進位制編碼,規定所有的字元和符號最少由 16 位來表示(2個位元組),即:2 **16 = 65536,
注:此處說的的是最少2個位元組,可能更多。
UTF-8,是對Unicode編碼的壓縮和優化,他不再使用最少使用2個位元組,而是將所有的字元和符號進行分類:ascii碼中的內容用1個位元組儲存、歐洲的字元用2個位元組儲存,東亞的字元用3個位元組儲存...
GBK是國家標準GB2312基礎上擴容後相容GB2312的標準。GBK的文字編碼是用雙位元組來表示的,即不論中、英文字元均使用雙位元組來表示,為了區分中文,將其最高位都設定成1。GBK包含全部中文字元,是國家編碼,通用性比UTF8差,不過UTF8佔用的資料庫比GBD大。
unicode相容其他3種字符集。
4、請寫出 "李傑" 分別用 utf-8 和 gbk 編碼所佔的位數?
utf-8 3Bytes
gbk 2Bytes
5、Pyhton 單行註釋和多行註釋分別用什麼?
單行 #
多行 """ """
6、宣告變數注意事項有那些?
(1)不能以數字開頭
(2)不能使用系統保留關鍵字;
8、如何檢視變數在記憶體中的地址?
id(變數)
9、執行 Python 程式時,自動生成的 .pyc 檔案的作用是什麼?
10、寫程式碼
a.實現使用者輸入使用者名稱和密碼,當用戶名為 seven 且 密碼為 123 時,顯示登陸成功,否則登陸失敗!
while True:
name = input("pelease input name: ")
passwd = input("pelease input passwd: ").strip()
if name == "server" and passwd == "123":
print("welcome ..")
break
else:
print("error")
break
b.實現使用者輸入使用者名稱和密碼,當用戶名為 seven 且 密碼為 123 時,顯示登陸成功,否則登陸失敗,失敗時允許重複輸入三次
count = 1
while count <= 3:
name = input("pelease input name: ")
passwd = input("pelease input passwd: ").strip()
if name == "server" and passwd == "123":
print("welcome ..")
break
else:
print("error")
count +=1
c.實現使用者輸入使用者名稱和密碼,當用戶名為 seven 或 alex 且 密碼為 123 時,顯示登陸成功,否則登陸失敗,失敗時允許重複輸入三次
count = 1
while count <= 3:
name = input("pelease input name: ")
passwd = input("pelease input passwd: ").strip()
if name == "server" and passwd == "123" or name == "alex" and passwd == "123" :
print("welcome ..")
break
else:
print("error")
count +=1
11、寫程式碼
a. 使用while迴圈實現輸出2-3+4-5+6...+100 的和
count = 2
total = 0
while count <= 100:
if (count % 2):
total = total - count
count += 1
else:
total = total + count
count += 1
print(total)
b. 使用for迴圈和range實現輸出 1-2+3-4+5-6...+99 的和
total = 0
for i in range(1,100):
if (i % 2):
total = total + i
i +=1
else:
total = total - i
i +=1
print(total)
c. 使用 while 迴圈實現輸出 1,2,3,4,5, 7,8,9, 11,12
count = 1
while count <= 12:
if count == 6 or count == 10:
count += 1
continue
else:
print(count)
count += 1
d. 使用 while 迴圈實現輸出 1-100 內的所有奇數
#!/usr/bin/env python
# -*- coding: utf-8 -*-
count=1
while count<=100:
if count%2:
print(count)
else:
pass
count+=1
e. 使用 while 迴圈實現輸出 1-100 內的所有偶數
#!/usr/bin/env python
# -*- coding: utf-8 -*-
count=1
while count<=100:
if count%2:
count+=1
continue
else:
print(count)
count+=1
12、分別書寫數字 5,10,32,7 的二進位制表示(bin()函式)
64 32 16 8 4 2 1
5 1 0 1
10 1 0 1 0
32 1 0 0 0 0 0
7 1 1 1
14、現有如下兩個變數,請簡述 n1 和 n2 是什麼關係? n1 = 123 n2 = 123
沒有任何關係
15、現有如下兩個變數,請簡述 n1 和 n2 是什麼關係? n1 = 123456 n2 = 123456
沒有任何關係
>>> n1=123456
>>> n2=123456
>>> n1 is n2
False
>>> id(n1)
139934806583632
>>> id(n2)
139934806114672
16、現有如下兩個變數,請簡述 n1 和 n2 是什麼關係? n1 = 123456 n2 = n1
n1和2的記憶體相同,都指向123456所對的記憶體地址
18、布林值分別有什麼?
True和False,0和1
19、閱讀程式碼,請寫出執行結果
a = "alex"
b = a.capitalize()
print(a)
print(b)
請寫出輸出結果:
alex
Alex
20、寫程式碼,有如下變數,請按照要求實現每個功能 name = " aleX"
a. 移除 name 變數對應的值兩邊的空格,並輸出移除後的內容
print(name.strip())
b. 判斷 name 變數對應的值是否以 "al" 開頭,並輸出結果
print(name.startswith("al"))
False
c. 判斷 name 變數對應的值是否以 "X" 結尾,並輸出結果
print(name.endswith("X"))
True
d. 將 name 變數對應的值中的 "l" 替換為 "p",並輸出結果
print(name.replace("l","p"))
apeX
e. 將 name 變數對應的值根據 "l" 分割,並輸出結果。
print(name.split("l"))
[' a', 'eX']
f. 請問,上一題 e 分割之後得到值是什麼型別?
list
g. 將 name 變數對應的值變大寫,並輸出結果
print(name.upper())
ALEX
h. 將 name 變數對應的值變小寫,並輸出結果
print(name.lower())
alex
i. 請輸出 name 變數對應的值的第 2 個字元?
print(name[1])
a
j. 請輸出 name 變數對應的值的前 3 個字元?
print(name[:3])
ale
k. 請輸出 name 變數對應的值的後 2 個字元?
print(name[-2:])
eX
l. 請輸出 name 變數對應的值中 "e" 所在索引位置?
print(name.index("e"))
3
21、字串(name='Baoge-IT')是否可迭代?如可以請使用 for 迴圈每一個元素?
for i in range(len(name)):
print(name[i])
22、請用程式碼實現:利用下劃線將列表的每一個元素拼接成字串,li = ['alex', 'eric', 'rain']
print("_".join(li))
alex_eric_rain
22、寫程式碼,有如下列表,按照要求實現每一個功能 li = ['alex', 'eric', 'rain']
a. 計算列表長度並輸出
print(len(li))
b. 列表中追加元素 "seven",並輸出新增後的列表
li.append("server")
print(li)
c. 請在列表的第 1 個位置插入元素 "Tony",並輸出新增後的列表
li.insert(0,"Tony")
print(li)
d. 請修改列表第 2 個位置的元素為 "Kelly",並輸出修改後的列表
li[1] = "Kelly"
print(li)
e. 請刪除列表中的元素 "eric",並輸出修改後的列表
li.remove('eric')
print(li)
f. 請刪除列表中的第 2 個元素,並輸出刪除的元素的值和刪除元素後的列表
print(li.pop(1))
print(li)
g. 請刪除列表中的第 3 個元素,並輸出刪除元素後的列表
print(li.pop(2))
print(li)
h. 請刪除列表中的第 2 至 4 個元素,並輸出刪除元素後的列表
del li[1:]
print(li)
i. 請將列表所有的元素反轉,並輸出反轉後的列表
li.reverse()
print(li)
['rain', 'eric', 'alex']
j. 請使用 for、len、range 輸出列表的索引
for li_index in range(len(li)):
print(li_index)
k. 請使用 enumrate 輸出列表(li)元素和序號(序號從 100 開始)
for k,j in enumerate(li,100):
print(k,j)
l. 請使用 for 迴圈輸出列表的所有元素
for n in li:
print(n)
23、寫程式碼,有如下列表,請按照功能要求實現每一個功能 li = ["hello", 'seven', ["mon", ["h", "kelly"], 'all'], 123, 446]
a. 請輸出 "Kelly"
print(li[2][1][1])
b. 請使用索引找到 'all' 元素並將其修改為 "ALL"
li[2][2] = "ALL"
print(li)
24、寫程式碼,有如下元組,按照要求實現每一個功能 tu = ('alex', 'eric', 'rain')
a. 計算元組長度並輸出
print(len(tu))
3
b. 獲取元組的第 2 個元素,並輸出
print(tu[1])
eric
c. 獲取元組的第 1-2 個元素,並輸出
print(tu[0:2])
d. 請使用 for 輸出元組的元素
for n in tu:
print(n)
e. 請使用 for、len、range 輸出元組的索引
for i in range(len(tu)):
print(i)
f. 請使用 enumrate 輸出元祖元素和序號(序號從 10 開始)
for n in enumerate(tu,10):
print(n)
25、有如下變數,請實現要求的功能
tu = ("alex", [11, 22, {"k1": 'v1', "k2": ["age", "name"], "k3": (11,22,33)}, 44])
a. 講述元祖的特性
元組裡儲存的資料是不應該被修改的
b. 請問 tu 變數中的第一個元素 "alex" 是否可被修改?
可以,但是一般不修改
c. 請問 tu 變數中的"k2"對應的值是什麼型別?是否可以被修改?如果可以,請在其中新增一個元素 "Seven" d. 請問 tu 變數中的"k3"對應的值是什麼型別?是否可以被修改?如果可以,請在其中新增一個元素 "Seven"
listà可以被修改à tu[1][2]['k2'].append('Seven')
tupleà不可以修改
26、字典
dic = {'k1': "v1", "k2": "v2", "k3": [11,22,33]}
a. 請迴圈輸出所有的 key
or n in dic:
print(n)
b. 請迴圈輸出所有的 value
for n in dic:
print(dic[n])
c. 請迴圈輸出所有的 key 和 value
for n in dic:
print(n,dic[n])
d. 請在字典中新增一個鍵值對,"k4": "v4",輸出新增後的字典
dic["k4"] = "v4"
print(dic)
e. 請在修改字典中 "k1" 對應的值為 "alex",輸出修改後的字典
dic["k1"] = "alex"
print(dic)
f. 請在 k3 對應的值中追加一個元素 44,輸出修改後的字典
dic["k3"].append(44)
print(dic)
g. 請在 k3 對應的值的第 1 個位置插入個元素 18,輸出修改後的字典
dic["k3"].insert(0,18)
print(dic)
27、轉換
a. 將字串 s = "alex" 轉換成列表
s = list(s)
print(s)
b. 將字串 s = "alex" 轉換成元祖
s = tuple(s)
print(s)
('a', 'l', 'e', 'x')
b. 將列表 li = ["alex", "seven"] 轉換成元組
s = tuple(li)
print(li)
['alex', 'seven']
c. 將元祖 tu = ('Alex', "seven") 轉換成列表
tu = list(tu)
print(tu)
['Alex', 'seven']
d. 將列表 li = ["alex", "seven"] 轉換成字典且字典的 key 按照 10 開始向後遞增
li = ["alex","seven"]
dict = {}
for i,name in enumerate(li,10):
dict[i] = name
print(dict)
27、轉碼n = "微曦教育"
a. 將字串轉換成 utf-8 編碼的位元組,並輸出,然後將該位元組再轉換成 utf-8 編碼字串,再輸出
b. 將字串轉換成 gbk 編碼的位元組,並輸出,然後將該位元組再轉換成 gbk 編碼字串,再輸出
28、求 1-100 內的所有數的和
#!/usr/bin/env python
# -*- coding: utf-8 -*-
count = 1
total =0
while count <= 100:
total +=count
count +=1
print(total)
29、元素分類
有如下值集合 [11,22,33,44,55,66,77,88,99,90],將所有大於 66 的值儲存至字典的第一個 key 中,
將小於 66 的值儲存至第二個 key 的值中。
即: {'k1': 大於 66 的所有值, 'k2': 小於 66 的所有值}
#!/usr/bin/env python
# -*- coding: utf-8 -*-
name = [11,22,33,44,55,66,77,88,99,90]
obj = {}
for n in name:
if n >= 66:
if "k1" in obj:
obj["k1"].append(n)
else:
obj["k1"] = [n]
else:
if "k2" in obj:
obj["k2"].append(n)
else:
obj["k2"] = [n]
print(obj)
30、購物車 功能要求:
要求使用者輸入總資產,例如:2000 顯示商品列表,讓使用者根據序號選擇商品,加入購物車 購買,如果商品總額大於總資產,提示賬戶餘額不足,否則,購買成功。
goods = [
{"name": "電腦", "price": 1999},
{"name": "滑鼠", "price": 10}, {"name": "遊艇", "price": 20}, {"name": "美女", "price": 998},
]
goods = [
{"name": "電腦", "price": 1999},
{"name": "滑鼠", "price": 10},
{"name": "遊艇", "price": 20},
{"name": "美女", "price": 998}
]
shopping = {}
while True:
try:
salary = int(input("input your salary: "))
break
except:
continue
if salary < 10:
print("你工資太少了.金額為", salary, "退出吧..老表")
exit()
count = 1
total = 0
while True:
print("You can buy the following items")
for i in range(len(goods)):
print("%s %s %s" % (i + 1, goods[i]["name"], goods[i]["price"]))
choice = input("please choice number or input q exit>>").strip()
if choice.isdigit():
choice = int(choice)
if choice in range(len(goods)+1):
balance = salary - goods[choice -1]["price"]
if balance >= 0:
print("\033[31;1myour bought\033[0m", goods[choice -1]["name"], "\033[31;1mbalance\033[0m", balance, "元")
if len(shopping) > 0:
if goods[choice - 1]["name"] in shopping:
shopping[goods[choice - 1]["name"]][0] += 1
# shopping[goods[choice - 1]["price"]] += goods[choice - 1]["price"]
else:
shopping[goods[choice - 1]["name"]] = [1, goods[choice - 1]["price"]]
else:
shopping[goods[choice-1]["name"]] = [1, goods[choice -1]["price"]]
salary = balance
else:
print("you money", salary, "Differ", balance, "you can try")
else:
continue
elif choice == "q":
if len(shopping) == 0:
print("You didn't buy anything")
else:
print("id 商品 數量 單價 總價")
for i in shopping:
print("%-5d %-8s %-6d %-6d %-6d" % (count, i, shopping[i][0], shopping[i][1], shopping[i][1]*shopping[i][0]))
count += 1
total += shopping[i][1]*shopping[i][0]
print("\033[31;1myour balance\033[0m", total, "元")
exit()
else:
continue