• python---分支控制、循环控制语句


    一、分支控制语句

    条件测试

    检查是否相等

    两个等号==,返回True或者False。

    检查是否相等时不考虑大小写
    1. car = "Audi"
    2. print(car.lower() == 'audi')
    3. print(car)

    lower()函数不改变存储在变量car中的值。

    检查是否不相等

    !=

    比较数字

    ==、<、<=、>、>=、

    多个检查条件

    and、or

    检查特定值是否包含在列表中
    1. requested_toppings = ['mushrooms', 'onions', 'pineapple']
    2. print('mushrooms' in requested_toppings)
    3. print('pepperoni' in requested_toppings)

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

    1. requested_toppings = ['mushrooms', 'onions', 'pineapple']
    2. print('mushrooms' not in requested_toppings)
    3. print('pepperoni' not in requested_toppings)
    布尔表达式

    注意大小写:

    True或者False

    if语句

    简单if语句

    if  conditional_test:

    do something

    1. age = 19
    2. if age >= 18:
    3. print("ok")

    if-else语句

    1. age = 19
    2. if age >= 18:
    3. print("ok")
    4. else:
    5. print("no ok")

    if-elif-else结构

    1. age = 12
    2. if age < 4:
    3. print("小朋友")
    4. elif age > 18:
    5. print("年轻人")
    6. else:
    7. print("该写作业了")
    多个elif代码块
    省略else代码块
    确定列表不是空的
    1. requested_toppings = []
    2. if requested_toppings:
    3. for requested_topping in requested_toppings:
    4. print(requested_topping)
    5. else:
    6. print("空的列表")

    二、python中的循环控制语句

    while循环

    python不支持do ~ while循环。

    使用while循环
    1. current_number = 1
    2. while current_number <= 5:
    3. print(current_number)
    4. current_number += 1

    让用户选择何时退出

    1. prompt = "\nTell me something, and I will repeat it back to you:"
    2. prompt += "\nEnter 'quit' to end the program."
    3. message = ""
    4. while message != 'quit':
    5. message = input(prompt)
    6. print(message)

    发现'quit'一并打印出来,改进:

    1. prompt = "\nTell me something, and I will repeat it back to you:"
    2. prompt += "\nEnter 'quit' to end the program."
    3. message = ""
    4. while message != 'quit':
    5. message = input(prompt)
    6. if message != 'quit':
    7. print(message)
    使用标志

    在要求很多条件满足才能继续运行的程序中,可以定义一个变量,用于判断整个程序是否处于活动状态,该变量称为标志。可让标志为True时继续运行,False时终止运行。

    1. prompt = "\nTell me something, and I will repeat it back to you:"
    2. prompt += "\nEnter 'quit' to end the program."
    3. active = True
    4. while active:
    5. message = input(prompt)
    6. if message == 'quit':
    7. active = False
    8. else:
    9. print(message)

    使用break退出循环

    1. prompt = "\nPlease enter the name of a city you have visited:"
    2. prompt += "\n(Enter 'quit' when you are finished.)"
    3. while True:
    4. city = input(prompt)
    5. if city == 'quit':
    6. break
    7. else:
    8. print("I'd love to go to " + city.title() + "!")

    在循环中使用continue

    1. current_number = 0
    2. while current_number < 10:
    3. current_number += 1
    4. if current_number % 2 == 0:
    5. continue
    6. print(current_number)
    避免无限循环

    如果程序陷入无限循环,可按Ctrl+C,也可关闭显示程序输出的终端窗口。

    使用while循环处理列表和字典

    for循环是一种遍历列表的有效方式,但是for循环中不应该修改列表,否则将导致Python难以跟踪其中的元素。要在遍历列表的同时对其进行修改,可使用while循环。通过while循环同列表和字典结合使用,可收集、存储并组织大量输入。

    在列表之间移动元素
    1. uncomfirmed_users = ['alice', 'brian', 'candace']
    2. confirmed_users = []
    3. # 验证每个用户,直到没有未验证的用户为止
    4. # 将每个通过验证的用户都移动到已验证用户列表
    5. while uncomfirmed_users:
    6. current_user = uncomfirmed_users.pop()
    7. print("Verifying user: " + current_user.title())
    8. confirmed_users.append(current_user)
    9. # 显示所有已验证的用户
    10. print("\nThe following users have been confirmed:")
    11. for confirmed_user in confirmed_users:
    12. print(confirmed_user)
    删除包含特定值的所有列表元素

    假如有一个宠物列表,其中包含多个值为'cat'的元素,要删除所有这些元素,可以使用while循环:

    1. pets = ['dog', 'cat', 'dog', 'goldfish', 'cat', 'rabbit', 'cat']
    2. print(pets)
    3. while 'cat' in pets:
    4. pets.remove('cat')
    5. print(pets)
    使用用户输入来填充字典

    下面的循环每次都提示输入被调查者的名字和回答。然后将数据存储在一个字典中,将被调查者和回答关联起来:

    1. responses = {}
    2. # 设置一个标志,指出调查是否继续
    3. polling_active = True
    4. while polling_active:
    5. # 提示输入被调查者的名字和回答
    6. name = input("\nWhat's your name?")
    7. response = input("Which mountain would you like to climb someday?")
    8. # 将答案存储在字典中
    9. responses[name] = response
    10. # 看看是否还有人要参与调查
    11. repeat = input("Would you like to let another person respond?(yes/no)")
    12. if repeat == 'no':
    13. polling_active = False
    14. #调查结束,显示结果
    15. print("\n--- Poll Results ---")
    16. for name, response in responses.items():
    17. print(name + " would like to climb " + response + ".")

    for循环

    1. for iterating_var in sequence:
    2. statements(s)

  • 相关阅读:
    网络ip地址冲突会出现什么情况
    目标检测网络系列之R-CNN
    BCC源码内容概览(5)
    栈(C语言实现)
    采用connector-c++ 8.0操作数据库
    c++ 类中隐藏的六个(c11之后 八个)默认函数
    第九章 Ambari二次开发之自定义Flink服务 -- 自定义quiklinks链接
    【毕业设计】中文汉字识别算法 - 深度学习 卷积神经网络 机器视觉 OCR
    我的创作纪念日——纪念写博客128天
    2022”杭电杯“中国大学生算法设计超级联赛(2)1 3 11题解
  • 原文地址:https://blog.csdn.net/yaya_jn/article/details/134242851