Process control in python

Posted by alexinjamestown on Fri, 03 Jan 2020 15:46:23 +0100

for statement

The for statement in python iterates according to the subitems in any sequence (linked list or string) according to their order in the sequence

In python, if you modify the iteration sequence during the iteration, it is not safe (only when you use a variable sequence such as a linked list)

We can iterate over its copy and then modify its data

as

words=["liu","ming","zhe"]
for w in words[:]:
    if w=="liu":
        words.insert(0,w)
print(words)

Use the for loop to get a list, which is the iteration sequence of the for loop

# This sentence uses x as the element of the list, and the value of x is obtained from the for loop
list1=[x for x in range(10)]

print(list1)

 

range() function

range(10) is to generate a list of ten values

Different aspects range() The object returned by the function appears to be a list, but in fact it is not. When you iterate over it, it's an object that can return consecutive items as expected; but to save space, it doesn't really construct lists.

# Use range to get a list of steps from 1 to 2 and to 10
print(list(range(1,10,2))

To get the iterative index, we can use range() and len()

a=["A flower","A Qiang","Amin","A third","AI Shuai"]
# Get iteration sequence
i=0
for x in range(len(a)):
    print(i,x)
    i+=1

A simpler way is to use enumerate()

a=["A flower","A Qiang","Amin","A third","AI Shuai"]
# The return value of enumerate is not a list but an iterative object. We need to use the list method to convert it into a list
print(list(enumerate(a,1)))

break, continue and else in loop

for i in range(10):
    if i==5:
        print("About to jump out of the loop")
   # If there is no break, the else statement is executed after the loop ends
        break
    if i==2:
        print("")
        continue
    print('This is{0}'.format(i))
else:
    print("Loop execution complete")

function

def fib(num):
    a=0
    b=1
    list1=[]
    for i in range(num):
        list1.append(a)
# append is fast. We recommend using it when adding data to linked list
        c=b
        b=a+b
        a=c
    return list1

        

Drill down function definition

  1. Default parameter values,
# This function can be called with ask UK OK ("haha") or ask UK OK ("Y, 2) or ask UK OK (" Y, 5, "hello")
def ask_ok(ask,time=4,replay="what you say?"):
    for i in range(4):
        if ask==None:
            ask=input("Please speak:")
        if ask=='y':
            print("yes")
            break
        ask=Null



# The default value is resolved in the function definition scope
i =5
def func(arg=i):
    print(arg)

i=6
func()# Output is 5.

# The default value is parsed only once when the function is defined, and will not be taken every time when the function is called

def func(a,arg=[]):
    arg.apprend(a)
    print(arg)

func(1)# Output [1]
func(2)# Output [1,2]
func(3)# Output [1,2,3]



    

 

Topics: Python