Python program development -- Chapter 2 conditional statements

preface

This chapter mainly introduces conditional statements in Python: if statements and nesting of if statements, for loops, while loops, break statements, continue statements, etc.

1, if statement

Generate branches through if statements, and perform different operations (True or False) through the defined conditional results. The common greater than less than or less than or equal to in if statements is the same as in general. Here, it should be noted that equal is expressed as "= =", and not equal is expressed as "= ", followed by the object to be compared.

(1) Single branch

The single branch of an IF statement refers to a conditional statement with only the if keyword. It can be understood that if it is correct, the code will be executed.
The following Python code:

x = float(input("Please enter a number:"))
if x < 0:
    print(f"{x}Less than 0")
    

The operation results are as follows:
When we enter a number greater than 0, it does not display:

When we enter a number less than 0:

(2) Double branch

Double branch if statements can be generated through if... else statements. As follows, when the conditional expression is correct, execute code block 1, and when the conditional expression is wrong, execute code block 2.

if Conditional expression:
	Code block 1
else:
	Code block 2

The following is a double branch judgment program with the following Python code:

account = input("Please enter account number:")
password = input("Please input a password:")
print("Please confirm the account and password you entered again!")
print("Your account number is:", account, end="")
print("Your password is:", password)
print("Please wait...")
if account == "admin" and password == "123456":
    print("Administrator login succeeded")
else:
    print("Login failed!")
    

The operation results are as follows:

And is used here, which means that login can be successful only when the account and password are specific values. It also has or, which means or,

(3) Multi branch

Multi branch if... elif... Else statements can handle a variety of situations. When the value of conditional expression 1 is correct, execute code block 1, otherwise execute conditional expression 2. If conditional expression 2 is correct, execute code block 2, otherwise execute conditional expression 3. Go on in sequence. If the conditional expressions in front of else statements are all wrong, execute code block n, the format is as follows:

if Conditional expression 1:
	Code block 1
elif Conditional expression 2:
	Code block 2
elif Conditional expression 3:
	Code block 3
elif Conditional expression n-1:
	Code block n-1
...
else:
	Code block n

The following Python code will have different output results when the input is less than 0, greater than 0 or equal to 0:

x = float(input("Please enter a number:"))
if x < 0:
    print("The number is less than 0")
elif x > 0:
    print("The number is greater than 0")
else:
    print("The number is equal to 0")
    

The operation results are as follows:
When the input number is greater than 0:

When the input number is less than 0:

When the input number is equal to 0:

The following Python program will be evaluated automatically when the student's grade is entered:

x = float(input("Please enter the student's grade:"))
if 60 <= x <= 70:
    print("Pass!")
elif 80 <= x <= 90:
    print("good")
elif 90 <= x <= 100:
    print("Excellent!")
else:
    print("fail,")

The operation results are as follows:

(4) Nesting of if statements

If statements can be nested at multiple levels. Nesting means that if statements are included in if statements, and nesting is represented by indentation. The if statements here include the above three branches.
For example, in the following example, the program first judges the result of conditional expression 1. If it is correct, it executes code block 1. At this time, it judges the nested if statement (conditional expression 2). If it is correct, it executes code block 2:

if Conditional expression 1:
	Code block 1
	if Conditional expression 2
		Code block 2
		

2, for loop

The for loop can traverse iteratable objects, such as lists, strings, tuples, dictionaries, or collections, and the number of loops in the for loop can be controlled through the range() function.

(1) Definition of for loop

The format of the for loop is as follows. Whenever the for statement executes a loop, its temporary variable will be assigned as a sequence element read from the iteratable object:

for Temporary variable in Iteratable object:
    Code block

The following Python code traverses and outputs each character of the string through the for statement, the temporary variable is x, and the iteratable object is the number string, and then traverses and outputs the value of the temporary variable:

number = "12345"
for x in number:
    print(x)

The operation results are as follows:

(2) range() function

The range() function can be used to generate a sequence of numbers for traversal, or the number of loop executions can be controlled by this function.
The following Python code outputs the contents of the for statement three times:

for x in range(3):
    print("HELLO WORLD!")

The operation results are as follows:

The following Python code generates a sequence of numbers through the range() function, which can also be expressed in intervals or steps:

n1 = "abcdef"
for x in range(3, 6):
    print(x)
print("\t")
n2 = "123456"
for y in range(3):
    print(y)
print("\t")
n3 = "ABCDEF"
for z in range(1, 5, 2):
    print(z)

The operation results are as follows:

3, while loop

The format of the while loop is as follows. If the conditional expression is correct, the code block will be executed repeatedly until it exits when the expression is wrong, and the code block in the loop will no longer be executed:

while Conditional expression:
	Code block
	

The following Python calculates the value of 1 + 2 +... + 100 through the while loop:

i = 1
sum = 0
while i <= 100:
    sum = i + sum
    i = i + 1
print("1+2+...+100 The value of is:", sum)

The operation results are as follows:

You can infinite loop by setting while==1. The following Python code can exit the loop by ctrl+c:

sum = 0
y = 1
while y == 1:
    x = int(input("Enter number:"))
    x = x + 1
    sum = x + sum
    print("The current results are:", sum)

The operation results are as follows:

In addition, both for loops and while can be nested by indentation.

4, break statement and continue statement

There are two jump statements in Python. They can only be used in a loop and cannot be used alone. The break statement means to jump out of the whole loop and the continue statement means to jump out of the current loop.
In the following Python code, use the continue statement to set that when the input number i is less than 0, it will jump out of this cycle and will not be added to the sum calculation:

sum = 0
y = 1
while y == 1:
    x = int(input("Enter number:"))
    x = x + 1
    if x < 0:
        continue
    sum = x + sum
    print("The current results are:", sum)

The operation results are as follows:

In the following Python code, set the break statement to jump out of the whole loop and output the result when the input number i is less than 0:

sum = 0
y = 1
while y == 1:
    x = int(input("Enter number:"))
    x = x + 1
    if x < 0:
        break
    sum = x + sum
print("The result is:", sum)

The operation results are as follows:

Keywords: Python Pycharm

Added by alfmarius on Mon, 20 Sep 2021 21:42:33 +0300