《Python编程:从入门到实践》-3 if语句

2022-08-22  本文已影响0人  Yayamia

if语句

①检查是否相等
car = 'bmw':赋值
car == 'bmw': 测试检查变量的值是否与特定的值相等,返回TRUE或FALSE
==的判断将区分大小写

②检查是否不相等
car != 'bmw'

③检查多个条件:为了改善可读性,可以将每个变量放在一个括号里
and
or

④检查特定值是否包含在列表中
in

>>> names = ["aaa", "bbb", "ccc"]
>>> "aaa" in names
True

⑤检查特定值是否不包含在列表中
not in

if conditional_test:
  do something
elif conditional_test:
else:
  do something

练习:

alien_colors = ["green", "yellow", "red"]
for alien_color in alien_colors:
   if alien_color == "green":
       score = 5
   elif alien_color == "yellow":
       score =10
   else:
       score = 0
   print(f"Your score is {score}")

Your score is 5
Your score is 10
Your score is 0
requested_toppings = []

if requested_toppings:
    for requested_topping in requested_toppings:
        print(f"Adding {requested_topping}.")
    print("\nFinished making your pizza!")
else:
    print("Are you sure you want a plain pizza?")

Are you sure you want a plain pizza?

if语句中将列表名用作条件表达式时,Python将在列表至少包含一个元素时返回TRUE,并在列表为空时返回“FALSE”

aas = ["a","b","c","d"]
bbs = ["a","B","D"]

for bb in bbs:
    print(f"{bb}")
    if bb in aas:
        print("yes\n")
    else:
        print("not in\n")

练习:

current_users = ["admin", "Kelly", "Peter", "jasmine"]
new_users = ["Yayamia", "Kelly", "peter"]
current_users1 = [current_user.lower() for current_user in current_users]#创建一个所有用户名的小写版本
current_users1
for new_user in new_users:
    if new_user.lower() in current_users1: #保证比较时不区分大小写
        print(f"{new_user} has already been occupied.")
    else:
        print(f"you can use {new_user}!")

nums = list(range(1,10))
for num in nums:
    if num == 1:#注意区分=和==
        print("1st")
    elif num == 2:
        print("2nd")
    elif num == 3:
        print("3rd")
    else:
        print(f"{num}th")

关于格式的提醒: 在运算两边各添加一个空格

上一篇下一篇

猜你喜欢

热点阅读