• 第一模块·开发基础-第3章 作业讲解


    • 01-三级菜单作业讲解之普通青年版;
    • 02-三级菜单作业讲解之普通青年版2;
    • 03-三级菜单作业讲解之装逼版;
    • 04-三级菜单作业讲解之装逼版2;

    01-三级菜单作业讲解之普通青年版;

    02-三级菜单作业讲解之普通青年版2;

    03-三级菜单作业讲解之装逼版;

    04-三级菜单作业讲解之装逼版2;

     1 #!/usr/bin/env python
     2 # -*- coding:utf8 -*-
     3 #__author__:TQTL
     4 #date: 2018/5/7 16:18
     5 # 基础需求:
     6 # 1、让用户输入用户名密码;
     7 # 2、认证成功后显示欢迎信息;
     8 # 3、输错三次后退出程序;
     9 
    10 #Request分析过程;
    11 #Step1:自行定义变量counter(计数器)、username(用户名)、password(密码);
    12 #Step2:使用input关键字获取用户输入;
    13 #Step3:进行用户名与、密码与用户输入正确与否的合法性判断,并打印相应提示语;
    14 #Step4:将程序嵌套作为循环体套至while循环中;
    15 #Step5:自行进行功能的测试校验;
    16 username = "tqtl911"#tqtl为"天晴天朗的拼音首字母缩写,崔晓昭的alias就叫做:天晴天朗;希望每个人都有一个自己的'专属标签',比如金角大王Alex,银角大王Wu sir;
    17 password = "Ab123456."#设置一个复杂度较高的密码;
    18 times = 1#定义一个计数器变量times;
    19 cycles = 3#定义一个可循环次数变量cycles;
    20 while times <= cycles:#进入循环体;
    21     input_username = input("亲,Please input your Username:")
    22     input_password = input("你好,Please input your Password:")
    23     if input_username == username and input_password == password:
    24         print("Congratulations on you %s,Welcome to visit https://www.luffycity.com/路飞学城,帮助有志向的年轻人通过努力学习获得体面的工作和生活!!!"%input_username)
    25         break  # 输入正确后,先打印日志,再结束循环;
    26     elif input_username.strip()=="" or input_password.strip()=="":#使用字符串的strip方法,进行空字符的判断;
    27         print("Username or Password is null,Please input both.")
    28     else:
    29         print("Sorry your Username or Password is invalid, Check them carefully again please.")
    30     times += 1#每循环一次增加1,但此处times可缩进至print下,与现有的缩进效果相同,但个人觉得应该使用当前times的位置;
    31 else:#while~else用法;
    32     print("You hava try %s times,Game is over,See you again."%cycles)
    登录认证程序之基础需求
     1 #!/usr/bin/env python
     2 # -*- coding:utf8 -*-
     3 #__author__:TQTL
     4 #date: 2018/5/8 12:51
     5 # 升级需求:
     6 #1、可以支持多个用户登录 (提示,通过列表存多个账户信息);
     7 #2、用户3次认证失败后,退出程序,再次启动程序尝试登录时,还是锁定状态(提示:需把用户锁定的状态存到文件里);
     8 #Request分析过程;
     9 #Step1:将多个用户信息存储之一个list中;
    10 #Step2:分别定义计数器和循环次数变量
    11 #Step3:先打开文件,进行读取,如果已存在登录失败用户信息,将拒绝再次登录;
    12 #Step4:进行列表的遍历操作并与用户输入的值进行比对,给出相应提示语;
    13 #Step5:将登录失败用户信息写入文件(追加写入),循环次数+1,最后关闭文件;
    14 authentication= [
    15     ['cxz19930911','19930911cxz'],
    16     ['cxs19920519','19920519cxs'],
    17     ['cxs19871001','19871001cxs']
    18     ]#定义一个用户认证信息列表,包含用户名和密码;
    19 times = 0#定义一个计数器;
    20 cycles = 3#
    21 error_times = 0 #错误输入计数初始化;
    22 while times < cycles:
    23     file = open(file = "UserStatus.txt",mode = 'r',encoding = "utf-8")#自行创建文件UserStatus.txt并与程序放置于同一目录下;
    24     user_status = file.read()
    25     input_username = input("亲,Please input your Username:").strip()#字符串的strip方法去除多余空格
    26     input_password = input("你好,Please input your Password:").strip()
    27     if input_username.strip() == "" or input_password.strip() == "":#使用字符串的strip方法,进行空字符的判断;
    28         print("Username or Password is null,Please input both.")
    29     elif input_username in user_status: #首先,判断该用户是否被锁定;
    30         print("Sorry,the user %s is locked!You can't use this user to login our website anymore."%input_username)
    31         break
    32     else:
    33         for index,p in enumerate(authentication):#使用枚举
    34             if input_username == p[0] and input_password == p[1]:
    35                 print("Congratulations on you %s,Welcome to visit https://www.luffycity.com/路飞学城,帮助有志向的年轻人通过努力学习获得体面的工作和生活!"%input_username)
    36                 exit()#直接退出程序;
    37             else:
    38                 file = open(file = "UserStatus.txt",mode ='a+',encoding="utf-8")
    39                 error_times += 1
    40                 if error_times == 3*cycles:  #存储3个用户信息,for循环每次循环3次,cycles为循环次数;
    41                     file.write("User %s status is locked,you can't login anymore"%input_username)
    42         print("Sorry your Username or Password is invalid, Check them carefully again please.")
    43     times += 1
    44     file.close()#打开文件之后,一定记得关闭;
    登录认证程序之升级需求
     1 #! /usr/bin/env python
     2 # -*- coding:utf-8 -*-
     3 #__author__ = "tqtl"
     4 # Date:2018/5/13 23:06
     5 # 需求:
     6 # 可依次选择进入各子菜单;
     7 # 可从任意一层往回退到上一层;
     8 # 可从任意一层退出程序;
     9 # 所需新知识点:列表、字典;
    10 menu = {
    11     '北京':{
    12         '海淀':{
    13             '五道口':{
    14                 'soho':{},
    15                 '网易':{},
    16                 'google':{}
    17             },
    18             '中关村':{
    19                 '爱奇艺':{},
    20                 '汽车之家':{},
    21                 'youku':{},
    22             },
    23             '上地':{
    24                 '百度':{},
    25             },
    26         },
    27         '昌平':{
    28             '沙河':{
    29                 '老男孩':{},
    30                 '北航':{},
    31             },
    32             '天通苑':{},
    33             '回龙观':{},
    34         },
    35         '朝阳':{},
    36         '东城':{},
    37     },
    38     '上海':{
    39         '闵行':{
    40             "人民广场":{
    41                 '炸鸡店':{}
    42             }
    43         },
    44         '闸北':{
    45             '火车站':{
    46                 '携程':{}
    47             }
    48         },
    49         '浦东':{},
    50     },
    51     '山东':{},
    52 }
    53 current_layer,layers = (menu,[])#定义变量current_layer,layers;
    54 while True:
    55     for keys in current_layer:print(keys)#合成一层展示;
    56     choice = input(">>>:").strip()#strip方法去除多余字符;
    57     if not choice:continue#简化写法,省一行代码;
    58     if choice in current_layer:
    59         layers.append(current_layer);current_layer = current_layer[choice]#虽说省去一行代码,但是Python风格规范不建议这么书写;
    60     elif choice == 'b':#使用b代表回退一层,back的缩写;
    61         if len(layers) != 0:#层数为0时候pop()方法会报错,添加判断;
    62             current_layer = layers.pop()
    63         else:
    64             print("Back to the first floor.")
    65     elif choice == 'q':#使用b代表退出程序,quit的缩写;
    66         exit("exit the three layers menu program.")
    三级菜单之简化版
     1 #! /usr/bin/env python
     2 # -*- coding:utf-8 -*-
     3 #__author__ = "tqtl"
     4 # Date:2018/5/13 14:15
     5 # 数据结构:
     6 # goods = [
     7 # {"name": "电脑", "price": 1999},
     8 # {"name": "鼠标", "price": 10},
     9 # {"name": "游艇", "price": 20},
    10 # {"name": "美女", "price": 998},
    11 # ......
    12 # ]
    13 # 功能要求:
    14 # 基础要求;
    15 # 1、启动程序后,输入用户名密码后,让用户输入工资,然后打印商品列表
    16 # 2、允许用户根据商品编号购买商品
    17 # 3、用户选择商品后,检测余额是否够,够就直接扣款,不够就提醒
    18 # 4、可随时退出,退出时,打印已购买商品和余
    19 # 5、在用户使用过程中, 关键输出,如余额,入商品已加购物车等消息,需高亮显示
    20 goods = [
    21 {"name": "电脑", "price": 1999},
    22 {"name": "鼠标", "price": 10},
    23 {"name": "游艇", "price": 20},
    24 {"name": "美女", "price": 998},
    25 ]
    26 shopping_trolley = []  # 自定义一个购物车"空列表"shopping_trolley;
    27 exit_flag = False  # 自定义一个标志位变量exit_flag;
    28 username = "tqtl"
    29 password = "Ab123456."
    30 goods_format = "Welcome %s to visit our shopping website,Here are the products list" #定义字符串变量,后续调用;
    31 shopping_trolley_format = "Hi,Customer %s,You have bought the following goods, Please check the order"
    32 salary_format = "Your salary is left %s¥,Wishing you a happy shopping experience."
    33 input_username = input("Please input your Username:")
    34 input_password = input("Please input your Password:")
    35 if input_username == username and input_password == password:
    36     salary = input("Please input your salary:")
    37     if salary.isdigit():
    38         salary = int(salary)#工资为float类型;
    39         while not exit_flag:
    40             print(goods_format.center(100, '-')%username)#满足需求,使用字符串的center方法,以"#"分割,高亮显示;
    41             for index,p in enumerate(goods,1):#enumerate,枚举方法展示列表明细项;
    42                 print("%s. %s %s¥" %(index,p['name'],p['price']))  # 将人民币以¥展示;
    43             user_input = input("Please input the product number:")
    44             if user_input.isdigit():
    45                 user_input = int(user_input)
    46                 if user_input >= 0 and user_input <= len(goods):  # 此处使用=,报错IndexError: list index out of range
    47                     goods_items = goods[user_input-1]  # 将用户的输入选项赋值给商品明细项变量goods_items;
    48                     if goods_items['price'] < salary:
    49                         salary -= goods_items['price']
    50                         shopping_trolley.append(goods_items) # list下append方法追加至购物车中;
    51                         print("The goods item %s you selected has been added to the shopping trolley." %goods_items)
    52                     else:
    53                         print("Your salay is not enough to afford to this good,you have left %s¥," %salary,"You need %s¥ more."%(goods_items['price']-salary))
    54                 else:
    55                     print("The product number entered is not within the legal scope,Please check it carefully.")
    56             elif user_input.strip() == "":
    57                 print("Your input is empty, Please input again.")
    58             elif user_input == "Q" or user_input == "q":
    59                 if len(shopping_trolley) > 0:  #通过购物车的列表长苏判断购物车是否为空;
    60                     print(shopping_trolley_format.center(100,'#')%username)#满足需求,"#"分割,高亮显示;
    61                     for index,p in enumerate(shopping_trolley,1):  # 此刻,遍历购物车列表;
    62                         print("%s. %s %s¥" % (index, p['name'], p['price']))  # 将购买的商品编号从1开始显示,即index+1;
    63                     print(salary_format.center(100,'&')%salary)
    64                     exit_flag = True  # 调制标志位的值,结束循环;
    65             else:
    66                 print("Invalid goods number input,Please check the number carefully.")  # 输入为Q、q以及数字之外的值,给出错误提示语;
    67     else:
    68         print("Invalid salary input,Please check the salary input carefully.")
    69 else:
    70     print("Invalid Username or Pasword input,you can't input the salary,program is ended.")
    购物车程序之基础需求
     1 #! /usr/bin/env python
     2 # -*- coding:utf-8 -*-
     3 #__author__ = "tqtl"
     4 # Date:2018/5/13 17:47
     5 # 扩展需求:
     6 # 1、用户下一次登录后,输入用户名密码,直接回到上次的状态,即上次消费的余额什么的还是那些,再次登录可继续购买;
     7 # 2、允许查询之前的消费记录;
     8 goods = [
     9 {"name":"电脑","price":1999},
    10 {"name":"鼠标","price":10},
    11 {"name":"游艇","price":20},
    12 {"name":"美女","price":998}
    13 ]
    14 shopping_trolley = []# 自定义一个购物车"空列表"shopping_trolley;
    15 account = []#自定义一个余额空列表account
    16 goods_format = "Welcome %s to visit our shopping website,Here are the products list."#定义字符串变量,后续调用;
    17 shopping_format = "Hi,Customer %s,You have bought the following goods, Please check the order."
    18 salary_format = "Your salary is left %s¥,Wishing you hava a happy shopping experience."
    19 #Step1:进行登录认证校验;
    20 times = 0#定义一个计数器;
    21 cycles = 3#
    22 username = "tqtl"
    23 password = "Ab123456."
    24 while times < cycles:
    25     input_username = input("亲,Please input your Username:").strip()#字符串的strip方法去除多余空格
    26     input_password = input("你好,Please input your Password:").strip()
    27     if input_username == "" or input_password == "":#进行空字符的判断;
    28         print("Username or Password is null,Please input both.")
    29     elif input_username == username and input_password == password:
    30         print("Welcome to visit our shopping website.")
    31         break
    32     else:
    33         print("Sorry your Username or Password is invalid, left %s times"%(cycles-times-1))
    34     times += 1
    35 else:
    36     print("You have try %s times,exit this program."%cycles)
    37 #Step2:打开账户余额文件;
    38 with open(file = 'account_left.txt',mode = 'r',encoding = 'utf-8') as file_account:#本次使用了with方法打开文件,避免了忘记f.close()关闭文件;
    39     list_account = file_account.readlines()
    40 if len(list_account) == 0:
    41     salary = input("Please input your salary:").strip()
    42     if salary.isdigit():
    43         salary = int(salary)
    44     account.append(salary)
    45 else:
    46     history_account = int(list_account[0].strip('
    '))#|n,将存储的值换换行保存;
    47     account.append(history_account)
    48 #Step3:进入循环体;
    49 exit_flag = False  # 自定义一个标志位变量exit_flag;
    50 while not exit_flag:
    51     print(goods_format.center(100,'-')%username)#满足需求,使用字符串的center方法,以"#"分割,高亮显示;
    52     for index,rows in enumerate(goods,1):#enumerate,枚举方法展示列表明细项;
    53         print("%s. %s %s¥" %(index,rows['name'],rows['price']))  # 将人民币以¥展示;
    54     user_input = input("Please input the product number:(exit the program can input[q/Q],find the purchase record can input[f/F])").strip()
    55     if user_input.isdigit():
    56         user_input = int(user_input)
    57         if user_input > 0 and user_input <= len(goods):  # 此处使用=,报错IndexError: list index out of range
    58             goods_items = goods[user_input-1]  # 将用户的输入选项赋值给商品明细项变量goods_items;
    59             if  account[0] >= goods_items['price']:
    60                 shopping_trolley.append(goods_items) # list中的append方法追加至购物车中;
    61                 history_data = goods_items['name'] + ':' + str(goods_items['price'])+'
    '#字符串的拼接;
    62                 with open(file = 'history_goods.txt',mode='a',encoding='utf-8') as history_goods:
    63                     history_goods.write(history_data)
    64                 account[0] -= goods_items['price']#余额扣款
    65                 print("The goods item %s you selected has been added to the shopping trolley."%(goods_items['name']))
    66             else:
    67                 print("Your salay is not enough to afford this good,you have left %s¥,"%account[0],"You need %s¥ more."%(goods_items['price']-account[0]))
    68         else:
    69             print("The product number input is not within the legal scope,Please check it carefully.")
    70 #Step4:空输入的判断;
    71     elif user_input == "":#此处不再重复使用strip方法;
    72         print("Your input is empty,Please input again.")
    73 #Step5:进行退出;
    74     elif user_input == "Q" or user_input == "q":
    75         if len(shopping_trolley) > 0:  #通过购物车的列表长度判断购物车是否为空;
    76             print(shopping_format.center(100,'#')%username)#满足需求,"#"分割,高亮显示;
    77         else:
    78             print("You haven't done shopping yet.")
    79         for index,rows in enumerate(shopping_trolley,1):  # 此刻,遍历购物车列表;
    80             print("%s. %s %s¥" % (index,rows['name'],rows['price']))# 将购买的商品编号从1开始显示;
    81         print(salary_format.center(100,'&')%account[0])
    82         with open(file = 'account_left.txt',mode='r+',encoding='utf-8') as file_account:
    83             file_account.write(str(account[0])+'
    ')
    84         exit_flag = True  #调制标志位的值,结束循环;
    85 #Step6:进行历史记录的查找;
    86     elif user_input == "f" or user_input == "F":
    87         with open(file = 'history_goods.txt',mode='r',encoding='utf-8') as history_goods:
    88             list_history = history_goods.readlines()
    89         if len(list_history) > 0:
    90             print(shopping_format.center(100,'#')%username)  # 满足需求,"#"分割,高亮显示;
    91             for index,rows in enumerate(list_history,1):
    92                 (name,price) = rows.strip('
    ').split(':')#split方法进行分割;
    93                 print("%s. %s %s"%(index,name,price))
    94         else:
    95             print("No history shopping records.")
    96     else:
    97         print("Invalid number input,Please check the number carefully.")  # 输入为Q&q、f&F以及数字之外的值,给出错误提示语;
    购物车程序之升级需求
     1 #!/usr/bin/env python
     2 # -*- coding:utf8 -*-
     3 #__author__:TQTL
     4 #date: 2018/5/16 15:31 
     5 # Author:TQTL
     6 # E-mail:tqtl911@163.com
     7 # 1、猜数字游戏,预设一个0~9之间的整数,让用户猜一猜并输入所谓的数,如果大于预设的数,显示“太大”,
     8 # 小于预设的数字,显示“太小”;
     9 # 如此循环,直至猜中改数字,显示“恭喜,你猜中了!”;
    10 #default_int = 6
    11 # 生成 0 ~ 9 之间的随机数
    12 # 导入 random(随机数) 模块
    13 import random#导入随机数模块;
    14 default_int = random.randint(0,9)#通过
    15 print("你好,随机生成的0~9之间的数字为:",default_int)
    16 exit_flag = True#定义一个标志位;
    17 while exit_flag:
    18     user_input = int(input("Please input a number:"))
    19     if user_input > default_int:
    20         print("太大")
    21     elif user_input < default_int:
    22         print("太小")
    23     else:
    24         print("恭喜,你猜中了!")
    25         break#猜中后,结束循环;
    26         exit_flag = False
    27 # 2、编写一个P程序,输入两个数,比较他们的大小并输出其中较大者;
    28 number01 = int(input("Please input the first Number:"))
    29 number02 = int(input("Please input the second Number:"))
    30 if number01 > number02:
    31     print("The bigger Number is the first number:%d"%number01)
    32 elif number01 < number02:
    33     print("The bigger Number is the second number: %d"%number02)
    34 else:
    35     print("Two Numbers are equal.")
    36 # 3、有四个数字,1,2,3,4,能组成多少个互相不同且无重复数字的三位数,各是多少?
    37 
    38 # 程序分析,可填写在百位、十位、个位的数字都是1,2,3,4,组成所有的排列后再去掉不满足条件的排列;
    39 #定义个位、十位、百位的数字分别为:z,y,x
    40 exit_flag = True#定义一个标志位;
    41 cycles = 0  # 定义循环起止点0;
    42 while exit_flag:
    43     start =int(input("Please input the start number:"))#定义range的起始点,程序容易维护;
    44     end = int(input("Please input the end number:"))#定义rangge的结束点,程序容易修改;
    45     while exit_flag:
    46         if end < start:
    47             print("起止数续小于结尾数字。")
    48             break
    49         elif end > start:
    50             break
    51             exit_flag = False
    52         else:
    53             print("The beginning and the end cannot be the same.")
    54             break
    55     lines = (end-start-1)*(end-start-2)#每行显示的第1位数字相同的组合数字的个数,比如123|124|132|134|142|143的总个数为6
    56     for x in range(start,end):#先进入百位循环;
    57         for y in range(start,end):#进入十位循环;
    58             for z in range(start,end):#进入个位循环;
    59                 if x != y and y != z and z != x:
    60                     cycles += 1
    61                     if cycles % lines:#每行仅显示第1位数字相同的组合数字,比如百分位均为1的组合数字,作为第一行显示,百分位为2的数字作为二行显示;
    62                         print("%d%d%d"%(x,y,z),end="|".center(0,' '))#以5个空格分隔'|'符号;
    63                     else:
    64                         print("%d%d%d"%(x,y,z))
    65                         break
    66     user_input = input("是否继续玩耍呢?[Y/y],退出程序请输入:[Q/q]")
    67     if user_input == "Y" or user_input == "y":
    68         exit_flag = True#将标志位重新定义为True后,继续重新进入while循环体;
    69     elif user_input == "q" or user_input =="Q":#quit的缩写;
    70         print("Exited the program,Welcome to come here next time.")
    71         break
    72     else:
    73         print("Game Over.")
    74         break#猜中后,结束循环;
    75         exit_flag = False#将标志位定义为False后,不再进入while循环体;
    张导师提供练习题
  • 相关阅读:
    objective-c保护属性
    第十七章、程序管理与 SELinux 初探 工作管理 (job control)
    第十七章、程序管理与 SELinux 初探
    Shell运算符:Shell算数运算符、关系运算符、布尔运算符、字符串运算符等
    go语言初始化内部结构体3中方式
    数据结构之C语言模拟整数数组实现
    使用python将元组转换成列表,并替换其中元素
    ruby中的类实例变量和实例的实例变量
    读<<programming ruby>> 7.6节 flip-flop 理解
    ruby逻辑判断符号
  • 原文地址:https://www.cnblogs.com/tqtl911/p/9019936.html
Copyright © 2020-2023  润新知