python基礎入門二

寫代碼,有如下變量,請按照要求實現每個功能 (共6分,每小題各0.5分)
name = ” aleX”
1)移除 name 變量對應的值兩邊的空格,並輸出處理結果
2) 判斷 name 變量對應的值是否以 “al” 開頭,並輸出結果

3) 判斷 name 變量對應的值是否以 “X” 結尾,並輸出結果

4) 將 name 變量對應的值中的 “l” 替換爲 “p”,並輸出結果
5) 將 name 變量對應的值根據 “l” 分割,並輸出結果。
6) 將 name 變量對應的值變大寫,並輸出結果

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

8) 請輸出 name 變量對應的值的第 2 個字符?
9) 請輸出 name 變量對應的值的前 3 個字符?
10) 請輸出 name 變量對應的值的後 2 個字符?

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

12) 獲取子序列,去掉最後一個字符。如: oldboy 則獲取 oldbo。

name = " aleX"


print(name.strip())

print(name.startswith('al'))

print(name.endswith('X'))

print(name.replace('l','p'))
print(name.split('l'))
print(name.upper())
print(name.capitalize())
print(name[1])
print(name[:3])
print(name[3:])
print(name.index('e'))
print(name[:-1])
  1. 有列表data=[‘alex’,49,[1900,3,18]],分別取出列表中的名字,年齡,出生的年,月,日賦值給不同的變量
data=['alex',49,[1900,3,18]]
name = data[0]
age = data[1]
birth = data[2]
print("名字是{0}年齡是{1}出生年月是{2}".format(name,age,birth))
  1. 用列表模擬隊列(隊列是先進先出,類似於自動扶梯)
dui = [1,2,3,4,5,6]
dui.insert(len(dui),'ll')
print(dui)
dui.pop(0)
print(dui)
  1. 用列表模擬堆棧(堆棧先進後出,類似於喝酒喝吐了)
zhan = [1,2,3,4,5,6]
zhan.insert(len(zhan),'ll')
print(zhan)
zhan.pop()
print(zhan)
  1. 有如下列表,請按照年齡排序(涉及到匿名函數)
l=[
    {'name':'alex','age':84},
    {'name':'oldboy','age':73},
    {'name':'egon','age':18},
]

l.sort(key=lambda item:item['age'])
print(l)

1 有如下值集合 [11,22,33,44,55,66,77,88,99,90…],將所有大於 66 的值保存至字典的第一個key中,將小於 66 的值保存至第二個key的值中
即: {‘k1’: 大於66的所有值, ‘k2’: 小於66的所有值}

l = [11,22,33,44,55,66,77,88,99,90,50,40,100]

dic = {'k1':[],'k2':[]}
for num in l:
    if num > 66:
        dic['k1'].append(num)
    else:
        dic['k2'].append(num)

print(dic)

2 統計s=’hello alex alex say hello sb sb’中每個單詞的個數
結果如:{‘hello’: 2, ‘alex’: 2, ‘say’: 1, ‘sb’: 2}
s=’hello alex alex say hello sb sb’
ll = s.split() # 以空格區分
集合去重實現#
res = set(ll) # 去重
dic = dic.fromkeys(res) #初始化字典
for k in res:
dic[k] = ll.count(k) #填入數據
print(dic)
字典的setdefault方法實現#
dic = {}
for k in ll:
dic.setdefault(k,ll.count(k))
print(dic)

1. 有列表l=[‘a’,’b’,1,’a’,’a’],列表元素均爲可hash類型,去重,得到新列表,且新列表無需保持列表原來的順序

l=['a','b',1,'a','a']
new = set(l)
print(new)

2.在上題的基礎上,保存列表原來的順序

l=['a','b',1,'a','a']
new = set()
res = []
for d in l:
    if d not in new:
        new.add(d)
        res.append(d)
print(res)

3.去除文件中重複的行,肯定要保持文件內容的順序不變


file = open('C:\Users\liuliangliang\Desktop\UserLoginServiceImplTest.java','r')
file = file.readlines()
s = set()
res = []
for line in file:
    if line in file:
        print(line)
        if line  not in s:
            s.add(line)
            res.append(line)

write = open('C:\Users\liuliangliang\Desktop\UserLoginServiceImplTest','w')
write.writelines(res)

4.有如下列表,列表元素爲不可hash類型,去重,得到新列表,且新列表一定要保持列表原來的順序

l=[
    {'name':'egon','age':18,'sex':'male'},
    {'name':'alex','age':73,'sex':'male'},
    {'name':'egon','age':20,'sex':'female'},
    {'name':'egon','age':18,'sex':'male'},
    {'name':'egon','age':18,'sex':'male'},
]

s = set()
res = []

for i in l:
    val = (i['name'],i['age'],i['sex'])
    if val not in s:
        print(val)
        s.add(val)
        res.append(i)
print(res)
print(s)
  1. 文件a.txt內容:每一行內容分別爲商品名字,價錢,個數,求出本次購物花費的總錢數

apple 10 3

tesla 100000 1

mac 3000 2

lenovo 30000 3

chicken 10 3

import os

