Python Introductory if statement

Source: Internet
Author: User
Tags list of attributes uppercase letter ticket
When programming, you often need to check a set of conditions and decide what action to take accordingly. In Python, the IF statement allows us to examine the current state of the program and take appropriate action accordingly.

5.1 A simple example

The following is a short example that demonstrates how to use an if statement to handle a particular situation correctly. Let's say we have a list of cars and want to print out the name of each car. For most cars, the names should be printed in uppercase letters, but for cars named "BMW", they should be printed in full capitalization. The following code iterates through a list and prints the name of the car in an uppercase letter, but for the car named "BMW", it is printed in full capitalization:

Cars = [' Audi ', ' BMW ', ' Subaru ', ' Toyota ']for car in cars:if car = = "BMW":p rint (Car.upper ()) Else:print (Car.title ()) The loop in this example first checks whether the current car name is "BMW". If so, print it in full capitalization; otherwise it will be printed in uppercase: Audibmwsubarutoyota This example covers many of the concepts described in this chapter. The following first describes the tests that you can use to check conditions in your program. 5.2 Article tests the core of each if statement is an expression that evaluates to True or FALSE, which is called a conditional test. Python determines whether execution executes the code in the If statement based on the value of the condition test as true or false. If the value of the condition test is True,python, the code immediately following the IF statement is executed, and if it is False,python, the code is ignored. 5.2.1 Checking for equality most condition tests compare the current value of a variable with a specific value. The simplest condition test checks if the value of a variable is equal to a specific value:>>> a = "BMW" >>> a = = "BMW" True we first use an equal sign to set the value of car to "BMW", which we have seen many times. Next, use the two equals sign (= =) to check whether the car's value is "BMW". This equality operator returns true if the values on either side of it are equal, otherwise false is returned.    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 stated; for the code at an equal sign, it can be interpreted as " Set the value of the variable car to ' Audi '. Two equals is the question; for the code at two equals, it can be interpreted as "is the value of car variable" BMW "? ". Most programming languages use the equals sign in the same way as shown here. Summary: In Python, the IF statement evaluates to TRUE or FALSE, returns true if the condition is satisfied, or false if it is not satisfied, and two equal signs (= =) are questions asking whether Python is equal or not. 5.2.2 Checks if case is case-insensitive when checking for equality, in Python, for example, two different case values willis considered unequal:>>> car = ' audi ' >>> car = = ' Audi ' False if capitalization is important, this behavior has its advantages. But if the case doesn't matter, and you just want to check the value of the variable, you can convert the value of the variable to lowercase, and then compare:>>> car = "Audi" >>> car.lower () = = ' Audi ' True regardless of value ' Audi ' The above test will return true because the test is not case-sensitive. The function lower does not modify the value stored in the variable car, so this comparison does not affect the original variable: (1) >>> car = "Audi" (2) >>> car.lower () = = "Audi" True (3) >>> car ' Audi ' at (1), we store the capitalized string "Audi" in the variable car, and at (2) we get the value of the variable car and convert it to lowercase, comparing the result to the string ' Audi '. The two strings are the same, so Python returns True.    From the output at (3), this condition test does not affect the value stored in the variable car. Here's a scenario for simulating a site registration: [Object Object]

First, when we register the website, the website will let us enter the user name first, then will prompt us this user name is available, if can the user name not be usable, prompt us this username has already registered, please re-enter the user name, if the user name is not registered, you can follow the registration process step by step down, After the user registration is successful, to put the registered user name in the previous registered user name, in order to prompt the next user registration, the same user name can not be registered, so that the registered account will not repeat the situation.

But note that in the process of registration, we have to judge the user name uniformly, we enter the username may have uppercase and lowercase, but the same user name regardless of the state of the case, the next user is not able to use, so to unify the conversion, how to transform it, The idea is to directly convert all registered users into lowercase, and now the name of the user to register the unified conversion to lowercase, and then to judge, if not already registered users can use, otherwise, you will re-enter the registration.

This is the idea of the above flowchart registration, the code is as follows:

