一個簡單的python練習題


最近幾天看了python的基礎知識,也寫了兩篇博客:http://futuretechx.com/python2/ http://futuretechx.com/python-basicknowl/ 但總感覺動手擼代碼的能力有所欠佳,周末沒事就做了一個小練習。一下是需求:

'''
4、輸出商品列表,用戶輸入序號,顯示用戶選中的商品
    商品 li = ["手機", "電腦", '鼠標墊', '游艇']
要求:1:頁面顯示 序號 + 商品名稱,如:
      	1 手機
	   	2 電腦
     		 …
     2: 用戶輸入選擇的商品序號,然后打印商品名稱
  3:如果用戶輸入的商品序號有誤,則提示輸入有誤,並重新輸入。
4:用戶輸入Q或者q,退出程序。

'''

沒有看答案,先自己寫了一遍,以下是我自己的代碼

li=["手機","電腦","鼠標墊","游艇"]
print("商品列表:")
for i in li :
    print("{}:\t{}".format(li.index(i)+1,i))

while True :
    strOrder=input("請輸入你要選的商品序號(Q/q 退出):")
    if strOrder.isdigit() :
        numOrder = int(strOrder)
        if numOrder < 5 and numOrder >0 :
            print(li[numOrder-1])
        else :
            print("number is more than large! Please input it again!")
    elif strOrder.upper()!="Q" :
        print("input error, Please input number and try it again!")
    else :
        print("exit!")
        break

輸出結果:

D:\Study\Python\Code\venv\Scripts\python.exe D:/Study/Python/Code/Storebuy
商品列表:
1:	手機
2:	電腦
3:	鼠標墊
4:	游艇
請輸入你要選的商品序號(Q/q 退出):1
手機
請輸入你要選的商品序號(Q/q 退出):2
電腦
請輸入你要選的商品序號(Q/q 退出):3
鼠標墊
請輸入你要選的商品序號(Q/q 退出):s
input error, Please input number and try it again!
請輸入你要選的商品序號(Q/q 退出):7
number is more than large! Please input it again!
請輸入你要選的商品序號(Q/q 退出):0
number is more than large! Please input it again!
請輸入你要選的商品序號(Q/q 退出):-5
input error, Please input number and try it again!
請輸入你要選的商品序號(Q/q 退出):q
exit!

 

給自己打90分吧,基本能實現需求。但有些不完美的地方。比如說。       

  1. if numOrder < 5 and numOrder >0 : 這里寫死了,沒有考慮到動態的情況。
  2. while添加一個flag比較好。能判斷flag的bool值

以上想法也是看到標准答案之后才想起來的。以下是給出的答案:

flag = True
while flag:
    li = ["手機", "電腦", "鼠標墊", "游艇"]
    for i in li:
        print('{}\t\t{}'.format(li.index(i)+1,i))
    num_of_chioce = input('請輸入選擇的商品序號/輸入Q或者q退出程序:')
    if num_of_chioce.isdigit():
        num_of_chioce = int(num_of_chioce)
        if num_of_chioce > 0 and num_of_chioce <= len(li):
            print(li[num_of_chioce-1])
        else:print('請輸入有效數字')
    elif num_of_chioce.upper() == 'Q':break
    else:print('請輸入數字')

 總結: 這么簡單一個問題,寫了半個小時,基礎知識還是不牢固,有些函數只知道名字,不知道具體用法。比如說format()。眼高手低,應加強動手能力。


免責聲明!

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



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