Python Basic data type exercises

Source: Internet
Author: User

First, the element classification
# has the following values set [11,22,33,44,55,66,77,88,99,90 ...], save all values greater than 66 to the first key in the dictionary, and save the value less than 66 to the value of the second key.
# that is: {' K1 ': All values greater than 66, ' K2 ': All values less than 66}

List1 = [11,22,33,44,55,66,77,88,99,90]dic1 = {     ' k1 ': [],     ' K2 ': []}for L in  list1:    if L >:        dic1 [' K1 '].append (l)    else:        dic1[' K2 '].append (l) print (DIC1)

Second, find
1. Find the elements in the list, remove the spaces for each element, and look for all elements that begin with a or a and end with C

Li = ["alc", "Aric", "Aex", "Tny", "Rain"]list1 =[]for L in Li:    #使用strip方法确定能寻找到所有元素, Startwith,endwith Search by condition    if L.strip (). StartsWith (' A ' or ' a ') and L.strip (). EndsWith (' C '):        #print (L.strip ())        List1.append (L.strip ()) Print (List1)

2, meta-group

Tu = ("alc", "Aric", "Alx", "Tny", "Rain") #找出的元素放到一个新列表中 because the element in the tuple cannot be increased list2 =[]for L in Tu:    #使用strip方法确定能寻找到所有元素, start With,endwith Search by Condition    #if determine    if L.strip (). StartsWith (' A ' or ' a ') and L.strip (). EndsWith (' C '):        #print (L.strip ())        List2.append (L.strip ()) print (LIST2)

3. Dictionaries

DiC = {' K1 ': ' Alx ', ' K2 ': ' Aric ', ' K3 ': ' Alx ', ' K4 ': ' Tny ', ' K5 ': '  Anc '} #定义一个空字典dic1 = {}for k,v in Dic.items ():    if (V.strip (). StartsWith (' a ') or V.strip (). StartsWith (' a ')) and V.strip (). EndsWith (' C '):        print (v)        dic1[k] = Vprint (DIC1)

Third, the output commodity list, the user enters the serial number, displays the user to select the product

#  Commodity li = ["Phone", "PC", "mouse pad", ' keyboard ']for num,v in Enumerate (li,1):     print (num,v) choice = Int (input ("SELECT Product:")) Choice1 =choice-1if choice1>=0 and Choice1<=len (LI)-1:    print (Li[choice1]) Else:     print ("Product does not exist")

Four, shopping cart
# Functional Requirements:
# requires the user to enter total assets, for example: 2000
# Display the list of items, let the user select items according to the serial number, add the shopping cart
# Purchase, if the total amount of goods is greater than the total assets, prompt account balance is insufficient, otherwise, the purchase succeeds.
# Additional: can recharge, a product to remove the shopping cart
Method One:

Goods = [    {"Product": "Computer", "Price": 1999},    {"Product": "Mouse", "Price": ten},    {"Product": "iphone", "Price": 50 XX},    {"Product": "Kindle", "Price": 998},] #已经买到的商品list_buy = [] #输入总资产all_money = 0all_money = Int (input ("Please enter total assets:")) #输出所有的产品for key,i in Enumerate (goods,1):    print (i[' product '],i[' price ') #当条件成立时, loop while buying link while True:    # Select the item you want to buy    choice = input ("Select item (y/y to settle purchase):")    #是否进行结算    if choice.lower () = = "Y": Break    # Loop all the goods in comparison with the selected commodity, if present, add to List_buy for    v in Goods: if        choice = = v["Product"]:            list_buy.append (v) # Output all products intended for purchase print (list_buy) #定义商品总价初始值total_price = 0for p in list_buy:    #计算所有商品价格    total_price = total_price+p ["Price"]if Total_price>all_money:    print ("Your money is not enough, please recharge%d yuan"% (Total_price-all_money))    Chongzhi = Int ( Input ("Enter recharge Amount:"))    All_money +=chongzhielse:    print ("buy success")    print (list_buy)

Method Two:

Goods = [{"Product": "Computer", "Price": 1999}, {"Product": "Mouse", "Price": ten}, {"Product": "iphone", "Price": 5000}, {"Product": "Kindle", "price": 998},]salary = Int (Input ("Enter Salary:")) #dic_shop_cart = {"Product": {"Price": 0, "num": 0}}dic _shop_cart = {} #循环输出所有产品for p in Goods:print (p[' product '],p[' prices ') while True:choice = input ("Please select the purchased item (y/y for settlement): ") if choice.lower () = = ' Y ': Break #循环所有商品 for item in goods: #判断选择的商品是否在所有商品中 if item[" prod UCT "] = = Choice: #如果存在, assign the product to product Product = item[" Product "#如果商品在字典dic_shop_cart中, dictionary In num add 1 if product in Dic_shop_cart.keys (): dic_shop_cart[product]["num"] = Dic_shop_cart[produc t]["num"] + 1 #如果不在, added to the dictionary for the first time else:dic_shop_cart[product] = {"num": 1, "SINGLE_PR Ice ": item[" Price "]} print (Dic_shop_cart) Sum_price = 0for k,v in Dic_shop_cart.items (): # print (k,v) T_price = v[" s  Ingle_price "]*v[" num "]  Print ("The number of purchased%s is%s: Total Price is%d"% (k,v["num"],t_price)) Sum_price=sum_price+t_priceprint ("All Products:%s"%sum_price) if sum_ Price>salary:print ("Your money is not enough, hahaha ... , don't buy it. Else:print ("Buy success, rich people ah ...) ")

Output Result:


V. User interaction, showing the choice of three-level linkage between provincial and municipal counties

DIC = {"    Hebei": {"        Shijiazhuang": ["Luquan", "Gaocheng", "Yuanshi"],        "Handan": ["Yongnian", "she County", "CI"],    },    "Beijing": {"        daxing": ["Huang Cun", "Qingyuan", "Heavenly Court"],        "Haidian": ["Zhongguancun", "West Two Flags", "five crossings"],    },    "Anhui": {"        Hefei": ["Luyang", "Feixi", "Binhu"],        "anqing": ["Tongcheng", "Yi Xiu District", "Yuexi "],    }}for p in dic:    print (p) p1 = input (" Please enter Province: ") if P1 in Dic.keys (): For    s in DIC[P1]:         print (s)    S1 = input ("Please enter Downtown:")    if S1 in Dic[p1].keys (): For        Q in  dic[p1][s1]:            print (q)    else:        Print ("No entry in the city") Else:    print ("The province has not been entered")

Execution Result:

Python Basic data type exercises

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.