[Python 1-10] Python hands-on tutorial — an article on if statements and the special usage of if statements

Time:2021-9-17

By Vlad
Source Vlad (official account: fulade_me)

If simple example

Suppose you have a list of cars and want to print out the name of each car. For most cars, the name should be printed in capital letters, but for car name ‘BMW’, it should be printed in full capital letters.
The following code traverses a list and prints the car name in uppercase, but for the car name ‘BMW’, it prints in full uppercase:

car_list = ['bmw','audi','toyota','honda']
for car in car_list:
    if car == 'bmw':
        print(car.upper())
    else: 
        print(car.title())

In this example, ifcarYour name equalsbmwWill callupper()Method to output the result in uppercase, if not equal tobmwIt is output in uppercase.
The output results are as follows:

BMW
Audi
Toyota
Honda

Conditional statement

The core of each if statement is a value ofTrueorFalseThe expression is calledConditional statement。 The value judged by Python according to the condition isTruestillFalseTo determine whether to execute the code in the if statement. If the value of condition judgment isTrue, python executes the code immediately following the if statement; If yesFalse, python will not execute this code.

Check for equality

Most conditional judgments compare the current value of a variable with a specific value. The simplest condition is to check whether the value of a variable is equal to a value:

car = 'bmw'
print(car == 'bmw')
True

We first use an equal sign to set the value of car tobmw。 Next, use two equal signs==inspectcarIs the value ofbmw。 This equality operator returns when the values on both sides of it are equalTrue, otherwise returnFalse。 In this example, the values on both sides are equal, so it returnsTrue
If variablecarThe value of is notbmw, the above judgment will returnFalse:

car = 'audi'
print(car == 'bmw')
False

A first equal sign sets the value of the variable car toaudi。 The two equal signs ask “what is the value of the variable car?”bmwAre you? “. most programming languages use the equal sign in the same way as the example here.

If is used regardless of case

In Python, checking for equality is case sensitive. For example, two values with different case will be treated as unequal:

car = 'Audi' 
print(car == 'audi')
False

If case is important, this behavior has its advantages. However, if the case does not matter and you only want to check the value of the variable, you can convert the value of the variable to lowercase and compare it:

car = 'Audi'
print(car.lower() == 'audi')
True

Regardless of valueAudiThe above judgment will be returned regardless of the case ofTrue, because the judgment is case insensitive. functionlower()Variables stored in are not modifiedcarTherefore, such a comparison will not affect the original variable:

car = 'Audi'
print(car.lower() == 'audi')
True 
print(car)
'Audi'

Check for inequality

To determine whether the two values are unequal, you can use an exclamation mark and an equal sign in combination!=, where the exclamation mark indicatesno, this is true in many programming languages.
Here is another if statement to demonstrate how to use the inequality operator. We willApple(Apple) is stored in a variable, and what the customer wants to buy isa mandarin orange(Orange), not required by customersApple:

fruit = 'Apple'
if (fruit != 'Orange'):
    print('do not need ' + fruit)

takefruitValues andOrangeIf they are not equal, python returnsTrueAnd then execute the code immediately after the if statement; If the two values are equal, python returnsFalseTherefore, the code immediately following the if statement is not executed.
becausefruitThe value of is notOrangeTherefore, it was implementedprintsentence.
Most conditional expressions we write check whether two values are equal, but sometimes it is more efficient to check whether two values are equal.

Compare numbers

Checking the value is very simple. For example, the following code checks whether a person is 18:

age = 18
print(age == 18)
True

You can also check whether the two numbers are not equal. For example, the following code prints a message when the answer provided is incorrect:

answer = 17
if answer != 42:
    print("That is not the correct answer. Please try again!")

Conditional statements can contain various mathematical comparisons, such asless thanLess than or equal togreater thanGreater than or equal to:

age = 19
print(age < 21) 
True
print(age <= 21) 
True
print(age > 21)
False
print(age >= 21) 
False

Various mathematical comparisons can be used in if statements, which is also very simple to use.

Check multiple conditions

You may want to check multiple conditions at the same time. For example, we need to check when both conditions are trueTrueThe corresponding operation is executed only when a condition is true, and sometimes you only need to execute the corresponding operation when a condition is true. In these cases, the keywordandandorIt can help us save a lot of things.
1. Use and to check multiple conditions
To check whether both conditions areTrue, you can use keywordsandCombine the two conditional judgments into one; If each judgment passes, the whole expression isTrue; If at least one judgment fails, the whole expression isFalse。 For example, to check whether both people are not less than 21 years old, the following judgment can be used:

