Public account: You and the cabin by: Peter Editor: Peter

Hello, I’m Peter

You hear it all the time in your life:

  • If I work harder in class, I’m sure I can pass English
  • If I work hard, I’m sure I can get down to 100 jin
  • If I had good skills, I would have entered a big factory… .

That’s what conditional statements are all about: what happens if you assume a certain condition is true.

Rock paper scissors

Introduce the if conditional statement with a game of rock-paper-scissors:

import random  # Random module

player = int(input("Please enter (0- scissors 1- Rock 2- paper)"))  # Player input
computer = random.randint(0.2)   A random number is generated between 0 and 2 as input to the computer

if (player == 0 and computer == 2) or (player == 1 and computer == 0) or (player == 2 and computer == 1) :print("Congratulations player, you won.")  # parentheses
elif (player == 0 and computer == 0) or (player == 1 and computer == 1) or (player == 2 and computer == 2) :print("Draw")
else:
    print("Unfortunately, you lost.")
Copy the code

Because the computer’s input is random, it can produce different results.

Python conditional control statements

Conditional control statements in Python determine the code logic to be executed based on the execution result (True or False) of one or more statements.

  • Key words: it containsifelifelseThe keyword does not exist in Pythonelse ifElif is the only one that exists.
  • The colon is important: use a colon – for each statement:End, useThe indentationDivide statement blocks. Statements with the same indentation number form a statement block.
  • 3 conditional control statements: if, if-else, if-elif (multiple elif) -else

If statement

If statement, which has only one judgment condition. If the condition is True, the indented code logic after the judgment statement is executed, otherwise it is not executed.

1. Syntax format:

if expression:
    statements...
Copy the code

Take a look at the specific execution flow chart:

Let’s take a concrete example: we define a variable a that satisfies the condition of the if statement, so we print congratulations

If-else statement

if expression
    statements...
else:
    statements...
Copy the code

If-else statements, which have only one judgment condition, differ from if statements in that:

  • If the condition following if is True, the indented code logic after the if statement is executed,

  • Otherwise, the code logic with an else indentation is executed.

Take a look at the specific execution flow chart:

Look at a specific example:

  • Define variable a=2 that does not satisfy an if condition
  • Execute the code block followed by the else indentation

If-elif-else statement

if expression:
    statements...
elif expression:
    statements...
     There can be one or more elIF statements
else:
    statement...
Copy the code

When using a judgment statement, we sometimes need to judge two or more conditions and execute the corresponding code logic, when the above two statements do not meet our needs. Note that if only one condition is true in the if-elif-else statement, the entire statement will exit. In short, only one of the three judgment paths will be taken.

Note the following for this statement:

  • There are multiple conditional statements that execute statements following if if is true
  • Elif If one of them is true, the elif is executed, and the subsequent code block is not executed
  • If neither if nor elif is satisfied, the else statement is executed

Take a look at the specific execution flow chart:

Specific cases are as follows:

The if… else… Statements nested

Multiple if statements are used simultaneously. This is illustrated by an example of whether the guest is drinking An American-style coffee with sugar:

1, meet both American and “yes” (sugar) conditions

2, Meet the American, but no sugar “no”

If you don’t want to add sugar (no), go into the first else

3. Not being “American” from the start

Ternary operator

If conditional statements can be used with ternary operators. If… else… The conditional statement is written to a line of code:

X = A if B else C
Copy the code
  • If the B condition is true, the output X=A
  • If B is false, then the output X=C

If x>y, assign x to a, otherwise (x<y) assign y to a.

Now x is less than y, so y is assigned to A, so a ends up being 17

Python list comprehensions use if statements

To find the number up to 50 divisible by 5, do this in two ways:

  • List derivation
  • The for loop

Logical operators in Python

The operator instructions
not Logical “not”
and Logical and
or Logical “or”

Python manipulates operators

The basic operators commonly used in Python can be found in the following table:

The operator instructions
< Less than
< = Less than or equal to
> Is greater than
> = Greater than or equal to
= = Is equal to the
! = Is not equal to
in / not in Member operator
is / not is Identity operator

Here are a few examples of basic operators:

Special objects in Python

Boolean values (bool) in Python are True and Fool. If the condition is True in the if judgment, the code block indented after the if is executed. Some special objects have a Boolean value for fool:

object Boolean value
None False
All numbers with zero value (integer/complex/floating point) False
An empty string False
An empty list False
An empty tuple False
An empty dictionary False
Empty collection False

The following examples show that a print statement is executed when the Boolean value is False, then True after adding not

By negating, we can simplify our code:

Take a plane

There are two main steps to getting on an airplane:

  • Buy the ticket
  • Through the security check
def fly() :
    ticket = int(input("Purchased air ticket (0- not purchased 1- Purchased)"))
    safety = int(input("Are you through security (0- not through 1- through)"))
    
    if ticket == 1 and safety == 1:
        print("Boarding please")
    elif ticket == 1 andsafety ! =1:
        print("No boarding without security clearance.")
    else:
        print("You can't board without a ticket.")
        
if __name__ == "__main__":
    fly()
Copy the code

conclusion

  1. When using if conditional control statements, you can flexibly use basic operators and logical operators according to actual requirements.
  2. Normal if conditional statements are nested as multiple if statements
  3. Note the colon after the conditional control statement:And then there’s the indentation problem in Python.
  4. If-else statements can be understood as one of two choices, if-elif-else statements are one of three choices, if there are more than one elif statements are one of N choices, where else is not mandatory.
  5. When using logical operators, their precedence needs to be taken care of, with parentheses(a)The statement has the highest priority,() > not > and > or . When we do not know the priority of the statement execution, the best solution isI’m going to put a little bracket here