Home  >  Article  >  Backend Development  >  How to use judgment statements, loop statements, and functions in Python

How to use judgment statements, loop statements, and functions in Python

WBOY
WBOYforward
2023-05-28 18:41:231979browse

    1. Judgment statement

    1.1 Boolean type and comparison operator

    1.1.1 Boolean type

    Boolean expresses logic in real life, that is, true and false:

    • True represents true

    • False means false

    The essence of True and False are both numbers. True is recorded as 1, False as 0.

    Define variables to store Boolean type data: variable name = Boolean type literal

    Boolean types can not only be defined by themselves, but also can obtain Boolean type results through comparison operations.

    result = 10 > 5
    print(f"result的值是{result},类型是{type(result)}")

    Output result:

    The value of result is True and the type is

    1.1.2 Comparison operators

    How to use judgment statements, loop statements, and functions in Python

    ##1.2 if statement

    1.2.1 Basic format of if statement

    Basic format of if statement :

    if Conditions to be judged: #Don’t forget to add a colon

    What to do when the condition is true #There are 4 spaces in front of it for indentation

    [Example] Combined with the input statement learned previously, complete the following case:

    • (1) Obtain keyboard input through the input statement and assign a value to the variable age . (Pay attention to converting to numeric type)

    • (2) Use if to determine whether you are an adult. If the conditions are met, a prompt message will be output,

    is as follows:

    Welcome to the Black Horse Children's Playground, children are free and adults are charged.

    Please enter your age: 30
    You are of age
    A supplementary ticket of 10 yuan is required to play
    I wish you a happy visit.

    print("欢迎来到黑马儿童游乐场,儿童免费,成人收费。")
    age = int(input("请输入你的年龄:"))#类型转换
    
    if age >= 18:
        print("您已成年") #有4格缩进
        print("游玩需要补票10元")
    
    print("祝您游玩愉快")

    Output result 1:

    Welcome to the Black Horse Children's Playground, children are free and adults are charged.

    Please enter your age: 20
    You are an adult
    You need to pay a supplement of 10 yuan to play
    I wish you a happy game

    Output result 2:

    Welcome to the Black Horse Children's Playground. Children are free and adults are charged.

    Please enter your age: 10
    Wish you a happy trip

    1.2.2 if else statement
    print("欢迎来到黑马儿童游乐场,儿童免费,成人收费。")
    age = int(input("请输入你的年龄:"))#类型转换
    
    if age >= 18:
        print("您已成年,游玩需要补票10元。")
    else:#同样有冒号,且其中的语句有4个格缩进
        print("您未成年,可以免费游玩")
    1.2.3 if elif else statement
    print("欢迎来到黑马动物园")
    if int(input("请输入你的身高(cm):")) < 120:
        print("您的身高小于120cm,可以免费游玩")
    elif int(input("请输入vip等级:")) > 3:
        print("您的vip等级大于3,可以免费游玩")
    elif int(input("请告诉我今天几号:")) == 1:
        print("今天是1号免费日,可以免费游玩")
    else:
        print("不好意思,您不满足免费游玩的条件,需购票")
    1.2.4 Nesting of judgment statements

    The basic syntax format is as follows:

    if Condition 1:

    Made when condition 1 is met Things 1
    Things to do when condition 1 is met 2
    if Condition 2:
    Things to be done when condition 2 is met 1
    Things to be done when condition 2 is met 2

    As in the above code, the second if is within the first if. The second if will only be executed when the conditions of the first if are met.

    The key point of nesting is: space indentation.
    Python uses
    space indentation to determine the hierarchical relationship between statements.

    print("欢迎来到黑马动物园")
    if int(input("请输入你的身高(cm):")) > 120:
        print("您的身高大于120cm,不能免费游玩")
        print("不过,若您的vip等级超过3,可以免费游玩")
        if int(input("请输入vip等级:")) > 3:
            print("您的vip等级大于3,可以免费游玩")
        else:
            print("不好意思,您不满足免费游玩的条件,需购票")
    else:
        print("您的身高小于120cm,可以免费游玩")

    2. Loop statement

    2.1 while loop

    2.1.1 while loop basic syntax
    while condition:

    Condition is met When the conditions are met, do things 1
    When the conditions are met, do things 2
    When the conditions are met, do things 3
    ...

    【Example】Set a range 1 A random integer variable of ~100, through a while loop and an input statement, determines whether the input number is equal to a random number.

    Requirements:

    • (1) Unlimited opportunities until you guess correctly;

    • (2) Every time you fail to guess, you will be prompted whether it is too high or too low;

    • (3) After guessing the number, you will be prompted how many times you have guessed.

    • import random
      count = 0
      num = random.randint(1,100)#生成1~100的随机整数,包括1和100
      
      while True:
          guess = int(input("请输入猜测的数字:"))
          count += 1	#python中没有count++这种累加操作
          if guess == num:
              print("猜中了")
              break
          else:
              if guess < num:
                  print("小了")
              else:
                  print("大了")
      
      print("共猜了%d次" % count)
    2.1.2 Use of while loop nesting
    while Condition 1:

    When condition 1 is met, what to do 1
    Condition When condition 1 is met, do things 2
    When condition 1 is met, do things 3
    ...
    while condition 2:
    When condition 2 is met, do things 1
    Condition 2 When condition 2 is met, do 2
    When condition 2 is met, do 3
    ...

    [Example 1] Confess love to Xiaomei for 100 days and give 10 flowers every day Rose flower.

    i = 1
    while i <= 100:
        print(f"第{i}天表白")
    
        j = 1
        while j <= 10:
            print(f"第{i}天,送的第{j}朵玫瑰花")
            j += 1
    
        print("小美,我喜欢你")
        i += 1

    Supplementary knowledge

    print statement By default, the output content will automatically wrap, as shown below:

    How to use judgment statements, loop statements, and functions in Python

    In the case that is about to be completed, you need to use the function of printing statement output without line breaks, just add

    end='':

    How to use judgment statements, loop statements, and functions in Python

    ps:end=''使用了方法传参功能,后面会详细讲解。

    【例2】打印九九乘法表

    i = 1
    while i < 10:
    
        j = 1
        while j <= i:
            print(f"{j} * {i} = {j * i}\t", end = &#39;&#39;)
            j += 1
    
        i += 1
        print()

    2.2 for 循环

    2.2.1 for 循环基础语法

    for 临时变量 in 待处理数据集(序列):
        循环满足条件时执行的代码

    遍历字符串:

    info = "hello"
    for ch in info:
        print(ch)

    输出结果:

    h
    e
    l
    l
    o

    由此看出,与 while 循环不同,for 循环无法定义循环条件,只能从被处理的数据集里,依次取出内容进行处理。
    所以,理论上讲,Python 的 for 循环无法构建无限循环(被处理的数据集不可能无限大)

    【例】统计 “itheima is a brand of itcast” 中有多少个 a。

    name = "itheima is a brand of itcast"
    count = 0
    for ch in name:
        if ch == &#39;a&#39;:
            count += 1
    print(f"共有{count}个a")	# 共有4个a
    2.2.2 range 语句

    for 循环语法中待处理数据集,严格来说,称为序列类型
    序列类型:其内容可以一个个依次取出的一种类型,包括:字符串、列表、元组 等。
    目前只介绍了字符串类型,其余类型后面会详细讲解。

    由于现阶段只介绍了字符串,所以暂且只能通过 range 语句,可以获得一个简单的数字序列(range 语句还有其他用途,后面详讲)。

    range(num):获取一个从 0 开始,到 num 结束的数字序列(不含 num 本身)

    如:range(5) 取得的数据是:[0,1,2,3,4]

    range(num1, num2):获得一个从 num1 开始,到 num2 结束的数字序列(不含 num2 本身)

    如:range(5,10)取得的数据是:[5,6,7,8,9]

    range (num1, num2, step):获得一个从 num1 开始,到 num2 结束的数字序列(不含 num2 本身)
    数字之间的步长,以 step 为准(step 默认为1)

    如:range(5,10,2) 取得的数据是:[5,7,9]

    range 语句通常配合 for 使用:

    for i in range(5):
        print(i)

    输出结果:

    0
    1
    2
    3
    4

    【例】

    有了 range 语句,前面送 10 朵玫瑰花的操作也可以用 for 循环实现:

    count = 0
    for i in range(1, 100):
        if i % 2 == 0:
            count += 1
    
    print(f"共有{count}个偶数")	# 共有49个偶数
    2.2.3 变量作用域

    如代码,思考:最后的 print 语句,能否访问到变量 i?

    for i in range(5):
    	print(i)
    print(i)	# 能否访问到变量i?

    规范上:不允许
    实际上:可以,最后的 print 语句输出 4

    回看 for 循环的语法:

    for 临时变量 in 待处理数据集(序列):
        循环满足条件时执行的代码

    我们会发现,将从数据集(序列)中取出的数据赋值给临时变量
    该临时变量,在编程规范上,作用范围(作用域),限定在 for 循环内部。
    如果在 for 循环外部访问该临时变量,实际上可以访问到;但在编程规范上,不允许、不建议这么做。

    上面代码中,若想要在 for 循环外面使用 i,可以将 i 定义在 for 循环外面:

    i = 0
    for i in range(5):
        print(i)
    print(i)
    2.2.4 for 循环嵌套使用

    for 临时变量 in 待处理数据集(序列):
        循环满足条件应做的事情1
        循环满足条件应做的事情2
        循环满足条件应做的事情N
        for 临时变量 in 待处理数据集(序列):
            循环满足条件应做的事情1
            循环满足条件应做的事情2
            循环满足条件应做的事情N

    【例】用 for 循环实现送小美 100 天玫瑰花,每天送 10 朵的功能。

    for i in range(1, 101):
        print(f"今天是向小美表白的第{i}天")
    
        for j in range(1, 11):
            print(f"送小美第{j}朵玫瑰花")
    
        print("小美,我喜欢你")

    目前学习了 2 个循环,while 循环和 for 循环。这两种循环可以相互嵌套

    【例】用 for 循环打印九九乘法表。

    for i in range(1, 10):
        for j in range(1, 10):
            if j <= i:
                print(f"{j} * {i} = {j * i}\t", end = &#39;&#39;)
        print()

    2.3 break 和 continue

    • break:所在的循环完全结束。

    • continue:中断本次循环,直接进入下一次循环。

    注意点:

    • (1)两者都可以用于 for 循环和 while 循环。

    • (2)在嵌套循环中,两者都只能作用于所在的循环,无法对上层循环起作用。

    【例】某公司,账户余额有 1 W元,给 20 名员工发工资。规则:

    • (1)员工编号从 1 到 20,从编号1开始,依次领取工资,每人可领取 1000 元

    • (2)领工资时,财务判断员工的绩效分(1~10)(随机生成),如果低于 5,不发工资,换下一位。

    • (3)如果工资发完了,结束发工资。

    输出格式如图:

    How to use judgment statements, loop statements, and functions in Python

    import random
    money = 10000
    for i in range(1, 21):
        if money < 1000:
            print("工资发完了,下个月领取吧")
            break
        score = random.randint(1, 10) #生成1~10的随机整数,包括1和10
        if score < 5:
            print(f"员工{i},绩效分{score},低于5,不发工资,下一位")
        else:
            money -= 1000;
            print(f"向员工{i}发放工资1000元,账户余额还剩余{money}元")

    输出结果:

    向员工1发放工资1000元,账户余额还剩余9000元
    向员工2发放工资1000元,账户余额还剩余8000元
    向员工3发放工资1000元,账户余额还剩余7000元
    向员工4发放工资1000元,账户余额还剩余6000元
    向员工5发放工资1000元,账户余额还剩余5000元
    员工6,绩效分3,低于5,不发工资,下一位
    向员工7发放工资1000元,账户余额还剩余4000元
    向员工8发放工资1000元,账户余额还剩余3000元
    向员工9发放工资1000元,账户余额还剩余2000元
    员工10,绩效分3,低于5,不发工资,下一位
    向员工11发放工资1000元,账户余额还剩余1000元
    员工12,绩效分1,低于5,不发工资,下一位
    向员工13发放工资1000元,账户余额还剩余0元
    工资发完了,下个月领取吧

    3. 函数

    3.1 函数的定义

    函数的定义:

    def 函数名(传入参数):
        函数体
        return 返回值

    函数的调用:

    函数名(参数)

    # 函数定义
    def say_hello():
        print("hello world")
    # 函数调用
    say_hello()	#输出 hello world

    注意事项:

    • (1)参数如果不需要,可以省略(后续章节讲解)。

    • (2)返回值如果不需要,可以省略(后续章节讲解)。

    • (3)函数必须先定义后使用

    3.2 函数的参数

    # 函数定义
    def add(x, y):
        print(f"{x} + {y} = {x + y}")
    # 函数调用
    add(3, 4)

    函数定义中的参数,称之为形式参数;
    函数调用中的参数,称之为实际参数;
    函数的参数数量不限,使用逗号分隔开;
    传入参数的时候,要和形式参数一一对应(顺序、个数),逗号隔开。

    3.3 函数的返回值

    带返回值的函数的定义和调用:

    # 函数定义
    def add(x, y):
        return x + y
    # 函数调用
    res = add(3, 4)
    print(res)	#输出7

    question:如果函数没有使用 return 语句返回数据,那么函数有返回值吗?
    answer:有返回值。
    why:Python 中有一个特殊的字面量:None,其类型是:
    无返回值的函数,实际上就是返回了:None 这个字面量,
    函数返回 None,就表示没有返回什么有意义的内容,也就是返回了空的意思。

    def say_he11o():
        print("Hello...")
    
    result = say_he11o()
    print(result)
    print(type(result))

    输出结果:

    Hello...
    None

    None可以主动使用 return 返回,效果等同于不写 return 语句:

    def say_he11o():
        print("Hello...")
        return None
    
    result = say_he11o()
    print(result)
    print(type(result))

    输出结果:

    Hello...
    None

    None 作为一个特殊的字面量,用于表示:空、无意义,其有非常多的应用场景。

    • 用于函数无返回值。

    • 用于 if 判断。在 if 判断中,None 等同于 False。在函数中可以主动返回 None,配合 if 判断做相关处理。

    def check_age(age):
        if age >= 18:
            return "success"
        else:
            return None
    
    result = check_age(16)
    if not result:
        print("未满18岁,不能进网吧")

    用于声明无内容的变量。定义变量,但暂时不需要变量有具体值,可以用None来代替

    #暂不赋予变量具体值
    name = None

    3.4 函数说明文档

    虽然函数的说明文档只是注释,随便写也没啥,但最好要遵循一定的规范。
    在函数内写引号一回车,就自动出现参数和返回值的说明头部(这就是规范)。这样就可以在此基础上继续补充。

    How to use judgment statements, loop statements, and functions in Python

    写好函数说明文档后,将鼠标悬停在函数的上方,会出现函数的说明信息。

    How to use judgment statements, loop statements, and functions in Python

    3.5 函数的嵌套调用

    函数的嵌套调用:在一个函数中,调用另外一个函数。

    def func_b():
        print("---2---")
    
    def func_a():
        print("---1---")
        func_b()
        print("---3---")
    
    func_a()  # 调用函数func_a

    输出结果:

    ---1---
    ---2---
    ---3---

    3.6 变量的作用域

    变量主要分为两类:局部变量和全局变量。
    局部变量:定义在函数体内部,只在函数内部生效。

    def testA():
        num = 100
        print(num)
    testA() # 100
    print(num)#报错:name&#39;num&#39;is not defined

    变量 a 定义在 testA 函数内部,在函数外部访问则立即报错。
    局部变量的作用:在函数体内部,临时保存数据,当函数调用完成后销毁。

    全局变量:在函数内、外都能生效的变量。
    如果有一个数据,在函数 A 和函数 B 中都要使用,则可以将这个数据存储在一个全局变量中。

    #定义全局变量num
    num = 100
    def testA():
        print(num)
    def testB():
        print(num)
        
    testA() #100
    testB() #100

    global 关键字

    现在有个需求:在函数内部修改函数外的全局变量。

    num = 200
    def test_a():
        print(f"test_a: {num}")
    
    def test_b():
        num = 500
        print(f"test_b:{num}")
        
    test_a()
    test_b()
    print(num)

    上述代码输出结果:

    test_a: 200
    test_b:500
    200

    代码并没有修改全局变量的值。原因是 test_b() 中的 num 是一个局部变量,与全局变量 num 没有丝毫关系。
    想要在函数内修改全局变量,可以使用 global 关键字。

    num = 200
    def test_a():
        print(f"test_a: {num}")
    
    def test_b():
        global num #增加了global
        num = 500
        print(f"test_b:{num}")
    
    test_a()
    test_b()
    print(num)

    输出结果:

    test_a: 200
    test_b:500
    500

    上面代码中,global 关键字将 num 声明为全局变量,这样 test_b() 中的 num 与函数外的 num 就是同一个变量。

    3.7 函数综合案例

    银行系统查询余额、存款、取款、退出功能。
    初始余额 5000000 元,进入系统时先输入姓名。

    money = 5000000
    name = input("请输入姓名:") 
    # 菜单
    def menu(): 
        print(f"{name},您好,欢迎来到黑马银行ATM,请选择操作:")
        print("查询余额\t【输入1】")
        print("存款\t\t【输入2】")
        print("取款\t\t【输入3]")
        print("退出\t\t【输入4】")
        return input("请输入您的选择:")
    # 查询余额
    def query(show_header): 
        # 控制是否输出表头
        if show_header:
            print("-------------查询余额--------------")
        print(f"{name},您好,您的余额剩余:{money}元")
    # 取款
    def save(deposit): 
        print("-------------存款--------------")
        global money
        money += deposit
        print(f"{name},您好,您存款{deposit}元成功")
        query(False)
    # 存款
    def get(withdraw): 
        print("-------------取款--------------")
        global money
        money -= withdraw
        print(f"{name},您好,您取款{withdraw}元成功")
        query(False)
     
    while True:
        choice = menu() # 用户选择
        if choice == "1":
            query(True)
        elif choice == "2":
            save(int(input("请输入要存入的金额:")))
        elif choice == "3":
            get(int(input("请输入要去除的金额:")))
        else:
            break
    print("程序退出...")

    The above is the detailed content of How to use judgment statements, loop statements, and functions in Python. For more information, please follow other related articles on the PHP Chinese website!

    Statement:
    This article is reproduced at:yisu.com. If there is any infringement, please contact admin@php.cn delete