### 獲取當前文件路徑
pwd = os.getcwd()
### 得到存儲用戶信息的文件路徑
filedir = pwd + '\qingdan'
### 判斷信息文件是否存在,存在即取出並轉換成字典類型數據,否則提示文件不存在退出
if os.path.exists(filedir):
    wp = open(filedir, 'r',encoding='utf-8')
    sett = wp.readlines()
    print(sett)
    wp.close()
else:
    print("文件不存在!")
    exit()
last = 0
for i in sett:
    res = i.split()
    count = int(res[1])*int(res[2])
    last = last + count
print(last)

需求:

用戶名和密碼存放於文件中,格式爲:egon|egon123
啓動程序後,先登錄,登錄成功則讓用戶輸入工資,然後打印商品列表,失敗則重新登錄,超過三次則退出程序
允許用戶根據商品編號購買商品
用戶選擇商品後,檢測餘額是否夠,夠就直接扣款,不夠就提醒
可隨時退出,退出時,打印已購買商品和餘額



import json
import os

# 獲取當前文件路徑
pwd = os.getcwd()
# 得到存儲用戶信息的文件路徑
filedir = pwd + '\dic'
listdir =pwd + '\list'
# 判斷信息文件是否存在,存在即取出並轉換成字典類型數據,否則提示文件不存在退出
if os.path.exists(filedir) and os.path.exists(listdir):
    wp = open(filedir, 'r')
    sett = wp.read()
    dic_user = json.loads(sett)
    wp.close()
    sp = open(listdir,'r')
    shop = sp.read()
    dic_product = json.loads(shop)
    sp.close()
else:
    print("文件不存在!")
    exit()

Tag = True
while Tag:

    name = input("請輸入用戶名:")
    # 判斷用戶名是否存在於文件中
    if name not in dic_user.keys():
        print("用戶不存在!")
        continue
    passwd = input("請輸入用戶密碼:")
    # 判斷用戶名密碼是否正確
    if name in dic_user.keys() and passwd == dic_user.get(name).get('passwd'):
        list_info = [{"username": name}]
        cmd = input("輸入你的工資")
        last = int(cmd)
        while Tag:

            print(dic_product)
            # cap,num = input("___輸入您想要購買的物品編號和個數以空格分開:如'001 2'").split()
            cap = input("輸入您所購買的物品編碼:").strip()

            if cap  not in dic_product :
                print("請輸入正確的物品編碼")
                continue

            num = input("輸入您所購買物品的數量:").strip()

            if cap  not in dic_product or not num.isdigit():
                print("請輸入正確的物品編碼或購買數!")
                continue

            account = int(dic_product[cap][1]) * int(num)
            if  account <= last:
                last = last - account

                list_info.append({"product":dic_product[cap],"num":num})
                quit = input("購買成功,退出輸入q,繼續輸入y")
                if quit == 'q':
                    Tag = False
                    continue
                else:
                    continue
            else:

                addin = input("餘額不足!充值輸入y,退出輸入q")
                if addin == 'y':
                    add = input("輸入充值金額:").strip()
                    last = int(last) + int(add)
                    print("餘額爲%d" %last)
                if addin == 'q':
                    Tag =False
                    continue

        list_info.append({"last_money": last})
        for i in list_info:
            print(i)
        continue
    else:
        if name in dic_user.keys():
            print("用戶名存在,密碼錯誤")

            dic_user[name]['count'] += 1
            if dic_user[name]['count'] == 3:
                print("輸入錯誤三次,退出程序")
                Tag = False

input(" ")

要求:

打印省、市、縣三級菜單
可返回上一級
可隨時退出程序

import json
import os

# 獲取當前文件路徑
pwd = os.getcwd()
# 得到存儲用戶信息的文件路徑
filedir = pwd + '\www'
# 判斷信息文件是否存在,存在即取出並轉換成字典類型數據,否則提示文件不存在退出
if os.path.exists(filedir):
    wp = open(filedir, 'r',encoding='utf-8')
    sett = wp.read()
    data = json.loads(sett)
    wp.close()
else:
    print("文件不存在!")
    exit()
# 定義一個字典類型,存放修改後的字典
diction = data
# 定義一個列表類型,存放修改後的字典
listion = [data]

while True:
# 當字典爲空時,提示沒有下級,顯示上一層內容
    if diction == {}:
        print("沒有下級了!")
        diction = listion[-1]
        listion.pop()

    for key in diction:
        print(key,end=' |')
    agent = input("\n輸入上述名稱查詢,輸入r返回上一層,輸入q退出:")
# 如果輸入信息存在當前字典中,將當前的字典追加進入列表,將當前字典轉換成下級字典
    if agent in diction:
        listion.append(diction)
        diction = diction[agent]
# 如果輸入信息是r, 判斷列表爲空時提示沒有上一級,不爲空返回上一級,當前字典轉換成上一級字典
    elif agent == 'r':
        if len(listion) == 0:
            print("沒有上一級了!")
        else:
            diction = listion[-1]
            listion.pop()
# 如果輸入信息是q,退出程序
    elif agent == 'q':
        break
    else:
        print("輸入有誤,重新輸入")









發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章