age_0 = 22 
age_1 = 18
print(age_0 >= 21 and age_1 >= 21)
False
age_1 = 22
print(age_0 >= 21 and age_1 >= 21)
True

We defined two variables for storing ageage_0andage_1。 First, we check whether the two variables are greater than or equal to 21. The judgment on the left passes, but the judgment on the right fails. Therefore, the result of the whole conditional expression isFalse
Next we willage_1Change to 22, soage_1The value of is greater than 21, so both judgments pass, resulting in the result of the whole conditional expression isTrue
To improve readability, each judgment can be placed in a pair of parentheses, but this is not necessary. If you use parentheses, the judgment will be similar to the following:

(age_0 >= 21) and (age_1 >= 21)

2. Use or to check multiple conditions
keywordorIt also allows you to check multiple conditions, but as long as at least one condition is met, you can pass the whole judgment. Use only if both judgments failorThe expression for isFalse
Next, check the age of two people again, but the condition is that at least one person is not less than 21 years old:

age_0 = 22 
age_1 = 18
print(age_0 >= 21 or age_1 >= 21)
True
age_0 = 18
print(age_0 >= 21 or age_1 >= 21)
False

Similarly, we first define two variables for storing age. yesage_0The judgment passed, so the result of the whole expression isTrue。 Next, we willage_0Change to 18. In the next judgment, neither judgment passes, so the result of the whole expression isFalse

Check whether a specific value is included in the list

Sometimes, you must check whether the list contains specific values before performing an operation. To determine whether a particular value is included in the list, use the keywordin。 You may write code for the fruit store, first create a list containing the fruit the user wants to buy, and then check whether a specific fruit is included in the list:

fruits = ['apple','banana','cherry']
print('apple' in fruits)
True
print('orange' in fruits)
False

keywordinCan help us checkfruitsIncludeappleandorange。 This kind of judgment is very useful. It can help us easily check whether it contains specific values after creating a list.

Check whether a specific value is not included in the list

There are also times when it is important to determine that a particular value is not included in the list. In this case, you can use keywordsnot in。 For example, if there is a list that contains users who are forbidden to comment on the forum, you can check whether they are forbidden before allowing users to submit comments:

banned_users = ['andrew', 'carolina', 'david'] 
user = 'marie'
if user not in banned_users:
    print(user.title() + ", you can post a response if you wish.")

IfuserThe value of is not included in the listbanned_usersIn,PythonWill returnTrueTo execute indented lines of code.
usermarieNot included in listbanned_usersSo she will see a message inviting her to comment:
Marie, you can post a response if you wish.

Boolean expression

As with conditional expressions, the result of a Boolean expression is eitherTrue, orFalse
Boolean values are often used to record conditions, such as whether the game is running or whether users can edit specific content of the website:

game_active = True 
can_edit = False

Boolean judgment is an efficient judgment method.

If statement

Once you understand the conditional statements, you can start writing if statements. Several examples of if statements were listed in the previous discussion of conditional statements, and this topic is discussed in more depth below.

If else statement

It is often necessary to perform one operation when the conditional statement passes and another operation when it fails. In this case, you can use theif-elsesentence.if-elseThe statement block is similar to a simple if statement, but the else statement allows you to specify the operation to be performed when the conditions are not met.
The following code displays the same message as before when a person is old enough to vote, and also displays a message when the person is old enough to vote:

age = 17
if age >= 18:
    print("You are old enough to vote!")  
    print("Have you registered to vote yet?")
else:
    print("Sorry, you are too young to vote.")
    print("Please register to vote as soon as you turn 18!")

When the conditional statement passes, the first indented print statement block is executed. If the judgment result isFalse, execute the following stepselseCode block. this timeageless than18, condition judgment failed, so executeelseCode in a code block.
The above code works because there are only two situations: either old enough to vote or not.if-elseThe structure is very suitable forPythonA situation in which one of two operations is performed. In this simpleif-elseStructure, one of two operations is always performed.

If elif else structure

It is often necessary to check more than two situations, for which you can use the provided by pythonif-elif-elseStructure. Python only executesif-elif-elseA code block in the structure that checks each conditional judgment in turn until a passed conditional judgment is encountered. When the judgment passes, python executes the code immediately following it and skips the rest of the judgment.
In the real world, there are more than two situations to consider in many cases. For example, take a look at an amusement park that charges according to age:

  1. Free of charge under the age of 4;
  2. 5 yuan for 4-18 years old;
  3. Charge 10 yuan for 18 years old (including Z above).

