表达式if ... else
登录场景:

# 提示输入用户名和密码 # 验证用户名和密码 # 如果错误,则输出用户名或密码错误 # 如果成功,则输出 欢迎,XXX! userName=input("请输入用户名:") userPwd=input("请输入密码:") if userName=='tom' and userPwd=='123456': print("欢迎!") else: print("用户名,密码错误")
#在程序里设定好你的年龄,然后启动程序让用户猜测,用户输入后,根据他的输入提示用户输入的是否正确,如果错误,提示是猜大了还是小了

myAge=22 userInput=int(input("please input age:")) if userInput==myAge: print("Congratulations, you got it !") elif userInput > myAge: print("bigger!") else: print("small!")
外层变量,可以被内层代码使用
内层变量,不应被外层代码使用
表达式for loop

#pass 通过 for i in range(10): if i == 5: pass else: print('loop', i) #break 跳出当前层的循环 for i in range(10): if i == 5: braek else: print('loop', i) #continue 跳出本次循环,进入下一次循环 for i in range(10): if i == 5: continue else: print('loop', i)
表达式while loop

import time # count=0 # while True: # print("这是一个死循环",count) # count +=1 to_start=time.time() count0=0 while True: if count0==10000: break count0+=1 print("cost0:",time.time() - to_start,count0)
三元运算
result = 值1 if 条件 else 值2
如果条件为真:result = 值1
如果条件为假:result = 值2
程序:购物车程序
需求:
- 启动程序后,让用户输入工资,然后打印商品列表
- 允许用户根据商品编号购买商品
- 用户选择商品后,检测余额是否够,够就直接扣款,不够就提醒
- 可随时退出,退出时,打印已购买商品和余额

carList=[] #购物车列表 goodsList=[["iphone7",6500],["macbook",12000],["pythonbook",66],["bike",999],["coffee",31],] salary = int(input("请输如你的工资:")) while True: for index,i in enumerate(goodsList): print("%s: %s %s" %(index,i[0],i[1])) choice=input("请输入商品编号>>:") if choice.isdigit(): choice=int(choice) if choice < len(goodsList) and choice >=0: print("你目前有多少钱:",salary) product_item=goodsList[choice] if salary > product_item[1]: salary -= product_item[1] carList.append(product_item) print(carList) else: print("