python notes: #009#judgment statement

Judgment (if) statement

Target

  • Application scenarios under development
  • if statement experience
  • Advanced if statement
  • Comprehensive application

01. Application scenarios under development

Judgment in life is almost omnipresent, and we make all kinds of choices every day, if so? if that? ...

Minors are not allowed to enter

judgment in the program

Judgment diagram

if 今天发工资:

    先还信用卡的钱

    if 有剩余:

        又可以happy了,O(∩_∩)O哈哈~

    else:

        噢,no。。。还的等30else:

    盼着发工资

Definition of Judgment

  • If the conditions are met , something can be done,
  • If the condition is not met , do another thing, or do nothing

It is precisely because of judgment that the programming world is colorful and full of changes!

Judgment statement Also known as "branch statement", it is precisely because of judgment that the program has many branches

02. If statement experience

2.1 Basic syntax of if judgment statement

PythonIn , the if statement is used to judge, the format is as follows:

if 要判断的条件:
    条件成立时,要做的事情
    ……

Note: Code is indented by one tabkey , or 4 spaces - spaces are recommended

  • In Python development, don't mix tabs and spaces!

We can think of the entire if statement as a complete block of code

if statement is a complete block of code

2.2 Judgment sentence drill - judging age

need

  1. Define an integer variable to record age
  2. Determine if you are over 18 ( >= )
  3. If you are 18 years old, you are allowed to enter the Internet Cafe Hipi
# 1. 定义年龄变量
age = 18

# 2. 判断是否满 18 岁
# if 语句以及缩进部分的代码是一个完整的代码块
if age >= 18:
    print("可以进网吧嗨皮……")

# 3. 思考!- 无论条件是否满足都会执行
print("这句代码什么时候执行?")

Note :

  • ifStatements and indented parts are a complete block of code

2.3 else handles the case where the condition is not met

think

When using ifjudgment , you can only do what you want to do when the conditions are met. So if you need to do something when the conditions are not met, what should you do?

Answer

else, the format is as follows:

if 要判断的条件:
    条件成立时,要做的事情
    ……
else:
    条件不成立时,要做的事情
    ……

Note :

  • iftogether with the elsestatements and their respective indented parts is a complete code block

2.4 Judgment sentence drill - Judgment age improvement

need

  1. Enter user age
  2. Determine if you are over 18 ( >= )
  3. If you are 18 years old, you are allowed to enter the Internet Cafe Hipi
  4. If under 18, prompt to go home and do homework
# 1. 输入用户年龄
age = int(input("今年多大了?"))

# 2. 判断是否满 18 岁
# if 语句以及缩进部分的代码是一个完整的语法块
if age >= 18:
    print("可以进网吧嗨皮……")
else:
    print("你还没长大,应该回家写作业!")

# 3. 思考!- 无论条件是否满足都会执行
print("这句代码什么时候执行?")

ifelse statement is a complete block of code

03. Logical operations

  • In program development, when judging conditions , it is usually necessary to judge multiple conditions at the same time.
  • Subsequent code can be executed only if multiple conditions are met. At this time, logical .
  • Logical operators can logically connect multiple conditions into more complex conditions
  • Logical operators in Python include: and and / or or / not three

3.1and

条件1 and 条件2
  • with / and
  • Both conditions are met, returnTrue
  • Return as long as one is not satisfiedFalse
Condition 1 Condition 2 result
established established established
established invalid invalid
invalid established invalid
invalid invalid invalid

3.2or

条件1 or 条件2
  • or / or
  • As long as one of the two conditions is satisfied, returnTrue
  • Both conditions are not met, returnFalse
Condition 1 Condition 2 result
established established established
established invalid established
invalid established established
invalid invalid invalid

3.3not

not 条件
  • not / not
condition result
established invalid
invalid established

Logical Operation Walkthrough

  1. Exercise 1: Define an integer variable ageand write code to determine if the age is correct
    • The age of the person is required to be between 0-120
  2. Exercise 2: Define two integer variables python_score, c_score, and write code to judge grades
    • Requires only one subject score > 60 points to pass
  3. Exercise 3: Define a boolean variable is_employeeand write code to determine whether it is an employee of the company
    • If it is not prompted not to enter

Answer 1:

# 练习1: 定义一个整数变量 age,编写代码判断年龄是否正确
age = 100

# 要求人的年龄在 0-120 之间
if age >= 0 and age <= 120:
    print("年龄正确")
else:
    print("年龄不正确")

Answer 2:

# 练习2: 定义两个整数变量 python_score、c_score,编写代码判断成绩
python_score = 50
c_score = 50

# 要求只要有一门成绩 > 60 分就算合格
if python_score > 60 or c_score > 60:
    print("考试通过")
else:
    print("再接再厉!")

Answer 3:

# 练习3: 定义一个布尔型变量 `is_employee`,编写代码判断是否是本公司员工
is_employee = True

# 如果不是提示不允许入内
if not is_employee:
    print("非公勿内")

04. Advanced if statement

4.1elif

  • In development, use ifcan determine the condition
  • Use elseto handle situations where conditions are not met
  • However, if you want to add some more conditions , when the conditions are different, the code to be executed is also different , you can useelif
  • The syntax format is as follows:
