python表达是 if-else,for,while loop,三元运算

表达式if ... else

登录场景:

# 提示输入用户名和密码

# 验证用户名和密码
#     如果错误,则输出用户名或密码错误
#     如果成功,则输出 欢迎,XXX!


userName=input("请输入用户名:")
userPwd=input("请输入密码:")

if userName=='tom' and userPwd=='123456':
    print("欢迎!")
else:
    print("用户名,密码错误")
View Code

#在程序里设定好你的年龄,然后启动程序让用户猜测,用户输入后,根据他的输入提示用户输入的是否正确,如果错误,提示是猜大了还是小了

myAge=22

userInput=int(input("please input age:"))
if userInput==myAge:
    print("Congratulations, you got it !")
elif userInput > myAge:
    print("bigger!")
else:
    print("small!")
View Code

外层变量,可以被内层代码使用
内层变量,不应被外层代码使用

表达式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)
View Code

表达式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)
View Code

 三元运算

result = 值1 if 条件 else 值2

如果条件为真:result = 值1
如果条件为假:result = 值2

程序:购物车程序

需求:

  1. 启动程序后,让用户输入工资,然后打印商品列表
  2. 允许用户根据商品编号购买商品
  3. 用户选择商品后,检测余额是否够,够就直接扣款,不够就提醒 
  4. 可随时退出,退出时,打印已购买商品和余额
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("33[31;1m你的钱不够了33[0m")
        else:
            print("商品不存在")
    elif choice=='exit':
        print("你本次购物为:",carList)
        print("你剩余钱:", salary)
        break
View Code

作业一:博客

作业二:编写登陆接口

  • 输入用户名密码
  • 认证成功后显示欢迎信息
  • 输错三次后锁定
作业三:多级菜单
  • 三级菜单
  • 可依次选择进入各子菜单
  • 所需新知识点:列表、字典
原文地址:https://www.cnblogs.com/wuchangsoft/p/13604815.html