A Free Trial That Lets You Build Big!
Start building with 50+ products and up to 12 months usage for Elastic Compute Service
5.1 A simple example
The following is a short example to demonstrate how to use the if statement to correctly handle special cases. Suppose we have a car list and want to print out the name of each car. For most cars, the name should be printed in uppercase, but for cars named "bmw", it should be printed in uppercase. The following code traverses a list and prints the name of a car in uppercase. However, for a car named "bmw", it is printed in uppercase:
Cars = ['Audi ', 'BMW', 'Subaru', 'Toyota '] for car in cars: if car = "bmw": print (car. upper () else: print (car. in this example, the cycle first checks whether the current car name is "bmw ". if yes, print it in uppercase; otherwise, print it in uppercase: AudiBMWSubaruToyota this example covers many concepts described in this chapter. Next we will introduce the test that can be used to check conditions in the program. 5.2 The core of each if statement is a True or False expression. this expression is called a conditional test. Python determines whether to execute the code in the if statement based on the True or False value of the conditional test. If the value of the conditional test is True, Python executes the code that follows the if statement. if the value is False, Python ignores the code. 5.2.1 check for equality most condition tests compare the current value of a variable with a specific value. The simplest condition test checks whether the variable value is equal to a specific value: >>> a = "bmw" >>> a = "bmw" True we first use an equal sign to set the car value to "bmw". we have seen this practice many times. Next, use two equal signs (=) to check whether the car value is "bmw". The equal operator returns True if the values on both sides are equal; otherwise, False. In this example, the values on both sides are equal, so Python returns True. If the value of the variable car is not 'BMW ', the above test will return False: >>> a = 'BMW' >>>> a = 'Audi 'false an equal sign is a statement; the code at an equal sign can be interpreted as "setting the variable car value to 'Audi '. two equal signs are used to ask questions. for the code at the two equal signs, can it be interpreted as "is the variable car value" bmw? ". Most programming languages use equal signs in the same way as described here. Summary: In Python, True or False is returned when the if statement is judged. True is returned if the condition is met; otherwise, False is returned, the two equal signs (=) ask if Python is equal. 5.2.2 when checking whether the values are equal, check whether the time zone is case-insensitive in Python. for example, two values with different cases are considered unequal: >>> car = 'Audi '> car = 'Audi' False if case sensitivity is very 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 lower case and then compare it: >>> car = "Audi" >>> car. lower () = 'Audi 'True regardless of the case of The 'Audi 'value, True is returned for the above test because the test is case insensitive. The lower function does not modify the value stored in the variable car. Therefore, such a comparison does not affect the original variable: (1) >>> car = "Audi" (2) >>> car. lower () = "audi" True (3)> car 'Audi 'at (1), we store the uppercase character string "Audi" in the variable car; at (2), we get the value of the variable car and convert it to lower case. we can compare the result with the string 'Audi. The two strings are the same, so Python returns True. According to the output at (3), this condition test does not affect the value stored in the variable car. The following describes how to register a website: [object Object]
First, when we register a website, the website will first let us enter the user name, and then will prompt us whether this user name is available; if the user name is unavailable, it will prompt us that this user name has been registered, enter the user name again. if the user name is not registered, you can follow the registration process step by step. after the user registration is successful, you need to put the registered user name in the previous registered user name, this means that the same user name cannot be registered during the next user registration, so that the registered account will not be repeated.
However, during the registration process, we need to make a unified judgment on the user name. The user name we enter may be in uppercase or lowercase, but the same user name may be in various states regardless of the case, the next user cannot be used. Therefore, we need to convert all registered users into lowercase letters, the names of the users to be registered are also converted to lowercase letters and then judged. if they are not already registered, they can be used. Otherwise, you must enter the registration information again.
This is the idea of registering the flowchart above. the code is as follows:
# Register = input ("Please input your username:") # First define an empty list, transformation_registered_names =  # registered user registered_users = ["Zengmingzhu", "zhagnqq", "jIangxb", "gZd", "loujq ", "liuxs", "cDq"] # use the True loop. when the user name is the same, you can keep the user input without exiting. while True: register = input ("Please input your username: ") # use the for loop to convert the list of registered users to a unified for user_name in registered_users: transformation_registered_names.append (user_n Ame. title () # Use if to determine whether the input username (lowercase conversion) exists in the registered list if register. title () in transformation_registered_names: print ("Sorry, the name you entered is registered! Please enter again ") else: print (" Successful! ") Registered_users.append (register) breakprint (registered_users) run the following results: Please input your username: zengmignzhuSuccessful! ['Zengmingzhu', 'zhagnqq', 'jiangxb ', 'gzd', 'loujq', 'liuxs', 'cdq', 'zengmignzhu'] ideas: first, we all know that our registration information list is available on the website the next day. This list is named registered_users, and an empty list is defined to store the converted registered users and named transformation_registered_names, then, use the while loop so that the user can enter a registered user again so that different user names can be entered. in the while loop, we use the for loop to convert, then, use the if statement to judge whether the user name is in use. if the user name does not exist, the user is prompted to use the user name, in addition, you need to store the registered user name to the registration user name list in the website background, so that the user name of the next user is unique with the current user name. The website adopts a similar method to make the data entered by the user conform to the specific format. For example, a website may use a similar test to ensure that the user name is unique, not just in case of another user name. When you submit a new user name, convert it to lowercase and compare it with the lower-case versions of all existing users. When performing this check, if the user name 'join' already exists (regardless of case), the user will be rejected when submitting the user name 'join. 5.2.3 check whether the two values are unequal. you can use the exclamation mark and equal sign (! =), Where the exclamation point indicates no, which is true in many programming languages. Next we will use an if statement to demonstrate how to use unequal operators. We will store the required pizza ingredients in a variable and print a message indicating whether the ingredients requested by the customer are anchovies: requested_topping = 'Mushrooms 'if requested_topping! = 'Anchovies': print ("Hold the anchovies! ") The code compares the requested_topping values with 'anchovies'. if they are not equal, Python returns True, and then runs the code that follows the if statement. if the two values are equal, python returns False, so the code followed by the if statement is not executed. Because the requested_topping value is not 'anchovies', execute the print statement: Hold the anchovies! Most of the conditional expressions we write check whether the two values are equal, but sometimes it is more efficient to check whether the two values are unequal. 5.2.4 it is very easy to compare numeric values. for example, we can check whether a person is 18 years old: >>>> age = 18 >>> age = 18 True. we can also check whether the two numbers are different, for example, the following code prints a message when the provided answer is incorrect: answer = 17 if answer! = 42: print ("That is not the correct answer. Please try again! ") Answer (17) is not 42, the condition is met, so the indent code block can be executed: That is not the correct answer. Please try again! Conditional statements can contain various mathematical comparisons, such as less than, less than or equal to, greater than, and greater than or equal to: >>> age = 19 >>> age <21 True >>> age <= 21 True >>> age> 21 False >>> age >=21 False you can use various mathematics in the if statement. comparison, this allows us to directly check the conditions of interest. 5.2.5 check multiple conditions we may want to check multiple conditions at the same time. for example, sometimes we need to perform the corresponding operation when both conditions are True, sometimes, when only one condition is required to be True, the corresponding operation is performed. In these cases, the keywords and or can help us. 1. use and to check whether both conditions are True. use the keyword and to combine the two conditions. if each test passes, the entire expression is True; if at least one test fails, the true expression is False. For example, to check whether both users are younger than 21 years old, you can use the following test: >>> age_0 = 22 >>> age_1 = 18 >>> age_0 >=21 and age_1 >=21 False >>>> age_1 = 22 >>> age_0 >= 21 and age_1 >= 21 true improves readability, each test can be placed in a bracket, but this is not required. If we use parentheses, the test will look like the following: (age_0> = 21) and (age_1> = 21) 2. use or to check multiple conditions> age_0 = 18> age_1 = 22> (age_0> = 21) or (age_1> = 21) true >>> age_1 = 18 >>> (age_0 >= 18) or (age_1 >= 18) True >>> (age_0 >= 21) or (age_1 >= 21) false. Similarly, we first define two variables for age storage. If one condition is met, the result is True. if both conditions are not met, the result is False.
Banned_users = ['Andrew ', 'mongolina', 'David'] user = 'Marie' if user not in banned_users: print (user. title () + ", you can post a response if you wish. ") the code is easy to understand: if the user value is not included in the banned_users list, Python returns True and then runs the indented code line. The user "marie" is not included in the banned_users list, so he will see a message inviting him to comment: Marie, you can post a response if you wish.5.2.8 Boolean expressions as we learn more and more about programming, we will encounter a Boolean expression, which is just an alias for conditional testing. Like a conditional expression, the result of a Boolean expression is either True or False. Boolean values are usually used to record conditions, such as whether a game is running or whether a user can edit specific content of a website: game_active = True can_edit = False boolean value provides an efficient way to track program states or important conditions in programs. 5.3 After the if statement understands the condition test, you can start to write the if statement. There are many if statements, depending on the number of conditions to be tested. In the previous discussion on conditional testing, we listed multiple if statement Examples. the topic is further discussed below. 5.3.1 simple if statements the simplest if statement has only one Test and one operation: if conditional_test: do something can contain any condition test in row 1st, in the indent code block that follows the test, you can perform any operation. If the conditional test result is True, Python executes the code that follows the if statement; otherwise, Python ignores the code. Suppose there is a variable that represents a person's age, and you want to know whether the person is age enough to vote, you can use the following code:
Age = 19if age> = 18: print ("You are old enough to vote! ") Python checks whether the value of the variable age is greater than or equal to 18; the answer is yes, so Python executes the indented print statement: You are old enough to vote! In the if statement, indentation serves the same purpose as in the for loop. If the test passes, all indented code lines after the if statement are executed; otherwise, they are ignored. In China, the code block following the if statement can contain any number of code lines as needed. When a person is age enough to vote, he will print a line of output and ask him if he has registered it:
Age = 19if age> = 18: print ("You are old enough to vote! ") Print (" Have you registered to vote yet? ") The condition test is passed, and the two print statements are indented, so they will all be executed: You are old enough to vote! Have you registered to vote yet? If the age value is less than 18, this program will not have any output. 5.3.2 if-else statements often need to execute an operation when the conditional test is passed and execute another operation when the test fails. in this case, the if-else statement block provided by Python is similar to a simple if statement, but the else statement allows us to specify the operations to be executed when the condition test is not passed. The following code displays the same information in front of u when a person is older than the voting age, and displays a message when the person is not older than the voting age:
Age = 17if age> = 18: print ("You are old enough to vote! ") Print (" Have you registered to vote yet? ") Else: print (" You are too young to vote. ") print (" Please register to vote as soon as you turn 18! ") If the condition test passes, execute the print statement block of the first indent. if the test result is False, execute the else code block. This time the age is less than 18 and the condition test fails. Therefore, run the code in the else code block: You are too young to vote. Please register to vote as soon as you turn 18! The above code is feasible because there are two cases of values; either the age of voting or not enough. The if-else structure is very suitable for Python to execute one of the two operations. In this simple if-else structure, one of the two operations is always executed. 5.3.3 the if-elif-else structure often needs to check more than two situations. Therefore, you can use the if-elif-else structure provided by Python. Python only executes a code block in the if-elif-else structure, which checks each conditional test until it passes the conditional test. After the test is passed, Python executes the code that follows it and skips the remaining Tests. In the real world, there are more than two situations to consider. For example, to see a playground charged by Age Group: 1. free of charge for children under four years old; 2. 4 ~ $5 for the age of 18; $10 for the age of 3 and 18 (inclusive. If only one if statement is used, how can I determine the ticket price? The following code identifies a person's age group and prints a message containing the ticket price:
Def your_age (age): if age <4: print ("Your admission cost is $0. ") elif age> = 4 and age <18: print (" Your admission cost is $5. ") else: print (" Your admission cost is $10. ") # I'm thinking about how to let users enter their own names. in programming, our programmers certainly know how to call functions, but users do not know your_age (18) your_age (10) your_age (2) # The problem of age can be returned. we can directly redefine an age variable so that users can enter it. but how can we solve the problem of automatic function call, the user cannot call the function my_age = int (input ("Please input your age:") your_age (my_age) if to check whether a person is 4 years old. if so, Pyth On prints an appropriate message and skips the remaining test. The elif code line is actually another if test. it runs only when the previous test is not passed. Here, we know that this person is not younger than 4 years old because the first test failed. If this person is under 18 years old, Python will print the corresponding message and skip the else code block. if both the if test and the elif test fail, Python will run the code in the else code block. To make the code more concise, you can not print the ticket price in the if-elif-else code block. Instead, you can only set the ticket price and add a simple print statement later:
Def your_age (age): if age <4: price = 0 elif age> = 4 and age <18: price = 5 else: price = 10 print ("Your admission cost is $" + str (price) + ". ") # I'm thinking about how to let users enter their own names. in programming, our programmers certainly know how to call functions, but users do not know your_age (18) your_age (10) your_age (2) # The problem of age can be returned. we can directly redefine an age variable so that users can enter it. but how can we solve the problem of automatic function call, you cannot call the my_age = int (input ("Please input your age:") your_age (my_age) code line by yourself, as in the previous example, set the value of the variable price based on the age of the person. After the price value is set in the if-elif-else structure, an unindented print statement prints a message based on the value of this variable, indicating the price of the ticket. The output of these codes is the same as that in the previous example, but the if-elif-else structure is less effective. it only determines the price of the ticket, rather than printing a message while determining the price of the ticket. In addition to higher efficiency, the modified code is easier to modify: to adjust the content of the output message, you only need to modify one statement instead of three print statements. Note: The Python code is concise and beautiful. the fewer functions of a function, the better. try to be concise, avoid repetitive work, and put repetitive work in the last module, when encountering repetitive code blocks, try to optimize the code and make the code simple and best. 5.3.4 multiple elif code blocks can be used based on any number of elif code blocks. for example, if a discount is required for the elderly at the playground, you can add another conditional test to determine whether the customer meets the discount conditions. The following example shows that a person over 65 years old can buy a ticket at half price ($5:
Def your_age (age): if age <4: price = 0 elif age> = 4 and age <18: price = 5 elif age <65: price = 10 elif age> = 65: price = 5 print ("Your admission cost is $" + str (price) + ". ") # I'm thinking about how to let users enter their own names. in programming, our programmers certainly know how to call functions, but users do not know your_age (18) your_age (10) your_age (2) # The problem of age can be returned. we can directly redefine an age variable so that users can enter it. but how can we solve the problem of automatic function call, you cannot call the my_age = int (input ("Please input your age:") your_age (my_age) function by yourself. The second elif code block checks to determine that the ticket price is set to full price-$10 after the age is less than 65. Note that in the else code block, the assigned value must be changed to 5 because the code block is executed only when the age is over 65. 5.3.5 omitting the else code block Python does not require that the if-elif structure be followed by an else code block. In some cases, the else code block is useful. In other cases, you can use an elif statement to handle specific situations more clearly: the elif code block is more than 65 (inclusive) of the customer's age) the price is set to $5, and the use of the else code block is clearer. After such modification, each code block is executed only when the corresponding test is passed. Else is an all-encompassing statement. as long as it does not meet any conditions in the if or elif test, the code will be executed, which may introduce invalid or even malicious data. If you know the conditions for the final Test, consider using an elif code block instead of else. In this way, we can be sure that our code will be executed only when the corresponding conditions are met. 5.3.6 test multiple conditions if-elif-else has a powerful structure, but it is only suitable for situations where only one condition is met: After the test is passed, Python skips the remaining Tests. This kind of behavior is good and efficient, so that we can test a specific condition. However, sometimes all the conditions that we care about must be checked. In this case, you should use a series of simple if statements that do not contain the elif and else code blocks. This method is applicable when multiple conditions are True, and we need to take appropriate measures when each condition is True. Toppings. py
Requested_toppings = ['Mushrooms ', 'extra chees'] if 'Mushrooms' in requested_toppings: print ("Adding mushrooms. ") if 'pepperons' in requested_toppings: print (" Adding pepperoni ") if 'extra chees' in requested_toppings: print (" Adding extra cheese ") print ('\ nFinished making your pizza! ') We first created a list containing the ingredients for the customer's vertex. The if statement checks whether the customer has ordered the mushroom ('Mushrooms '). if yes, a confirmation message is printed. Check the ingredients sausage ('pepperons'). This program will perform the next test regardless of whether the previous test has passed. Each time the program runs, these three independent tests are performed. In this example, each condition is checked, so a mushroom is added to the pizza and the cheese is added: Adding mushrooms. Adding extra cheeseFinished making your pizza! If you use the if-elif-else structure in the following way, the code will not run correctly, because after a test passes, the remaining tests will be skipped:
Requested_toppings = ['Mushrooms ', 'extra chees'] if 'Mushrooms' in requested_toppings: print ("Adding mushrooms. ") elif 'pepperons' in requested_toppings: print (" Adding pepperoni ") elif 'extra chees' in requested_toppings: print (" Adding extra cheese ") print ('\ nFinished making your pizza! ') The first test checks whether the list contains 'Mushrooms'. if it passes, it adds mushrooms to the pizza. However, Python skips the test in the remainder of the if-elif-else structure and does not check whether the list contains 'extra chees' and 'pepperons '. the result is that the first ingredient of the customer's vertex will be added, but no other ingredients will be added: Adding mushrooms. finished making your pizza! In short, if we only want a code block of the star, we will use the if-elif-else structure. if we want to run multiple code blocks, we will use a series of independent if statements. Try 5-3 alien_color = 'yellow' if alien_color = 'yellow': print ("You get 5 score.") if alien_color! = 'Yellow': print ("The other color. ") 5-4alien_color = 'red' if alien_color = 'yellow': score = 5 else: score = 10 print (" You get "+ str (score) +" score. ")
5.4 using the if statement processing list combined with the if statement and list can complete some interesting tasks: special processing of specific values in the list; efficient management of changing situations, such as whether a restaurant has specific ingredients; proof that the code can run as expected in various circumstances. 5.4.1 check Special elements this chapter begins with a simple example to demonstrate how to process the special value 'BMW '-it needs to be printed in different formats. Since we have a rough understanding of the conditional test and if statements, we will further study how to check the special values in the list and make appropriate processing for them. Continue to use the previous Pisa store example. This pizza store prints a message for each ingredient added when making a pizza. By creating a list containing the ingredients of a customer's vertex and using a loop to indicate the ingredients added to a pizza, you can write this code with high efficiency:
Requested_toppings = ['Mushrooms ', 'extra chees', 'pepperons'] for requested_topping in requested_toppings: print ("Adding" + requested_topping + '. ') print ("\ nFinished making your pizza. ") the output is very simple, because the above code is just a simple for loop: Adding mushrooms. adding extra cheese. adding pepperoni. finished making your pizza. however, if the green peppers in the pizza store are used up, what should we do? To properly handle this situation, you can include an if statement in the for loop:
Requested_toppings = ['Mushrooms ', 'extra cheese', 'pepperons'] for requested_topping in requested_toppings: # add the if condition to determine whether pepperoni is used up, if requested_topping = 'pepperoni ': print ("Sorry, we are out of pepperoni right now. ") else: print (" Adding "+ requested_topping + '. ') print ("\ nFinished making your pizza. ") check before adding each type of ingredients to the pizza. The code checks whether the customer points are green peppers. If yes, a message is displayed, indicating the reason why green peppers cannot be clicked. The code block at the else ensures that other ingredients are added to the pizza. The output indicates that each of the ingredients of the customer's vertex is properly handled: Adding mushrooms. adding extra cheese. sorry, we are out of pepperoni right now. finished making your pizza.5.4.2 determines that the list is not empty so far. a simple assumption is made for each list to be processed, that is, they all contain at least one element. We will immediately ask users to provide information stored in the list. Therefore, we cannot assume that the list is not empty during loop runtime. Therefore, it is important to determine whether the list is empty before running the for loop. Before making a pizza, check whether the ingredients list of the customer's site is empty. If the list is empty, confirm with the customer if she wants a regular pizza. if the list is not empty, make a pizza as in the previous example:
Requested_toppings =  # check whether the list is empty. if it is empty, an error occurs. Therefore, you must first determine whether the list is empty. if requested_toppings: for requested_topping in requested_toppings: if requested_topping = 'pepperons': print ("Sorry, we are out of pepperoni right now. ") else: print (" Adding "+ requested_topping + '. ') print ("\ nFinished making your pizza. ") else: print (" Are you sure you want a plain pizza? ") Here, we first create an empty list that does not contain any ingredients. The first if statement performs a simple check instead of directly executing the for loop. When the list name is used in a conditional expression in an if statement, Python returns True if it contains at least one element in the list and returns False if the list is empty. If requested_toppings is not empty, run the for loop that is the same as the previous example. Otherwise, a message is printed asking the customer if they really want a normal pizza without any ingredients. Here, the list is empty, so the output is as follows -- ask the customer if they really want a normal pizza: Are you sure you want a plain pizza? If this list is not empty, the output of various ingredients added to the pizza is displayed. 5.4.3 The requirements for using multiple List customers are often varied, especially in the aspect of pizza ingredients. What if a customer wants to add French fries to a pizza? You can use the list and if statements to determine whether the query meets the requirements of customers. Let's see how to reject the weird ingredient requirements before making a pizza. The following example defines two lists, the first of which contains the ingredients supplied by the pizza store, and the second of which contains the ingredients of the customer's point. This time, for each element in requested_toppings, check whether it is a ingredient provided by the Pisa store and decide whether to add it to the Pisa:
Available_toppings = ['Mushrooms ', 'olives', 'Green Peppers', 'pepperons', 'pineapple', 'extra chees'] requested_toppings = ['Mushrooms ', 'French fries', 'extra chees'] for requested_topping in requested_toppings: if requested_topping in available_toppings: print ("Adding" + requested_topping + '. ') else: print ("Sorry, we don't have" + requested_topping + '. ') print ("\ nFinished making your pizza. ") first, we define A pizza store provides a list of ingredients. Note that if the ingredients provided by the pizza store are fixed, you can use a single tuple to store them. Next, we have defined a list that contains the ingredients for the customer's Vertex. Please note that the unusual ingredient-'French fries'. then we traverse the ingredients list for the customer's vertex. In this cycle, we check whether each of the ingredients purchased by the customer is contained in the ingredients that are provided, and if the answer is yes, add them to the pizza, otherwise, the False code block will be run: print a message and tell the customer not to supply the ingredients. the output of the code is neat and detailed: Adding mushrooms. sorry, we don't have french fries. adding extra cheese. finished making your pizza. give a try 5-8 and greet the administrator in a special way: This article describes the use of the for loop and if statements. when a user logs on to the website, the user will be judged based on the user's nature.
Login_users = ['admin', 'zhangxx', 'loujq', 'xiaoaj ', 'liuxs'] for login_user in login_users: if login_user = 'admin ': print ("Hello admin, wocould you like to see a status report? ") Else: print (" Hello Eric, thank you for logging in again. ") 5-9 no user processing: This question first checks whether the user list is empty. if it is empty, what operations are performed? if not empty, another operation is performed:
Login_users =  # check whether the list is empty. if it is empty, run the empty statement if login_users: for login_user in login_users: if login_user = 'admin ': print ("Hello admin, wocould you like to see a status report? ") Else: print (" Hello Eric, thank you for logging in again. ") else: print (" We need to find some users! ") 5-10 check the user name
Current_users = ['admin', 'zqq', 'lxs ', 'ljq', 'dls', 'gw', 'scs'] new_users = ['gcx ', 'zmz', 'lxs ', 'gjz', 'scs'] transfor_current_users =  # converts all user names to lowercase letters, to ensure the uniqueness of the user name for current_user in current_users: transfor_current_users.append (current_user.title () for new_user in new_users: if new_user.title () in transfor_current_users: print ("The user name of" + new_user + "has been registered, please enter another us Er name. ") else: print (" This user name is not used. ") this topic describes the representation method of the list, then the use of if-elif-else, and the features of the for loop traversal list, a for loop traverses every element of the list. it traverses from the first element of the list and runs the entire program.
Ordinal_numbers = list (range () for ordinal_number in ordinal_numbers: if ordinal_number = 1: print (str (ordinal_number) + 'st') elif ordinal_number = 2: print (str (ordinal_number) + 'nd') else: print (str (ordinal_number) + 'th ') 5.5 set the format of the if statement each example in this chapter shows the good format setting habits. In terms of format settings for conditional testing, the only recommendation provided by PEP 8 is to add a space on both sides of comparison operators, such as ==, >=, and <=. for example, if age <4; is better than if age <4. Such spaces do not affect Python's interpretation of the code, but make it easier to read the code.
The above is the details of the if statement for getting started with Python. For more information, see other related articles in the first PHP community!
Start building with 50+ products and up to 12 months usage for Elastic Compute Service