Python basics -- conditional statements and their loops

Conditional statements and their loops

1, Conditional statement

All of the following operators can be used in conditional statements:

  • Arithmetic operators: +, -, *, /, / /,%**
  • Relational operators: >, <, = =, < =, > ==
  • Test operators: in, not in, is, is not
  • Logical operators: and, or, not
  • Bitwise operators: ~, &, |, ^, < <, > >

1.1 single branch selection structure

Syntax:

if expression :
    pass
 	#Code block

Special note: the next step of the program can be carried out only when the "condition" is correct. If the "condition" is false, it will not be executed

if True:
    print('Code 1 for conditional execution')
    print('Code 2 for conditional execution')

#The following code is not indented into the if statement block, so it has nothing to do with the if condition

print('I am the code to execute whether the condition is true or not')

#example
age = input('Please enter your age:')

if int(age) >= 18:
    print('He is an adult and can surf the Internet')

print('System shutdown')

1.2 dual branch selection structure

Syntax:

if expression:
    pass

else:
    pass

When the value of the expression is True, execute statement block 1, otherwise execute statement block 2

age = int(input('Please enter your age:'))

if age >= 18:
    print(f'What is your age{age},He is an adult and can surf the Internet')
else:
    print(f'What is your age{age},Minors, please go home and do your homework by yourself')

print('System shutdown')

python also supports expressions in the following forms. When the value of the expression condition is equivalent to True, the value of the expression is values1, otherwise it is values2. In addition, complex expressions can be used in values1 and values2

values if condition else values2

a=5
print(6) if a>3 else print(5)
6

print(6 if a>3 else 5)
6

b=6 if a>13 else 9
print(b)
9

1.3 multi branch selection structure

Syntax:

if Condition 1:
    Code 1 executed when condition 1 is true
    Code 2 executed when condition 1 is true
    ......
elif Condition 2:
	Code 1 executed when condition 2 is true
    Code 2 executed when condition 2 is true
    ......
......
else:
    None of the above conditions is true. Execute the code

Multiple judgments can also be used with else. Generally, else is placed at the end of the entire if statement to represent the code executed when the above conditions are not true.

example:

age = int(input('Please enter your age:'))
if age < 18:
    print(f'What is your age{age},One for child labor')
elif (age >= 18) and (age <= 60):
    print(f'What is your age{age},Legal length of service')
elif age > 60:
    print(f'What is your age{age},Can retire')
    

    
# You can still write that
age = int(input('Please enter your age:'))
if age < 18:
    print(f'What is your age{age},One for child labor')
elif (age >= 18) and (age <= 60):
    print(f'What is your age{age},Legal length of service')
else:
    print(f'What is your age{age},Can retire')

2, Circular statement

2.1 while cycle

Syntax:

while Conditional expression:
	Circulatory body
# Loop counter note: when you mainly see while, you can see the loop 

while 9 >8 :
    print('What are you looking at ????') 

while True :
    print('What are you looking at ????')	#Use with break described below
    
while 9 < 0  :  #  No loop because the result of the condition is False 
    print('What are you looking at ????')
    

i = 0
while i < 5:
    print('I was wrong')
    i += 1

print('End of task')

2.2 for loop

Syntax:

for variable in Sequence or other iterative objects (generally similar to range()Function combination) :
    Circulatory body

example:

for i in range(5):
	print('I was wrong')
    
    
for i in range(5): 
    print(i)   #It can be seen that there are 5 numbers in total, including 0, 1, 2, 3 and 4, but they are closed on the left and open on the right, starting from 0 by default 
    
    
for i in range(1,5):  # Start from 1 or close left and open right 
    print(i)
    
    
    
for i in range(1,6):
    print(f'I was wrong to say no{i}Times')  
    
# Compared with while, the code is simpler and easier to understand
# Range stands for range, i.e. left closed right open interval
# Pay special attention to the two layers of meaning represented by the for loop (what does i stand for? How many times does it loop?)

Nested for loop

***
***
***

requirement :  Try printing it*

for  j in range(4):
    for i in range(3):
        print("*",end="")
    print()   # It only plays the role of line feed 
    
"""
1: The first thing you see is* First thought of printing print function,And because print The function defaults to line breaking. There is no line breaking here,So sure end parameter=''
2: You can see the printed*There are three conceivable for Cycle three, then think of it right away for i in range(3)Inside print(*)also end = ''
3: Think of the second step as an arrangement,Again for Cycle four times ,And because of the previous print Is to remove line breaks,So print() Just wrap 

"""

# a key: 
- understand***Print order of
- understand print Usage of
- understand for The practical significance of the representative of the cycle
- Understand the execution sequence and logic of the two loops  

for i in range(1,10):
    for j in range(1,10):
        if i>=j:
            print(f'{j}*{i}=',j*i," ",end="")
    print()
#Multiplication formula table

2.3 collocation else

Both the while loop and the for loop can contain else statements. If the loop ends naturally because the expression is not tenable (not because the loop ends because the break statement is executed), the statements in else will be executed; if the loop ends early because the break statement is executed, the statements in else will not be executed.

while Conditional expression:
	Circulatory body
else:
	Code block
	
for variable in Sequence or other iteration object:
	Circulatory body
else:
	Code block

#example    
s=0
for i in range(1,101):
	s+=i
else:
	print(s)
5050

3, Break & continue

break and continue are two different ways to exit a loop when certain conditions are met.

For example: eat a total of 5 apples. After eating the first, eat the second... Is the action of "eating apples" repeated here?

Case 1: if you are full after eating the third apple, you do not need to eat the fourth and fifth apples, that is, the action of eating apples stops. Here is the break control cycle process, that is, terminate the cycle.

Case 2: if you see a big bug when you eat the third one... Do you stop eating the apple and start eating the fourth apple? Here is the continue control loop flow, that is, exit the current loop and then execute the next loop code

3.1 break termination

# break
i = 1
while i <= 5:
    if i == 4:
        print(f'Don't eat when you're full')
        break
    print(f'Eat the second{i}An apple')
    i += 1

print('Jumped out of the loop')
   
# Chestnuts
while True:
    s = input('Enter anything(input quit It's over): ')

    if s == 'quit':
        break

    print(f'The string you entered is{s}')
print('finish')

3.2 continue skip

for i in range(1, 20):
    if i % 2 == 0:
        continue
        # print(1)

    print(i)

# Note: continue will not execute even if there are several lines of code below



num = 0
while num < 10:
    print(num)
    if num == 3:
        num += 1
        continue
    print("&")
    num += 1

Tags: Python Pycharm

Posted on Mon, 11 Oct 2021 14:11:02 -0400 by jmakeig