python学习之路-day2

1.练习

 需求:三级菜单,输入目录地址进入下一级菜单

代码:

area={
    'hubei':{'huanggang':['qichun','wuxue','huangzhou'],
               'wuhan':['wuchang','hankou','hongshan']
            },
    'jiangsu':{'nanjing':['jianye','baixia','gulou'],
               'suzhou':['wuzhong','sugu','xiangcheng']
            }
    }
floor=area
empty_list=[]
while True:
    for key in floor:
        print(key)
    choice=input("请输入地址【返回/b,退出/q】:")
    if choice=='q':
        break
    if len(choice)==0:
        continue
    if choice in floor:  #如果输入的地址是当前列表的值
        empty_list.append(floor)   #先将当前列表加入空列表empty_list中中
        floor=floor[choice]
    elif choice =='b':
        if empty_list:
           floor=empty_list.pop()
    else:
        print("您输入的有误!")
View Code

运行结果:

hubei
jiangsu
请输入地址【返回/b,退出/q】:
View Code

2.练习

    需求:登陆认证

    代码: 

username="wang"
password="wang@123"
for i in range(3):
    _username=input("Please enter your name: ")
    _password=input("please enter your PIN:")
    if username==_username and password==_password:
        print("Welcome to log!")
        break
    else:
        print("You entered an incorrect user name or password")
print("Yours is temporarily locked!")
View Code

 

 

3.字符编码转换

    代码:

msg="我爱中国"
print(msg)
print(msg.encode(encoding="utf-8"))#将字符串转为bytes类型
print(msg.encode(encoding="utf-8").decode(encoding="utf-8"))#将bytes类型转为字符串类型
View Code

  

4.数组处理

    代码:

num=[10,11,12,13,14]
print(num)
num.append(15)#append方法给数组后面加元素
print(num)
num.insert(0,9)#insert方法给数组指定位置加元素
print(num)
num.remove(15)#删除数组中元素15
print(num)
del num[0]#删除第一个元素
print(num)
num.pop(0)#删除第一个元素
print(num)
View Code

5.os模块

    代码:

import os
#cmd_res=os.system("dir") #执行命令 不保存结果
cmd_res=os.popen("dir").read()
print("-->",cmd_res)
os.mkdir("new_dir")#新建目录  
View Code

  输出结果:

-->  驱动器 E 中的卷是 新加卷
 卷的序列号是 083D-2CEF

 E:pythonday2 的目录

2020/05/14  15:17    <DIR>          .
2020/05/14  15:17    <DIR>          ..
2020/05/13  14:44               373 log.py
2020/05/13  17:53               822 menu.py
2020/05/13  22:22               195 msg.py
2020/05/13  18:00    <DIR>          new_dir
2020/05/13  22:51               313 num.py
2020/05/13  18:04               156 sys_mod.py
2020/05/14  15:17             1,779 test.py
               6 个文件          3,638 字节
               3 个目录 199,113,728,000 可用字节
View Code

6.练习:

   需求:  

   (1)购物车程序,输入工资,选择购买的商品

   (2)购买结束打印购买商品列表及余额

    代码: 

product_list=[
    ('Iphone',5000),
    ('Watch',2000),
    ('Ipad',3000),
    ('Computer',6000),
    ('book',50)
]
shooping_cart=[]   #定义购物车
salary=(input("请输入您的工资:"))
while True:
    if salary.isdigit():#判断输入的内容是否为数字
        salary=int(salary) #将输入的数字转为整数型
        break
    else:
        print("请输入正确的数字")
        salary=(input("请输入您的工资:"))
while True:
    for index,item in enumerate(product_list):#可用enumerate方法获取元素索引
        print(index,item)
        #print(product_list.index(item),item)#或者直接打印索引
    user_choice=input("请选择您要购买的商品序号(或输入q退出):")
    if user_choice.isdigit():#判断输入的内容是否为数字
        user_choice=int(user_choice)#将输入的数字转为整数型
        if user_choice<len(product_list) and user_choice>=0:#判断输入的数字是否在合理范围内
            p_item=product_list[user_choice] #获得选择的商品
            if p_item[1]<=salary:  #判断商品价格是否小于余额(买的起)
                salary-=p_item[1]  #扣钱
                shooping_cart.append(p_item)#加购物车
                print("您购买了 %s ,余额剩余 %s "%(p_item,salary))
            else:
                print("您的余额不足")
        else:
            print("请输入正确的序号")
    elif user_choice=='q':
        print("---------您购买的商品列表-----")
        for i in shooping_cart:
            print(i)  #打印购物列表
        print("您的余额是 %s "%salary)
        print("购买结束")
        break
    else:
        print("请输入正确的序号")
View Code

 运行结果:

请输入您的工资:10000
0 ('Iphone', 5000)
1 ('Watch', 2000)
2 ('Ipad', 3000)
3 ('Computer', 6000)
4 ('book', 50)
请选择您要购买的商品序号(或输入q退出):q
---------您购买的商品列表-----
您的余额是 10000 
购买结束

Process finished with exit code 0
View Code

7.whlie循环

  代码:

1 current_number=1
2 while current_number<=5:
3     print(current_number)
4     current_number+=1
View Code

   让用户何时选择退出

1 prompt="
 Tell me something,and i will repeat it back to you:"
2 prompt+="
Enter 'quit' to end the program."
3 message=""
4 while message!='quit':#当输入的不是quit时,执行循环。直到输入的是quit,结束循环
5     message=input(prompt)
6     print(message)
View Code
  使用标志:我们将变量active设置成了True(见❶),让程序最初处于活动状态。这样做简化了while语句,因为不需要在其中做任何比较——相关的逻辑由程序的其他部分处理。只要变量active为True,循环就将继续运行(见❷)
1 promt="
Tell me something,and I will repeat it back to you:"
2 promt+="
Enter 'quit' to end the program."
3 ❶active=True
4while active:    #循环标志,直到它的状态为fales时停止
5     message=input(promt)
6     if message=='quit':
7         active=False
8     else:
9         print(message)
View Code
使用break退出循环
1 promt="
Please enter the name of a city you hava visited:"
2 promt+="
(Enter 'quit' when you are finished.)"
3 while True:  #while True打头的循环将不断运行,直到遇到break
4     city=input(promt)
5     if city=='quit':
6         break
7     else:
8         print("I'd love to go to "+city.title()+"!")
View Code
在循环中使用continue

1 current_number=0
2 while current_number<10:
3     current_number+=1
4     if current_number % 2 ==0:
5         continue  #判断当前数字是否为偶数,是就继续循环
6     print(current_number)
View Code

原文地址:https://www.cnblogs.com/awanghang/p/13257346.html