#register = input ("Please input your username:") #首先定义一个空的列表, the user stores the lowercase converted user Transformation_registered_names = []# Registered Users registered_users = ["Zengmingzhu", "Zhagnqq", "Jiangxb", "GZd", "LOUJQ", "Liuxs", "CDq"] #使用True循环, when the user name is the same, Allows the user to enter all the time without exiting while true:register = input ("Please input your username:") #使用for循环 to convert the list of registered users to a unified conversion for USER_NAME In Registered_users:transformation_registered_names.append (User_name.title ()) #使用if进行判断, determine the user name entered ( lowercase conversions) If there is a registered list of if Register.title () in Transformation_registered_names:print ("Sorry, the name of the entered is Registe red!        Please enter Again ") Else:print (" successful! ") Registered_users.append (Register) breakprint (registered_users) operation results are as follows: Please input your username: zengmignzhusuccessful! [' Zengmingzhu ', ' zhagnqq ', ' jiangxb ', ' gZd ', ' loujq ', ' liuxs ', ' cDq ', ' Zengmignzhu '] ideas: First of all we know that the website has a list of our registration information the day after tomorrow, This list is named Registered_users and then defines an empty list for the converted registered user, named Transformation_registered_names, and then using the while loop, So that when a user enters a registered user, they can enter it again to enter a different user name; in while, we use the FOR Loop on the line conversion, and then use the IF statement to judge, when the user name has been used, let the user re-enter, when the user name does not exist, prompt the user can use this user name, and to the registered user name stored in the background of the website registered user list,    So that the next registered person user name is unique to the current user name. The site takes a similar approach to allowing the user to enter data that conforms to a specific format. For example, a Web site might use a similar test to make sure that the user name is unique, not just a different case from another user name. When a user submits a new user name, it is converted to lowercase and compared to all lowercase versions of the existing user name. When this check is performed, if the user name ' join ' is already present (regardless of capitalization), the user will be rejected when submitting the user name ' join '.    5.2.3 Check for inequality to determine whether two values are unequal, use an exclamation point and an equals sign (! =), where the exclamation point indicates no, in many programming languages. The following uses an if statement to demonstrate how to use the inequality operator. We will store the requested pizza ingredient in a variable and print a message stating whether the customer's requested ingredient is an Italian small fish (anchovies): requested_topping = ' mushrooms ' if requested_topping! = ' A Nchovies ':p rint ("Hold the Anchovies!") The code compares the values of requested_topping with ' anchovies ', and if they are not equal, Python returns True to execute the code immediately following the IF statement, and if the two values are equal, Python returns false.    Therefore, the code immediately following the IF statement is not executed.    Because the value of requested_topping is not ' anchovies ', the print statement is executed: hold the anchovies! Most of the conditional expressions we write check that two values are equal, but sometimes it is more efficient to check whether two values are unequal. 5.2.4 comparison number check is very simple, for example, the following check whether a person is 18 years old:>>> age = 18>>> Ages = = 18True We can also check whether two numbers are unequal, for example, the following code in the provided answer does not Print a message correctly: Answer = if answer! = 42:print ("That's not the correct answer. Please try Again! ") Answer (17) was not 42 and the condition was met, so the indented code block was executed: that was not the correct answer.    Please try Again!    A conditional statement can contain various mathematical comparisons, such as less than, less than or equal, greater than, greater than or equal to: >>> age = + >>> Age < True >>> age<=21 True >>> age>21 false >>> age>=21 false in the IF statement can use a variety of mathematical comparisons, which allows us to directly examine the conditions of concern. 5.2.5 checking multiple conditions we may want to check multiple conditions at the same time, for example, sometimes we need to perform the corresponding operation when two conditions are true, and sometimes we only require a condition to be true.    In these cases, keywords and and or can help us.    1, use and check multiple conditions to check whether the two conditions are true, you can use the keyword and the two condition test into one; if each test passes, the entire expression is true; if at least one test does not pass, the whole expression is false. For example, to check that two people are less than 21 years old, use the following test: >>> age_0 = x >>> age_1 = Six >>> age_0 >= and Age_1 = False >>> age_1 = $ >>> age_0 >=21 and Age_1 >= True to improve readability, each test can be placed in parentheses, but not necessarily be required to do so. If we use parentheses, the test will resemble the following: (Age_0 >=) and (Age_1 >= 21) 2, use or to check multiple conditions >>> age_0 = >>> Age_1 = >>> (Age_0 >=) or (age_1 >=) True >>> age_1 = >>> (Age_0 >=) or (age_1 >=) True >>> (Age_0 >=) or (Age_1 >= 21 False again, we first defined two variables for storing age. As long as one condition satisfies, the result is true, and only two conditions are not satisfied, the result is false.
banned_users = [' Andrew ', ' Carolina ', ' david ']user = ' Marie ' If user not in Banned_ Users:print (User.title () + ", can post a response if you wish.")    The code is understandable: if the value of user is not included in the list banned_users, Python returns True, and the line of code that is indented is executed. The user "Marie" is not included in the list banned_users, so he will see a message inviting him to comment: Marie, can post a response if you wish.5.2.8 Boolean expression as we learn more about programming The more deeply you will encounter the term Boolean expression, which is merely the alias of the conditional test.    As with the conditional expression, the result of the Boolean expression is either True or false. Boolean values are typically used to record conditions, such as whether the game is running, or whether the user can edit specific content of the site: game_active = True Can_edit = False Boolean values provide an efficient way to track program state or important conditions in a program. After the 5.3 If statement understands the conditional test, you can begin writing an if statement. If there are many kinds of statements, choose which depends on the number of conditions to test. When we discussed the condition test earlier, we enumerated several examples of if statements, which are discussed in more depth below. 5.3.1 Simple If statement the simplest if statement has only one test and one action: if conditional_test:do something in line 1th, can contain any conditional tests, and in the indentation code block immediately following the test, any action is performed 。    If the result of the condition test is True,python, the code immediately following the IF statement is executed, otherwise Python ignores the code. Suppose you have a variable that represents someone's age, and you want to know if the person is old enough to vote, use the following code: 
Age = 19if Age >= 18:print ("Your is old enough to vote!") Python checks if 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're old    enough to vote!    In an If statement, the indentation acts the same as for the For loop. If the test passes, all lines of code that are indented after the IF statement are executed, otherwise they will be ignored.    in the code block immediately following the IF statement, China can include as many lines of code as needed. Below when a person is enough to vote for the age of printing a line of output, asked if he registered:
Age = 19if Age >=:    print ("Enough to vote!")    Print ("Registered to vote yet?")    The condition test passes, and two print statements are indented, so they are all executed: you're old enough to vote! Registered to vote yet?    If the value of age is less than 18, the program will not have any output. 5.3.2  if-else Statements    often need to perform an action when the condition test passes and perform another operation without passing, in which case the IF-ELSE statement block provided by Python is similar to a simple if statement. But the Else statement in it allows us to set the action to be taken when the condition test fails. The    following code displays the same information in front of you when a person has enough voting age, and displays a message when the person is not enough to vote for:
age = 17if Age >= 18:print ("Your is old enough to vote!") Print ("Registered to vote yet?") Else:print ("You were too young to vote.")    Print ("Register to vote as soon as turn 18!") If the condition test passes, the first indented print statement block is executed, and if the test result is false, the else code block is executed.  This time, age is less than 18, and the condition test does not pass, so execute the code in the Else code block: You is too young to vote.    Register to vote as soon as turn 18! The code above works because there are two scenarios for the value, or enough to vote for, or not enough. The IF-ELSE structure is ideal for situations where Python performs one of two operations. In this simple if-else structure, one of the two operations is always performed. The 5.3.3 If-elif-else structure often needs to check for more than two cases, so you can use the IF-ELIF-ELSE structure provided by Python. Python executes only one block of code in the If-elif-else structure, which examines each condition test until it encounters the passed condition test.    After the test passes, Python executes the code immediately following it and skips the rest of the tests. In the real world, there are more than two scenarios to consider.  For example, take a look at a playground based on age: 1, four years of age free, 2, 4~18岁 charges 5 USD, 3, 18 years old (inclusive) 10 USD. If you use only one if statement, how do you determine the ticket price? The following code determines the age in which a person belongs and prints a message containing the ticket price: 
def your_age (age): If Age < 4:print ("Your admission cost is $ $.") Elif Age >= 4 and Age < 18:print ("Your admission cost is $ $.") Else:print ("Your admission cost is $.") #我在考虑, how the result lets the user input the name, in the programming, we programmer certainly knew how to call the function, but the user did not know Your_age (your_age) your_age (2) #年龄的问题可以结果, we directly redefine an age variable , let the user input, but how to solve the problem of automatic call function, it is impossible for the user to call the function my_age = Int (input ("Please input your Age:")) Your_age (my_age) If detection check whether a person is over 4 years old, If so, Python prints an appropriate message and skips the rest of the tests. The Elif code line is actually another if test, which runs only when the previous test fails. Here, we know that this person's age is not less than 4 years old, because the first Test failed.    If this person is under 18, Python will print the appropriate message and skip the else code block, and if neither the if test nor the elif test pass, Python will run the code in the Else code block. To make the code more concise, do not print the ticket price in the If-elif-else code block, but only set the ticket price in it, 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 = ten print ("Your admission cost are $" + str (price) + ".") #我在考虑, how the result lets the user input the name, in the programming, we programmer certainly knew how to call the function, but the user did not know Your_age (your_age) your_age (2) #年龄的问题可以结果, we directly redefine an age variable , let the user input, but how to solve the problem of automatic call function, it is impossible for the user to call the function my_age = Int (input ("Please input your Age:")) Your_age (my_age) line of code or as in the previous example, Sets the value of the variable price according to the age of the person.    After you set the value of price in the IF-ELIF-ELSE structure, an indented print statement prints a message based on the value of the variable, indicating the cost of the ticket. The output of the code is the same as the previous example, but the IF-ELIF-ELSE structure is less useful, it only determines the price of the ticket, not the price of the ticket to print a message at the same time. More efficient, these modified codes are also easier to modify: To adjust the contents of the output message, you only need to modify one instead of the three print statement. Note: Python code for the United States, a function of the less the better, try to be concise, avoid repetitive work, put the repetitive work to the last module, so in the work, when encountering repetitive blocks of code, to try to optimize the code, try to make the function of the code is the best. 5.3.4 use more than one elif block of code to use as many elif blocks as needed, for example, assuming that the aforementioned playgrounds offer discounts to seniors, add a conditional test to determine if the customer is eligible for the discount. It is assumed that for older people aged 65 or older, tickets can be purchased at half-Price ($ 5): 
def your_age (age): if-< 4:price = 0 Elif Age >= 4 and age < 18:price = 5 Elif Age < 6 5:price = Elif Age >= 65:price = 5 print ("Your admission cost are $" + str (price) + ".") #我在考虑, how the result lets the user input the name, in the programming, we programmer certainly knew how to call the function, but the user did not know Your_age (your_age) your_age (2) #年龄的问题可以结果, we directly redefine an age variable , let the user input, but how to solve the problem of automatic calling function, it is impossible for the user to call the function my_age = Int (input ("Your Age:")) Your_age (My_age) The code is mostly unchanged. The second elif code block passes the check to determine that the ticket price is set to a unanimous price of $10, after the age of 65 years. Note that in the Else code block, the assigned value must be changed to 5, because this block of code executes only if the age exceeds 65 (inclusive). 5.3.5 omitting the Else code block Python does not require that the IF-ELIF structure must have an else code block behind it. In some cases, the else code block is useful, while in other cases it is clearer to use a elif statement to handle a particular situation: the ELIF code block is set to $5 when the customer's age exceeds 65 (inclusive), which is clearer with the else block.    After such a modification, each block of code is executed only when the corresponding test is passed. Else is an all-encompassing statement where the code executes, as long as the condition tests in any if or elif are not met, which may introduce invalid or even malicious data. If you know the final condition to test, you should consider using a ELIF code block instead of else. In this way, we can be sure that our code executes only when the appropriate conditions are met. 5.3.6 testing multiple conditions The IF-ELIF-ELSE structure is powerful, but only suitable for situations where only one condition is met: After passing the test, Python skips the rest of the tests.    This behavior is good and efficient, allowing us to test a specific condition. However, it is sometimes necessary to check all the conditions we care about. In this situationcase, you should use a series of simple if statements that do not contain elif and else code blocks. It is possible to use this method when there are multiple conditions that are true and we need to take appropriate action when each condition is true. toppings.py
requested_toppings = [' mushrooms ', ' extra cheese ']if ' mushrooms ' in requested_ Toppings:print ("Adding mushrooms.") If ' pepperoni ' in Requested_toppings:print ("Adding pepperoni") if ' extra cheese ' in Requested_toppings:print ("Adding    Extra cheese ") print (' \nfinished making your pizza! ') We first created a list that contains the ingredients for the customer's point. The If statement checks whether the customer has ordered the ingredients mushroom (' mushrooms '). If you click, print a confirmation message. Check the ingredient wax sausage (' pepperoni '), this program will carry out the next test regardless of whether the previous test passed.    Each time the program runs, these three independent tests are performed. In this example, each condition is checked, so mushrooms are added to the pizza and extra cheese: Adding mushrooms.    Adding extra cheesefinished Making your pizza! If you switch to using the IF-ELIF-ELSE structure as follows, the code will not run correctly, because once a test passes, the rest of the tests are skipped: 
requested_toppings = [' mushrooms ', ' extra cheese ']if ' mushrooms ' in requested_ Toppings:print ("Adding mushrooms.") Elif ' Pepperoni ' in Requested_toppings:print ("Adding pepperoni") elif ' extra cheese ' in Requested_toppings:print ("    Adding extra Cheese ") print (' \nfinished making your pizza! ') The first Test check list contains ' mushrooms ', which passes, so mushrooms will be added to the pizza. However, Python skips the rest of the tests in the IF-ELIF-ELSE structure and does not include ' extra cheese ' and ' pepperoni ' in the check list. As a result, the first ingredient of the customer point is added, but no additional ingredients are added: Adding Mushrooms.    Finished making your pizza! In short, if we want only one block of code, use the IF-ELIF-ELSE structure, and if you want to run multiple blocks of code, use a series of separate if statements.  Try it 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 = Ten print ("You get" + str (score) + "Score.") 
5.4  using the IF statement to work with lists by using the IF statement and the list, you can accomplish some interesting tasks: special handling of specific values in a list, efficient management of changing situations, such as whether a restaurant has specific ingredients, and proving that the code works as expected in a variety of situations. 5.4.1  checking special elements at the beginning of this chapter demonstrates how to handle the special value ' BMW ' by a simple example-it needs to be printed in a different format. Now that we have a general understanding of conditional tests and if statements, here's a closer look at how to check the special values in the list and handle them appropriately.    continue using the previous pizza shop example. This pizza shop prints a message for each ingredient you add when making a pizza. By creating a list that contains the ingredients for the customer point and using a loop to point out the ingredients added to the pizza, you can write the code in a very efficient way:
requested_toppings = [' mushrooms ', ' extra cheese ', ' pepperoni ']for requested_topping in requested_toppings:    print ( "Adding" + requested_topping + '. ') Print ("\nfinished Making your pizza.") The output is simple because the code above is just a simple for loop: Adding mushrooms. Adding extra cheese. Adding Pepperoni. Finished making your pizza.    However, what should I do if we run out of green pepper at the pizzeria? To properly handle this situation, you can include an if statement in the For loop:
requested_toppings = [' mushrooms ', ' extra cheese ', ' pepperoni ']for requested_ Topping in requested_toppings: #加入if条件进行判断, if the pepperoni is finished, tell the user that it has run out if requested_topping = = ' Pepperoni ': pri    NT ("Sorry, we are out of pepperoni right now.") Else:print ("Adding" + requested_topping + '. ')    Print ("\nfinished Making your pizza.") This is checked before adding each ingredient to the pizza. The code checks whether the customer point is green pepper, if so, displays a message stating that the cause of the green pepper cannot be ordered.    The Else code block ensures that other ingredients are added to the pizza. The output shows that each of the ingredients of the customer's point is properly processed: 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 has been made for each list that is processed, assuming that they all contain at least one element. We are going to let the user provide the information stored in the list, so we can no longer assume that the loop run-time list is not empty.    For this reason, it is important to determine whether the list is empty before running the for loop. Check that the list of ingredients for the customer point is empty before making pizza. If the list is empty, confirm to the customer whether she has a regular pizza or not; If the list is not empty, make the pizza as in the previous example: 
requested_toppings = [] #判断列表是否是空的, if it is empty without judgment, there will be an error, so you have to determine in advance whether the list is empty list if            Requested_toppings:for requested_topping in requested_toppings:if requested_topping = = ' Pepperoni ':        Print ("Sorry, we are out of pepperoni right now.")    Else:print ("Adding" + requested_topping + '. ') Print ("\nfinished Making your pizza.")    Else:print ("is sure you want a plain pizza?") Here, we first create an empty list that contains no ingredients. The first if statement performs a simple check instead of executing the for loop directly. When a list name is used in a conditional expression in an If statement, Python returns true in the list with at least one element, and False if the list is empty.    If requested_toppings is not empty, run the same for loop as the previous example, or print a message asking the customer if they really want a regular pizza without any toppings.    Here, the list is empty, so the output is as follows-ask the customer if they really want a regular pizza: is you sure want a plain pizza? If this list is not empty, the output of the various ingredients added in the pizza will be displayed. 5.4.3 The requirements for using multiple list customers are often varied, especially in the case of pizza ingredients. What if the customer wants to add French fries to the pizza?    You can use lists and if statements to determine whether a customer's requirements are met. Take a look at how to reject the weird ingredient requirements before making pizza. The following example defines two lists, where the first list contains the toppings supplied by the pizzeria, while the second list contains the ingredients for the customer's point. This time for each element in requested_toppings, check whether it is a pizzeria-supplied ingredient, and decide whether to add it in Pisa: 
available_toppings = [' mushrooms ', ' olives ', ' green peppers ', ' pepperoni ', ' Pineapple ', ' extra cheese ']requested_toppings = [' mushrooms ', ' French fries ', ' extra cheese ']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 shop to provide a list of ingredients. Please note that if the toppings supplied by the pizzeria are fixed, you can also use a tuple to store them. Next, we have defined a list that contains the ingredients for the customer point, please note that unusual ingredient-' french fries '. Then we traverse the list of ingredients in the customer's point. In this cycle, for each ingredient in the customer's point, we check to see if it is included in the supplied ingredient. If the answer is yes, add it to the pizza, or you will run the false block: Print a message telling the customer not to supply this ingredient the output of these codes is neat and informative: Adding Mushrooms. Sorry, we don ' t have French fries. Adding extra cheese. Finished making your pizza. Give it a try. 5-8 in a special way to greet the administrator: the subject of the use of the For loop and if statement, when the user log on the site, according to the nature of the user to Judge 
Login_users = [' admin ', ' zhangxx ', ' loujq ', ' Xiaoaj ', ' Liuxs ']for login_user in login_users:    if Login_user = = ' Admin ':        print ("Hello admin,would what do I see a status report?")    else:        print ("Hello Eric,thank logging in again.") 5-9  Handling No user situation: The first thing to determine whether the user list is empty, if it is empty, what to do, if not empty, then do another operation:
Login_users = [] #判断列表是否为空, if NULL, executes an empty corresponding statement if login_users: for    login_user in login_users:        if Login_user = = ' admin ' :            print ("Hello admin,would what do I see a status report?")        else:            print ("Hello Eric,thank logging in again.") else:    print ("We need to find some users!") 5-10 Checking user names
current_users = [' admin ', ' zqq ', ' lXs ', ' ljq ', ' DLs ', ' GW ', ' sC ']new_users = [' Gcx '    , ' Zmz ', ' lxs ', ' gjz ', ' sc ']transfor_current_users = [] #进行列表转换, convert the user name to lowercase to ensure the uniqueness of the username for the 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 user name.") Else:print ("This user name was not used.") 5-11 ordinal the way to the list, the method, then the use of If-elif-else, and the for loop traversal of the list of attributes, you know, for loop is to iterate through the list of each element, starting from the first element of the list to traverse, run the entire program. 
ordinal_numbers = List (range (1,10)) 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 format if statement each example in this chapter shows good formatting habits.    In terms of formatting for conditional tests, the only advice that PEP 8 provides is to add a space on each side of the comparison operator, such as ==,>= and <=, for example, if age < 4, or if age <4: OK. Such whitespace does not affect Python's interpretation of the code, but rather makes it easier to read the code. 
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.