Python [day 2] control structure

General description

Process: the order in which the computer executes code
Process control: effectively manage the execution sequence of computer code. Only process control can realize the business logic in development
Conditional expression: comparison operator / logical operator / compound operator
Classification of process control:
1. Sequential process: code is a top-down execution structure, which is also the default process of Python
2. Select process / branch process: a structure that selectively executes the corresponding logic according to the judgment at a certain step

  • Single branch
			if Conditional expression:
   				One by one Python code
    			......
  • Double branch
 			if Conditional expression:
    			One by one Python code
    			......
			else: 
    			One by one Python code
    			......
  • Multi branch
            if Conditional expression:
                One by one Python code
                ......
            elif Conditional expression:
                One by one Python code
                ......
            elif Conditional expression:
                One by one Python code
            	......
            else: 
                One by one Python code
                ......
  1. Loop flow: the logic (thing) that repeatedly executes a piece of code under certain conditions
        while Conditional expression:
                One by one Python code
                ......
        for... in Iteratable collection object:
                One by one Python code
                ......
Classification of cycles:
while Basic grammatical structure of loop
while Conditional expression:
	Code instruction
 Grammatical features:
	1.There is an initial value
	2.Conditional expression
	3.The counting variable in the loop must be self increasing or self decreasing
 Service conditions:
	The number of cycles is uncertain and ends depending on the cycle conditions
 Purpose:
	In order to simplify the operation table of similar or the same code, the code can be reused

Selection process

  • Single branch`
score = int(input("For single branch detection, please enter the score:"))
if score < 60:
    print("The results are not ideal, we should continue to refuel!")
    pass #Empty statement
  • Double branch
score = int(input("Double branch detection, please enter the score:"))
if score < 60:
    print("The results are not ideal, we should continue to refuel!")
    pass #Empty statement
else:
    print("Good results, keep up your efforts~")
    pass #Empty statement
  • Multi branch
score = int(input("For multi branch detection, please enter the score:"))
if score < 60:
    print("The results are not ideal. Come on!")
    pass #Empty statement
elif score<75:
    print("Qualified, keep working hard~")
    pass #Empty statement
elif score<85:
    print("Good grades, keep up~")
    pass #Empty statement
else:
    print("Excellent results, great duck~")
    pass #Empty statement

Circulation process

  • while loop
i = 0
while i<=100:
    print(i)
    i+=1
    pass
  • for loop

for loop
Syntax features: traversal operation, take each value in the collection container in turn
Usage condition: the known number of circular words can be iterated through the object
for temporary variable in container:
Execute code block
pass

tags = 'I am a Chinese'#The string type itself is a collection of character types
for item in tags:
    print(item,end='')
    pass 

range this function generates a list of data sets
Range (start, end, step) step cannot be 0

print(type(range(1,100)))
for i in range(1,101,1):
    print(i,end=' ')
    pass

1-100 cumulative sum

sum = 0
for i in range(1,101): #range(start,end):start includes and end does not
    sum +=i
    pass
print("1-100 The cumulative sum of is:%d"%(sum),end = '')

1-100 even items

for data in range(1,101):
    if data%2==0:
        print(data,end = ' ')
        pass
    pass
  • Use of break

break interrupt ends the loop of this layer directly if the conditions are met
Continue ends this cycle and continues the next cycle (when the continue condition is met, the remaining statements in this cycle will not be executed, and the subsequent cycles will continue)
These two and keywords can only be used in loops

sum = 0
for item in range(1,50):
    if sum > 100:
        break #Exit loop
        pass
    sum += item
    pass
print("Co circulation%d Times, the last cumulative sum is%d"%(item,sum))
for i in 'I love you':
    # if i == 'e':
    #     break #Complete interruption
    if i == ' ':
        continue #Interrupt this cycle
    print(i,end='')
    pass
  • Use of continue
for item in range(1,101):
    if item%2 == 0:
        continue
    print(item,end = ' ')
    pass
  • for else statement
for item in range(1,11):
    print(item,end=' ')
    if item >= 5:
        break
    pass
else:
    print("In the upper loop break that else Your code will no longer execute")
account = 'xyz'
pwd = '123'
for i in range (3):
    zh = input("Please enter your account number:")
    mm = input("Please enter your password:")
    if zh == account and mm == pwd:
        print("Login successful~")
        break
    pass
else:
    print("Your account has been locked by the system!!")
  • while -- else statement
index = 1
while index <= 10:
    print(index,end=' ')
    if index == 6:
        break
    index +=1
    pass
else:
    print("else Already implemented")

Case (guess age)

1. Allow users to try up to three times
2. After every three attempts, if you haven't guessed correctly, ask the user if it's OK to continue playing. If you answer y or Y, let him guess three times, and so on
3. If you guessed right, just quit

times = 1
while times <= 3:
    x = 'x'
    times += 1
    age = int (input("Please enter the age you want to guess:"))
    if age == 25:
        print("You're great, you guessed right!!! game over")
        break
    elif age > 25:
        print("Guess your age. Please try again~")
        pass
    else:
        print("Guess small, try again!")
        pass
    if times == 4 :
        while 'y' != x and 'Y' != x and 'n' != x and 'N' != x:
            x = input("Continue[Y/y:continue;N/n:sign out]:")
            if 'y' == x or 'Y' == x:
                times = 1
                pass
            elif 'n' == x or 'N' == x:
                print("game over!")
                pass
            else:
                print("Please enter the correct mark, thank you for your cooperation!")
    pass

Tags: Python Visual Studio Code

Posted by dreamdelerium on Sun, 25 Jul 2021 08:49:16 +0930