if 条件1:
    条件1满足执行的代码
    ……
elif 条件2:
    条件2满足时,执行的代码
    ……
elif 条件3:
    条件3满足时,执行的代码
    ……
else:
    以上条件都不满足时,执行的代码
    ……
  • Compare code for logical operators
if 条件1 and 条件2:
    条件1满足 并且 条件2满足 执行的代码
    ……

Notice

  1. elifelseand must be ifused in conjunction with , not alone
  2. if, elifand elseand their respective indented code can be regarded as a complete code block

elif walkthrough - girlfriend's holiday

need

  1. Define a holiday_namestring variable to record the festival name
  2. If it 's Valentine's Day, you should buy roses / watch a movie
  3. If it's Christmas Eve you should buy apples / eat dinner
  4. If it's a birthday you should buy a cake
  5. Every other day is a festival...
holiday_name = "平安夜"

if holiday_name == "情人节":
    print("买玫瑰")
    print("看电影")
elif holiday_name == "平安夜":
    print("买苹果")
    print("吃大餐")
elif holiday_name == "生日":
    print("买蛋糕")
else:
    print("每天都是节日啊……")

4.2 ifNesting

The application scenario of elif is: to judge multiple conditions at the same time, all conditions are equal

  • In development, use iffor conditional judgment. If you want to add conditional judgment to the execution statement where the condition is established , you can use the nesting of if
  • The application scenario of the nesting of if is: on the premise that the previous conditions are satisfied, add additional judgments
  • The syntax format of the nested if , except for indentation, is no different from the previous one
  • The syntax format is as follows:
if 条件 1:
    条件 1 满足执行的代码
    ……
    
    if 条件 1 基础上的条件 2:
        条件 2 满足时,执行的代码
        ……    
        
    # 条件 2 不满足的处理
    else:
        条件 2 不满足时,执行的代码
        
# 条件 1 不满足的处理
else:
    条件1 不满足时,执行的代码
    ……

Nested walkthrough of if - train station security

need

  1. Define a boolean variable has_ticketto indicate whether there is a ticket
  2. Define an integer variable knife_lengthto represent the length of the knife, unit: cm
  3. Check first to see if there is a ticket, and if so, allow security check
  4. During security inspection, you need to check the length of the knife to determine whether it exceeds 20 cm
    • If it exceeds 20 cm, the length of the knife will be prompted, and it is not allowed to get on the car
    • If not more than 20 cm, pass the security check
  5. If you do not have a ticket, you are not allowed to enter the door
# 定义布尔型变量 has_ticket 表示是否有车票
has_ticket = True

# 定义整数型变量 knife_length 表示刀的长度,单位:厘米
knife_length = 20

# 首先检查是否有车票,如果有,才允许进行 安检
if has_ticket:
    print("有车票,可以开始安检...")

    # 安检时,需要检查刀的长度,判断是否超过 20 厘米
    # 如果超过 20 厘米,提示刀的长度,不允许上车
    if knife_length >= 20:
        print("不允许携带 %d 厘米长的刀上车" % knife_length)
    # 如果不超过 20 厘米,安检通过
    else:
        print("安检通过,祝您旅途愉快……")

# 如果没有车票,不允许进门
else:
    print("大哥,您要先买票啊")

05. Comprehensive application - rock paper scissors

Target

  1. Enhances logical operations for multiple conditions
  2. Experience the use of importimport modules ("toolkits")

need

  1. Enter the punch to be delivered from the console - rock (1) / scissors (2) / cloth (3)
  2. Computer Random Punch - First assume that the computer can only throw stones to complete the overall code function
  3. Compare wins and losses
serial number rule
1 rock is better than scissors
2 Scissors beat cloth
3 Busheng Stone

5.1 Basic code implementation

  • First assume that the computer will only produce stones and complete the overall code function
# 从控制台输入要出的拳 —— 石头(1)/剪刀(2)/布(3)
player = int(input("请出拳 石头(1)/剪刀(2)/布(3):"))

# 电脑 随机 出拳 - 假定电脑永远出石头
computer = 1

# 比较胜负
# 如果条件判断的内容太长,可以在最外侧的条件增加一对大括号
# 再在每一个条件之间,使用回车,PyCharm 可以自动增加 8 个空格
if ((player == 1 and computer == 2) or
        (player == 2 and computer == 3) or
        (player == 3 and computer == 1)):

    print("噢耶!!!电脑弱爆了!!!")
elif player == computer:
    print("心有灵犀,再来一盘!")
else:
    print("不行,我要和你决战到天亮!")

5.2 Processing of random numbers

  • PythonIn , to use random numbers, you first need to import the random number module -- the "toolkit"
import random
  • After importing the module, you can directly type a name after the module name .and then press the Tabkey, it will prompt all functions contained in the module

  • random.randint(a, b), which returns an integer [a, b]between , inclusive aandb
  • E.g:

random.randint(12, 20)  # 生成的随机数n: 12 <= n <= 20   
random.randint(20, 20)  # 结果永远是 20   
random.randint(20, 10)  # 该语句是错误的,下限必须小于上限

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324579859&siteId=291194637