第五章 if语句

5.1 案例

  • if 中的比较运算符两边要添加空格
cars=['audi','bmw','toyota']
for car in cars:
    if car=='bmw':
        print(car.upper())
    else:
        print(car.title())

5.2 条件测试

  • 检查是否相等:==
  • 检查不相等:!=
  • 比较数字:< ;<=;>;>=
  • 同时满足多个条件:and
  • 至少有一个条件满足:or
  • 检查是否包含在列表中:book in books
  • 检查是否不包含在列表中:book not in books
  • 布尔表达式:a=True;b=False
cars=['audi','bmw','toyota']
car='audi'
print(car in cars)
car='lixiang'
print(car in cars)

image

5.3 if语句

  • 单一的if语句
  • if-else 语句
  • if-elif-else 语句

else是一个保罗万象的语句,只要不满足任何if或elif中的条件测试,其中的代码就会执行,这可能会引发无效甚至恶意的数据,如果指导最终要测试的条件,应考虑使用一个elif代码块来代替else代码块。

  • 多个if语句:不涉及否则

多个if可以执行多个代码块,if-else只能执行一个代码块

5.4使用if语句处理列表

5.4.1 检查特殊元素

cars=['audi','bmw','toyota']
for car in cars:
    if car=='audi':
        print('奥迪')
    else:
        print('不是奥迪')

image

5.4.2 确定列表不是空的

a=[]
if a:
    print("有元素")
else:
    print("没有元素")

image

5.4.3 使用多个列表

  • 判断一个列表中的元素是否在另一个列表中
cars=['audi','bmw','toyota']
buy_cars=['audi','lixiang']
for buy_car in buy_cars:
    if buy_car in cars:
        print(buy_car,"有库存")
    else:
        print(buy_car,"没有库存")

image

牛客刷题(43-48)

1.判断布尔值(43)

image

# 注意bool('0'), 字符串无论是'0'或'1'都为True,所以要先转为整形
a=bool(int(input()))
if a:
    print("Hello World!")
else:
    print("Erros!")

2.禁止重复注册(45)

image

current_users=['Niuniu','Niumei','GURR','LOLO']
new_users=['GurR','Niu Ke Le','LoLo','Tuo Rui Chi']
# 不区分大小写的话,需要全部转换为小写,再进行比较
for i in range(len(current_users)):
    current_users[i]=current_users[i].lower()
for new_user in new_users:
    if new_user.lower() in current_users:
        print('The user name '+new_user+' has already been registered! Please change it and try again!')
    else:
        print('Congratulations, the user name '+new_user+' is available!')

3.计算绩点(47)

image

grade_list={'A':4.0,'B':3.0,'C':2.0,'D':1.0,'F':0}
grades=[]
scores=[]
while True:
    grade=input()
    if grade=='False':#False需要是字符串
        break
    else:                  #注意这个部分
        score=int(input())
        grades.append(grade_list[grade]*score)
        scores.append(score)
print("%.2f"%(sum(grades)/sum(scores)))

image

posted @ 2022-11-08 12:32  Trouvaille_fighting  阅读(44)  评论(0编辑  收藏  举报