0. Learning objectives
Python is concise, easy to learn, object-oriented programming language. Not only does it have powerful native data types, but it also provides easy-to-use control statements. In the Python Basics Tutorial series of blog posts, we've covered the built-in native data types in Python, and we've also learned how programs can interact with the user using input and output statements. The main goal of this section is to introduce Python's control statements and lay the groundwork for what's to come. This article will provide a complete introduction to the Python fundamentals and basic ideas needed to learn about data structures and algorithms, as well as the corresponding real-world examples and explanations.
- Understanding and mastering Python's conditional and looping statements
- Mastering Complex Nesting of Conditional and Loop Statements and List Parsing in Python
1. Code blocks and indentation
A code block is a set of statements. The syntax used to define a code block in Python is the same for all control structures, and can be used to execute code when a condition is met (an if statement), to execute code multiple times (loops), and so on. Code blocks are created by indenting the code (either with spaces or tabs). In Python, a colon (:) is used to indicate that a block of code is to follow, and the indentation (typically 4 spaces per level) must be the same for all lines of code within the same block:
if condition is True: print('this is a block') print('another line of this block') print('escaped the previous block')
The same principle of code blocks applies when specifying function bodies and class bodies.
2. Conditional statements
The above example statements are executed line by line, but in practice having the program choose to execute specific blocks of statements is a must. This is where the Boolean type comes in handy.
When used as Boolean expressions, the standard values False and None, the value 0, and empty sequences (such as empty strings, empty tuples, empty dictionaries, and so on) are treated as false, while all other values are treated as true. This means that any Python value can be interpreted as true, but True and False are standard truth values. In C, the standard truth values are 0 (for false) and 1 (for true). In fact, True and False are aliases for 0 and 1, which serve exactly the same purpose:
>>> bool('') False >>> bool([0]) True >>> bool('Hello world') True >>> True == 1 True >>> True + 2 3
When the program is running, thePython will automatically convert any value to a boolean if needed, without having to explicitly do so:
# test_bool.py string_test = 'Hello world' if string_test: print('Automatic conversion ')
The result of the above script execution is as follows, indicating thatPython An automatic conversion was performed:
Automatic conversion
It is important to note that although the values may be equal when converted to truth values, for examplebool({}) == bool([]) == False
, but by themselves they are not equal, i.e., the{} != []
:
>>> bool({}) == bool([]) True >>> {} == [] False
2.1 If Statements
Conditional statements (also known as if statements) are able to conditionally execute code, executing subsequent blocks of code if the condition (the expression between the if and the colon) is true, or not executing if the condition is false:
if flag == True: flag = False print(flag)
The if statement shown above is also known as a one-way branching structure.If the flag is True, change it to False and print the flag value. There is another type of conditional structure called a binary branch (also known as an if.... .else statement):
answer = input('Please enter your answer: ') if answer == 'A': print('Right!') else: print('Error!')
In the above example, Python checks the user input answer and prints "Right!" if the input is A. Otherwise, it performs an else branch to print "Error!".
To check for multiple conditions, use elif, which stands for else if and can be thought of as an else clause containing a condition:
num = int(input('Please enter a number: ')) if num > 0: print('The number is positive') elif num < 0: print('The number is negative') else: print('The number is zero')
Note that when using elif, the final else is required to provide a default branch if all branching conditions are not met.
The above three conditional structures can be represented by the following flowchart:
In summary, we can summarize the most general form of a conditional statement in Python:
if first_condition: first_block elif second_condition: second_block elif third_condition: third_block else: fourth_block
Each condition is a Boolean expression, and each code block contains one or more statements to be executed if the condition is satisfied. If the first condition is true, the first block of code is executed without evaluating the other conditions. If the first condition fails, the second condition is evaluated, and so on. if statements can contain any number of elif clauses (or zero), with the last else clause being optional.
2.2 Nesting if Statements
The conditional structure supports nesting, i.e. calling any number of if statements within an if statement:
if alcohol < 20: print('Does not constitute drinking behavior!') else: if alcohol > 80: print('Already meet drinking and driving standards!') else: print('Has reached the standard for drunk driving!')
The logic expressed in the above program can be represented by a flowchart:
2.3 Assertions
In order for a program to abort when an error condition occurs, Python also provides an if-like keyword: assert, which can be used to require that certain conditions must be met. assert is similar to a checkpoint in that it can be used to terminate a program when it is known that a certain condition must be met for the program to run correctly. This is similar to checking the correctness of an e-mail address when registering for a Web site:
>>> mail_1 = 'test123456789@' >>> assert mail_1.endswith('.com') >>> mail_2 = 'test123456789@' >>> assert mail_2.endswith('.com') Traceback (most recent call last): File "<stdin>", line 1, in <module> AssertionError
To account for the termination of the program, theassert statement followed by a description string:
>>> assert mail_2.endswith('.com'),' Email must end with .com ' Traceback (most recent call last): File "<stdin>", line 1, in <module> AssertionError: Email must end with .com
3. Circulation
We've learned how to execute a block of code when the condition is true (or false), but how do you repeat the operation of a block of code multiple times? For example, print all the even numbers from 1-100. We could certainly write 50 lines of print statements, but if that were the case, we wouldn't need Python.
Python provides two different loop constructs. while loops allow a Boolean condition to be tested repeatedly until the condition can't be satisfied. for loops provide iteration through sequences (e.g., the characters of a string, the elements of a list, or the numbers in a given range, etc.).
3.1 while loops
The while statement repeats the block of code while a given condition is true. For example, in the following example, the variable number is initialized to 0, and it is incremented by 1 for each iteration in the while loop, with each execution of the loop body preceded by a conditional judgment, so that the loop ends when number equals 5:
number = 0 while number < 5: print('A total of {} time(s)'.format(number)) number += 1
The program runs with the following results:
A total of 0 time(s)
A total of 1 time(s)
A total of 2 time(s)
A total of 3 time(s)
A total of 4 time(s)
3.2 for loops
The while statement can be used to execute a block of code repeatedly while the condition is true, but sometimes we may need to execute a block of code for each element in the sequence.
In order to introduce for loops, we first need to understand iterable objects, which are objects that can be traversed using for loops, and for this stage, we can just think of iterable objects as sequences.
The for statement can be used to iterate through each element of a sequence:
fruits = ['apple', 'orange', 'banana', 'lemon'] for fruit in fruits: print(fruit)
for statement will list thefruits is assigned to each value in the variablefruit. The code block is then executed.for A common use of the statement is to iterate a finite number of times over a range of values.
We have already briefly introduced the built-in function range for creating ranges when we introduced the datatype list. range is syntactically similar to a slice, containing a start position but not an end position. In fact, if only one position is provided, it will be treated as the end position, and the start position will be 0. The range function can also be given a step parameter, which extracts an element every other element in the range:
for i in range(0, 10, 2): print('The square of {} equals {}'.format(i, i**2))
The output of the program is as follows:
The square of 0 equals 0
The square of 2 equals 4
The square of 4 equals 16
The square of 6 equals 36
The square of 8 equals 64
utilizationfor Loops can also traverse dictionaries, by default, the keys of the dictionary, if you need to traverse all values or key-value pairs, you need to use theto the values and items methods of the dictionary:
fruits = {'apple': 5.0, 'orange': 3.5, 'banana': 4.0} for k in fruits: print(k, 'corresponds to', fruits[k])
The code shown above is equivalent:
fruits = {'apple': 5.0, 'orange': 3.5, 'banana': 4.0} for k, v in (): print(k, 'corresponds to', v)
3.3 Interrupting the loop
Normally, a loop executes blocks of code over and over until the condition is false or until it has iterated over all the elements in the sequence. But sometimes, we may need to start a new iteration (jump to the beginning of the next iteration and not end the loop) or just end the loop.
🔍 break
To end the loop, you can use break, assuming you want to find the largest three-digit daffodil number (the sum of the powers of three of each digit equals its own three-digit number), you can start at 999 and iterate downward, and when you find a daffodil number, you don't need to continue iterating, you just jump out of the loop:
for i in range(999, 99, -1): b = i % 10 t = (i // 10) % 10 h = i // 100 if b ** 3 + t ** 3 + h ** 3 == i: print(i) break
Running this program will end after 407 is printed, as can be seen in the above example through theBy setting the step size of the range to a negative number, the range iterates in reverse.
A regular while loop will make a judgment at the beginning of the loop to end the loop, but sometimes we want the loop to end in the loop body, then we need to use while True/break syntax, use while True to make the loop never end, and then use if statement inside the loop body, and call break to end the loop when the condition of the if statement is satisfied. For example, in the login screen, the user can only proceed to the next step if he/she enters the correct username:
users = ['root', 'admin', 'user_1'] while True: user = input('Please enter your name: ') if user in users: break print('User does not exist!') print('The user name is correct!')
🔍 continue
When the statement continue is specified, it ends the current iteration and skips to the beginning of the next iteration. This basically means skipping the rest of the statements in the loop body, but not ending the loop, for example counting all the daffodils could be written as if the statement continue were used:
for i in range(100, 1000): b = i % 10 t = (i // 10) % 10 h = i // 100 if b ** 3 + t ** 3 + h ** 3 != i: continue print(i)
The output of the program is as follows:
153
370
371
407
4. Comprehensive nesting of control statements
Control statements can be nested in complex syntheses, and you can synthesize the use of control statements by printing a nine-nine multiplication table:
for i in range(1, 10): for j in range(1, 10): if i > j: print('{} * {} = {}'.format(i, j, i*j), end = '\t') elif i == j: print('{} * {} = {}'.format(i, j, i*j)) else: continue
5. List of analytic formulas
List derivation is a way to create a new list from a list. List derivation works like a for loop:
>>> [i**2 for i in range(10)] [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
Nesting is also possible in list derivation, for example by adding moreLots of for loops and if statements:
>>> [[i, j] for i in range(10) for j in range(10) if i % 3 == 0 and j % 4 == 0] [[0, 0], [0, 4], [0, 8], [3, 0], [3, 4], [3, 8], [6, 0], [6, 4], [6, 8], [9, 0], [9, 4], [9, 8]]
Equivalent:
new_list = [] for i in range(10): for j in range(1): if i % 3 == 0 and j % 4 == 0: new_list.append([i, j])
In addition to list derivatives, you can use curly braces to perform dictionary derivatives:
>>> print({i: i**3 for i in range(10)})
{0: 0, 1: 1, 2: 8, 3: 27, 4: 64, 5: 125, 6: 216, 7: 343, 8: 512, 9: 729}
Attention:
1, the cycle also ends with a colon (:)
2. Conditioned on various arithmetic expressions.
a) When true, loop body statement group 1, repeated
b) when false, loop body statement group 2, stop execution
3. If the loop body forgets to accumulate and the conditional judgment is always true, it is a dead loop. The loop body is always practiced.
a) Dead loops are sometimes used to build infinite loops.
b) You can use ctrl+c to abort, or stop the IDE.
summarize
To this point, this article on the Python basic tutorials on the control structure of the article is introduced to this, more related Python control structure content, please search for my previous articles or continue to browse the following related articles I hope you will support me in the future more!