[basic Python tutorial] program flow control statements in Python

preface

This blog will talk about the flow control statements in Python language. In high school, we have learned program flow problems in mathematics. To achieve a goal, we often need to go step by step from the beginning, sometimes in sequence, sometimes in choice, and sometimes in cycle. Circulation and selection control the whole process. Is it familiar to see the picture below? The sequential structure is executed step by step from top to bottom. I won't say more here. Make fun of the branch statements in the python language.

1, Branch statement

In Python, there are only if... elif... else... Branch statements, but no switch... case... Branch statements. Officials believe that if... else... Can meet the requirements. The function of branch statements is to make a judgment and filter out the data in line with a certain situation. In other words, different things are done in different situations.

# Single branch structure
if 80>70:
    print('Invincible 666')
# Multi branch structure
s=int(input("Please enter your test results:"))
if 100>=s>=90:
    print("Your grades are invincible")
    if s>95:
        print('Your grades are supreme')
    else:
        print('Your grades are below one person and above ten thousand people')
elif 90>s>60:
    print('Your grades are only qualified')
else:
    print('Your grades are not up to standard,Or input is not standard')

# Conditional expression [similar to the ternary operator in C + + language]
print("I was right" if 90>80 else "I was wrong")

# Placeholders and Boolean values of objects
# Each object has a Boolean value, so the object can be directly put into the condition statement as the judgment condition
# python also has only 0 or null, which is false in bool
# Placeholder is when you don't know what to write there, but you really lack a stop position at the statement, and the compiler doesn't report an error pass
ss=int(input("Input object:"))
if ss:
    print('yes')
    pass
elif ss>1:
    print('no')
else:
    pass

2, Circular statement

1. Iteratable object

Before talking about the loop statement, let's talk about what an iteratable object is. An iteratable object returns one element at a time
It mainly includes sequence, file object, iterator object and generator function. An iterator is an object representation
The main feature of an iterative data set is that it includes methods__ iter__ () and__ next__ (), can be realized
Iterative function. A generator is a function that uses a yield statement to produce one value at a time. The range object is an iterator object.
In Python, loop statements are still divided into while and for loops.

2.while loop

while This is followed by cyclic conditions,In the following example i It's a cyclic variable,Exit the loop when the loop variable does not meet the loop conditions
 The following example prints 1-100 And

The code is as follows:

i=1
mysum=0
while i<=100:
   mysum+=i
   i+=1
#    print(mysum)
print(mysum)

3.for loop

for The use of recycling is as follows,Generally used in conjunction with iterator objects.

The code is as follows:

# The for loop calculates the number of daffodils between 100-999

for temp in range(100,1000):
   if temp==(temp%10)**3+(temp//10%10)**3+(temp//100)**3:
      print(temp)
# Iterative print statement
for _ in range(5):
   print('Hello World')


# Use else to realize three times of error reporting of password input error and jump out of the loop when the input is correct

passward=0
for passward in range(3):
   if input('Please enter your password:')!='888888':
      print('Password input error!')
      passward+=1
   else:
      print('The password is correct!')
      break
else:
   print('The password is entered incorrectly multiple times,Auto exit!')

4. 99 multiplication table

# Comprehensive case, nested print 99 multiplication table
for teg in range(1,10):
   temp=1
   while temp<=teg:
      print(str(temp)+'*'+str(teg)+'='+str(teg*temp),end='  ')
      temp+=1
   print()

III Loop control statement

1.break

Jump out of this layer cycle

2.continue

Skip this cycle

3.goto

This statement is not built-in, but it is contained in some third-party libraries
For example, python goto can be used by interested partners.

4.else

This is unique. Python's loop statements support else statements,
That is, you can add an else statement after the loop statement. Else code
The condition that the code in the block is executed is that the loop body is not broken
Take the 99 multiplication table as an example

for teg in range(1,10):
   temp=1
   while temp<=teg:
      print(str(temp)+'*'+str(teg)+'='+str(teg*temp),end='  ')
      temp+=1
   print()
else:
    print("asdholcnnl")

4, Loop related built-in functions

1.enumerate()

This function is used to add an index to the traversable sequence, and the index start value can be specified

s=["Tom","jack","lisa"]
for i,name in enumerate(s,start=1):
    print(f"The first{i}Individual is{name}")

2.zip()

If you need to traverse multiple objects in parallel, you can use this function for packaging. The function of zip is to package multiple iteratable objects into tuples, and then return an iteratable object. If the length of each compressed iteratable object is different, merge according to the shortest length. The * operator can also be used to decompress tuples into lists.
[* zip(x,y)] package X and Y and convert them to list form
zip(*zip(x,y)), if x,y represents a matrix, then zip(*zip(x,y)) is its transpose

for i,j in zip(range(0,10),range(0,10)):
    print(i*j)

3.map()

The map function can pass one function and multiple iteratable lists. If the function passed by the map is None, the map function is the same as the zip function.
If other functions are passed, the function will act on each object. It should be noted that the number of iteratable objects should be the same as that of the function passed in
The number of parameters is consistent.

#Results 1,1,12
list(map(abs,[-1,-1,-12]))
#Results 1 1 4
list(map(pow,range(3),range(3)))

summary

This blog mainly shares the branch statements and circular statements in the process control statements. The operation of branch statements is relatively simple. We mainly master the circular statements, especially several built-in functions in the circular statements, which are commonly used in writing algorithm problems or data analysis.

Keywords: Python

Added by Jeff4507 on Wed, 23 Feb 2022 16:25:29 +0200