If only one if statement is used, how to determine the ticket price? The following code determines a person’s age group and prints a message containing the ticket price:

age = 12
if age < 4:
    print("Your admission cost is ¥0.")
elif age < 18:
    print("Your admission cost is ¥5.")
else:
    print("Your admission cost is ¥10.")

First, if judge whether a person is under the age of 4. If so, print an appropriate message and skip the rest of the judgment.elifThe line of code is actually another if judgment that runs only if the previous judgment fails. Here, we know that this person is not less than 4 years old, because the first judgment failed. If the person is under the age of 18, python will print the corresponding message and skipelseCode block. If both the if and elif judgments fail, python runs the last oneelseCode in a code block.
In this example, the firstifThe result of is false, so its code block is not executed. However, the result of the second judgment isTrue(12 is less than 18), so its code block will be executed. The output is a sentence indicating the ticket price to the user:

Your admission cost is ¥5.

As long as you are over 17 years old, you can’t pass the first two judgments. In this case, theelseCode block, indicating that the ticket price is 10 yuan. To make the code more concise, you can notif-elif-elsePrint the ticket price in the code block, only set the ticket price, and add a simple print statement after it:

age = 12
if age < 4:
    price = 0
elif age < 18:
    price = 5
else:
    price = 10
print("Your admission cost is ¥" + str(price) + ".")

Use multiple elif code blocks

Any number of can be used as neededelifCode block, for example, if the above amusement park wants to give discounts to the elderly, a condition judgment can be added to judge whether customers meet the discount conditions. It is assumed that for the elderly over 65 years old, tickets can be purchased at half price (i.e. 5 yuan):

age = 12
if age < 4:
    price = 0
elif age < 18:
    price = 5
elif age < 65:
    price = 10
else:
    price = 5
print("Your admission cost is ¥" + str(price) + ".")

Most of these codes remain unchanged. the secondelifAfter the code block checks and determines that the age is less than 65, the ticket price is set to the full ticket price – 10 yuan.

Omit else code block

Python does not requireif-elifStructure must be followed by else code block. In some cases,elseCode blocks are useful, and in other cases, use oneelifStatement to handle a specific situation is clearer:

age = 12
if age < 4: 
    price = 0
elif age < 18: 
    price = 5
elif age < 65: 
    price = 10
elif age >= 65: 
    price = 5
print("Your admission cost is ¥" + str(price) + ".")

ThirdelifWhen the customer’s age exceeds 65 (inclusive), the code block sets the price to 5 yuan, which is better than usingelseCode blocks are clearer. After such modification, each code block will be executed only after passing the corresponding judgment.

elseIs an all inclusive statement, as long as it does not meet any requirementsiforelifThe code will execute according to the condition judgment in, which may introduce invalid or even malicious data. If the final conditions are known, consider using oneelifCode block insteadelseCode block. In this way, you can be sure that your code will execute only when the corresponding conditions are met.

Judge multiple conditions

if-elif-elseThe structure is powerful, but it is only suitable for the case where only one condition is met. After passing the judgment, python skips the remaining judgment. This behavior is very good and efficient.
However, sometimes you have to check all the conditions you care about. In this case, a series that does not containelifandelseA simple if statement of a code block. There may be multiple conditions forTrue, and you need to beTrueWhen corresponding measures are taken, this method is suitable for use.
Let’s take a look at the previous fruit store example. If customers want two kinds of fruit, they need to ensure that they are included on the shelf:

requested_fruits = ['pear','banana']
if 'apple' in requested_fruits: 
    print("Adding apple.")
if 'pear' in requested_fruits: 
    print("Adding pear.")
if 'banana' in requested_fruits: 
    print("Adding banana.")
print("\nFinished adding your fruits!")

We first created a list of the fruits that the customer wanted. The first if statement checks whether the customer wants itapple, if so, print a confirmation message. Second, check the fruitpearThe code is also a simple if statement, noteliforelseStatement, so this judgment will be made whether the previous judgment passes or not. The third if code checks whether the customer wants itbanana; The code is executed regardless of the results of the first two judgments. These three independent judgments are made whenever the program runs. three
In this example, each condition is checked, so it will be added to the listpearandbananaOutput results:

Adding pear.
Adding banana.

Finished adding your fruits!

If you switch to the followingif-elif-elseStructure, the code will not run correctly because there is a judgment passed:

requested_fruits = ['pear','banana']
if 'apple' in requested_fruits: 
    print("Adding apple.")
elif 'pear' in requested_fruits: 
    print("Adding pear.")
elif 'banana' in requested_fruits: 
    print("Adding banana.")
print("\nFinished adding your fruits!")

