zoukankan      html  css  js  c++  java
  • 一个简单的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("{}:	{}".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:StudyPythonCodevenvScriptspython.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('{}		{}'.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()。眼高手低,应加强动手能力。

  • 相关阅读:
    正则表达式 之领宽断言
    bat(续七)-for语句(循环结构)
    RBAC权限管理
    Redis缓存服务搭建及实现数据读写
    Myeclipse集成Maven(图文说明)
    实习第四周
    POJ 3461 Oulipo KMP算法题解
    原创文章
    apue和unp的学习之旅07——多种边界条件的讨论
    单链表的实现
  • 原文地址:https://www.cnblogs.com/ChinacloudTech/p/9860738.html
Copyright © 2011-2022 走看看