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, if
carYour name equals
upper()Method to output the result in uppercase, if not equal to
bmwIt is output in uppercase.
The output results are as follows:
BMW Audi Toyota Honda
The core of each if statement is a value of
FalseThe expression is calledConditional statement。 The value judged by Python according to the condition is
FalseTo determine whether to execute the code in the if statement. If the value of condition judgment is
True, python executes the code immediately following the if statement; If yes
False, 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 to
bmw。 Next, use two equal signs
carIs the value of
bmw。 This equality operator returns when the values on both sides of it are equal
True, otherwise return
False。 In this example, the values on both sides are equal, so it returns
carThe value of is not
bmw, the above judgment will return
car = 'audi' print(car == 'bmw') False
A first equal sign sets the value of the variable car to
audi。 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 value
AudiThe above judgment will be returned regardless of the case of
True, because the judgment is case insensitive. function
lower()Variables stored in are not modified
carTherefore, 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 will
Apple(Apple) is stored in a variable, and what the customer wants to buy is
a mandarin orange(Orange), not required by customers
fruit = 'Apple' if (fruit != 'Orange'): print('do not need ' + fruit)
OrangeIf they are not equal, python returns
TrueAnd then execute the code immediately after the if statement; If the two values are equal, python returns
FalseTherefore, the code immediately following the if statement is not executed.
fruitThe value of is not
OrangeTherefore, it was implemented
Most conditional expressions we write check whether two values are equal, but sometimes it is more efficient to check whether two values are equal.
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 than、Less than or equal to、greater than、Greater 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 true
TrueThe 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 keyword
orIt can help us save a lot of things.
1. Use and to check multiple conditions
To check whether both conditions are
True, you can use keywords
andCombine the two conditional judgments into one; If each judgment passes, the whole expression is
True； If at least one judgment fails, the whole expression is
False。 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 age
age_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 is
Next we will
age_1Change to 22, so
age_1The value of is greater than 21, so both judgments pass, resulting in the result of the whole conditional expression is
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
orIt 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 fail
orThe expression for is
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. yes
age_0The judgment passed, so the result of the whole expression is
True。 Next, we will
age_0Change to 18. In the next judgment, neither judgment passes, so the result of the whole expression is
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 keyword
in。 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
inCan help us check
orange。 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 keywords
not 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.")
userThe value of is not included in the list
TrueTo execute indented lines of code.
marieNot included in list
banned_usersSo she will see a message inviting her to comment:
Marie, you can post a response if you wish.
As with conditional expressions, the result of a Boolean expression is either
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.
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 the
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 is
False, execute the following steps
elseCode block. this time
18, condition judgment failed, so execute
elseCode 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 for
PythonA situation in which one of two operations is performed. In this simple
if-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 python
if-elif-elseStructure. Python only executes
if-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:
- Free of charge under the age of 4;
- 5 yuan for 4-18 years old;
- 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 skip
elseCode block. If both the if and elif judgments fail, python runs the last one
elseCode in a code block.
In this example, the first
ifThe result of is false, so its code block is not executed. However, the result of the second judgment is
True(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, the
elseCode block, indicating that the ticket price is 10 yuan. To make the code more concise, you can not
if-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 needed
elifCode 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 second
elifAfter 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 require
if-elifStructure must be followed by else code block. In some cases,
elseCode blocks are useful, and in other cases, use one
elifStatement 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) + ".")
elifWhen the customer’s age exceeds 65 (inclusive), the code block sets the price to 5 yuan, which is better than using
elseCode 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 requirements
elifThe 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 one
elifCode block instead
elseCode 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 contain
elseA simple if statement of a code block. There may be multiple conditions for
True, and you need to be
TrueWhen 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 it
apple, if so, print a confirmation message. Second, check the fruit
pearThe code is also a simple if statement, not
elseStatement, so this judgment will be made whether the previous judgment passes or not. The third if code checks whether the customer wants it
banana; 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 list
Adding pear. Adding banana. Finished adding your fruits!
If you switch to the following
if-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 contains
apple, it passed, so add it to the shopping cart
apple。 However, python will skip
if-elif-elseFor the remaining judgment in the structure, no longer check whether the list contains
banana。 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, use
if-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 values
bmw——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 shop
appleSold 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 not
apple, if yes, a message will be displayed. There is no such message
appleYes. 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 element
True, and returns when the list is empty
requested_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.
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