Python之路【第四篇】Python基础2
一、格式化输出
按要求输出信息

name=input("name:") age=int(input("age:")) job=input("job:") salary=input("salary:") if salary.isdigit(): #长得像不像数字,比如200d,‘200’ salary=int(salary) else: exit("must input digit!") msg=''' ---------info of %s------------- Name: %s Age: %d Job: %s Salary: %f You'll retire in %s years. -----------end------------------ '''%(name,name,age,job,salary,65-age) print(msg)
二.循环
登录三次,不成功打印error
(1)for循环

#passed_authentication=False for i in range(3): username=input("username:") passwd=input("password:") if username=="admin" and passwd=="admin": # passed_authentication=True print("Welcome!") break #跳出,中断 break for后就不会执行后面的else语句 else: print("try again!") else: #只要上面的循环正常执行完毕,中间没被打断,就会执行else语句 #if not passed_authentication: print("error!")
(2)while循环

counter=0 while counter<3: username=input("username:") passwd=input("password:") if username=="admin" and passwd=="admin": print("Welcome!") break #跳出,中断 break for后就不会执行后面的else语句 else: print("try again!") counter += 1 if counter==3: keep_going_choice=input("还想玩吗?[y/n]") if keep_going_choice=='y': counter=0 else: print("error!")
三、练习(购物车程序)

goods_list=[('iphone',6000),('mac',9000),('coffee',32),('python book',100),('bicycle',1500)] #print(len(goods_list)) cart=[] saving=input("please input your saving:") if saving.isdigit(): saving=int(saving) while True: # 打印商品内容 for i,v in enumerate(goods_list,1): #for后面可以接列表、元祖、字典 print(i,v) # 引导用户选择商品 choice=input("请输入您要购买的商品序号[退出:q]:") # 验证输入是否合法 if choice.isdigit(): choice=int(choice) if choice > 0 and choice <= len(goods_list) : # 通过choice取出用户选择的商品 p_item=goods_list[choice-1] print(p_item) # 如果余额充足,用余额减去选择的商品的价格,并将该商品加入购物车 if p_item[1] < saving: saving-=p_item[1] print('还剩%s元'%saving) cart.append(p_item) else: print('余额不足,还剩%s元'%saving) else: print('编码不存在!') elif choice=='q': print('-----您已经购买如下商品------') # 循环遍历购物车的商品,注意:购物车存放的是已买商品 for i in cart: print(i) print('您还剩%s元'%saving) break else: print('非法字符!') else: print('error!')