The first is to determine whether the check list containsapple, it passed, so add it to the shopping cartapple。 However, python will skipif-elif-elseFor the remaining judgment in the structure, no longer check whether the list containspearandbanana。 As a result, the first fruit the customer wants will be added, but no other fruit will be added:

Adding pear.

Finished adding your fruits!

In short, if you only want to execute one block of code, useif-elif-elseStructure, if you want to run multiple code blocks, you use a series of independent if statements.

Use the if statement to process the list

By combining if statements with lists, you can accomplish some interesting tasks: special processing of specific values in the list; Efficiently manage changing situations, such as whether restaurants have specific ingredients; The proof code will work as expected in all cases.

Check special elements

We started with a simple example of how to handle special valuesbmw——It needs to be printed in different formats. Now that you have a general understanding of conditional judgment and if statements, let’s further study how to check the special values in the list and deal with them appropriately.
Continue with the previous example of a list of fruits. Each time a fruit knife is added to the shopping cart, a message is printed. By creating a list of fruits that customers need to buy and using a loop to indicate who is added to the shopping cart, you can write such code with great efficiency:

requested_fruits = ['apple', 'pear', 'banana']
for fruit in requested_fruits: 
    print("Adding " + fruit + ".")
print("\nFinished adding your fruits!")

The output is simple because the above code is just a simple for loop:

Adding apple.
Adding pear.
Adding banana.

Finished adding your fruits!

However, if the fruit shopappleSold out, how to deal with it? To handle this situation properly, include an IF statement in the for loop:

requested_fruits = ['apple', 'pear', 'banana']
for fruit in requested_fruits: 
    if fruit == 'apple':
        print("Sorry, we are apple right now.")
    else:
        print("Adding " + fruit + ".")
print("\nFinished adding your fruits!")

Here, check every fruit added to the shopping cart. The if code determines whether the customer wants it or notapple, if yes, a message will be displayed. There is no such messageappleYes. Else code block ensures that other fruits can be added to the shopping cart:

Sorry, we are apple right now.
Adding pear.
Adding banana.

Finished adding your fruits!

Make sure the list is not empty

So far, a simple assumption has been made for each list processed, that is, they all contain at least one element. However, it is important to determine whether the list is empty before running the for loop.
Next, when adding shopping carts to customers, first judge whether the online product list is empty. If the list is empty, confirm to the customer whether he wants vegetables. If the list is not empty, add it to the shopping cart as in the previous example:

requested_fruits = []
if requested_fruits:
    for fruit in requested_fruits:
        print("Adding " + fruit + ".") 
        print("\nFinished adding your fruits!")
else:
    print("Are you sure you want some vegetables?")

Here, we first create an empty list that does not contain any fruit. First, we made a judgment instead of directly executing the for loop. When we directly determine whether a list is, python will return when the list contains at least one elementTrue, and returns when the list is emptyFalse。 Ifrequested_fruitsIf it is not empty, run the same for loop as the previous example, otherwise, print a message
Here, the list is empty, so the output is as follows – ask the customer if they need vegetables:

Are you sure you want some vegetables?

If this list is not empty, the fruit will be added to the shopping cart.

Small tasks:
10-1 check that the two numbers are equal, unequal, greater than, less than, greater than or equal to, and less than or equal to.
10-2 please create one named brush_ Color and set it to ‘green’, ‘yellow’, or ‘Red’. Write an IF statement to check whether the brush is green. If so, print a message.
10-3 set the color of the brush as in exercise 10-2 and write an if else structure. If the brush is green, print a message. If the brush is not green, print another message.
10-4 change the if else structure in exercise 10-3 to the if elif else structure. Implement the following logic
If the brush is green, print a message. It’s green.
If the brush is yellow, print a message. It’s yellow.
If the brush is red, print a message. It’s red.
10-5 different stages of life: set the value of the variable age, and then write an if elif else structure to judge which stage of life you are in according to the value of age.
If a person is less than 2 years old, print a message indicating that he is a baby.
If a person is 2 (inclusive) – 4 years old, print a message indicating that he is toddler.
If a person is 4 (inclusive) – 13 years old, print a message indicating that he is a child.
If a person is 13 (inclusive) – 20 years old, print a message indicating that he is a teenager.
If a person is 20 (inclusive) – 65 years old, print a message indicating that he is an adult.
If a person is over 65 (inclusive), print a message indicating that he is an elderly person.

If you want to check your homework answers, you can go toMy githu warehouse


[Python 1-10] Python hands-on tutorial -- an article on if statements and the special usage of if statements