Python -- loop branch structure

Posted by Meissa on Thu, 13 Jan 2022 04:18:29 +0100

As a python beginner, I want to write a blog to record my growth process and share what I have learned. The following are some superficial views and personal understanding of Python language by a python beginner.

#while loop
'''
The syntax format of the while loop is as follows:
while conditional expression
Loop body statement
'''

#Exercise one
#Use the while loop to print numbers from 0 to 10

num = 0
while num<=10:
    print(num)
    num+=1

#Exercise 2
#Use the while loop to calculate the cumulative sum of numbers between 1-100; Calculate the even cumulative sum between 1-100 and the odd cumulative sum between 1-100

num = 0
sum_all = 0
sum_even = 0
sum_odd = 0
while num<=100:
    sum_all += num
    if num % 2 == 0:
        sum_even  += num
    else:
        sum_odd += num
    num += 1
print("1-100 Sum of all numbers",sum_all)
print("1-100 Cumulative sum of all even numbers",sum_even)
print("1-100 Sum of all odd numbers",sum_odd)

#for loop and traversal of iteratable objects
'''
The for loop is usually used for traversal of iteratable objects. The syntax format of the for loop is as follows:
for variable in iteratable object
Loop body statement
'''

#Traverse a tuple or list

for x in (20,30,40):
    print(x*3)

#Traversing characters in a string

for x in "ayg002":
    print(x)

#Traversal dictionary

d = {'name':'haha',"age":18,'job':'student'}
for x in d:  #Traverse all key s
    print(x)
for x in d.keys():  #Traverse all key s
    print(x)
for x in d.values():  #Traverse all value s
    print(x)
for x in d.items():  #Traverse all key value pairs
    print(x)

#Use the for loop to calculate the cumulative sum of numbers between 1-100; Calculate the even cumulative sum between 1-100 and the odd cumulative sum between 1-100

sum_all = 0
sum_even = 0
sum_odd = 0
for num in range(101):
    sum_all += num
    if num % 2 == 0:
        sum_even += num
    else:
        sum_odd += num
print("1-100 Sum of all numbers",sum_all)
print("1-100 Cumulative sum of all even numbers",sum_even)
print("1-100 Sum of all odd numbers",sum_odd)

#Exercise one
'''
Print
0 0 0 0 0
1 1 1 1 1
2 2 2 2 2
3 3 3 3 3
4 4 4 4 4
'''

for x in range(5):
    for y in range(5):
        print(x,end='\t')
    print()

#Exercise 2
'''
Print 99 multiplication table
11=1
21=2 22=4
31=3 32=6 33=9
41=4 42=8 43=12 44=16
51=5 52=10 53=15 54=20 55=25
61=6 62=12 63=18 64=24 65=30 66=36
71=7 72=14 73=21 74=28 75=35 76=42 77=49
81=8 82=16 83=24 84=32 85=40 86=48 87=56 88=64
91=9 92=18 93=27 94=36 95=45 96=54 97=63 98=72 9*9=81
'''
f

or m in range(1,10):
    for n in range(1,m+1):
        print("{0}*{1}={2}".format(m,n,(m*n)),end="\t")
    print()

#Exercise three
#Use lists and dictionaries to store table data

r1 = dict(name="petty thief",age=18,salary=50000,city="Nanjing")
r2 = dict(name="Xiao Liu",age=18,salary=50000,city="Nanjing")
r3 = dict(name="Xiao Wang",age=20,salary=10000,city="Beijing")

tb = [r1,r2,r3]
for x in tb:
    if x.get("salary")>15000:
        print(x)

#break statement
#Break statements can be used in while and for loops to end the entire loop. When there are nested loops, the break statement can only jump out of the nearest loop

while True:
    a = input("Please enter a character(input Q or q end)")
    if a == 'Q' or a == 'q':
        print("End of cycle, exit")
        break
    else:
        print(a)

#continue statement
#The continue statement is used to end this loop and continue the next time. When multiple loops are nested, continue is applied to the nearest loop
#It is required to enter the employee's salary. If the salary is less than 0, re-enter it. Finally, print out the number and salary details of the entered employees, as well as the average salary

empNum = 0
salarySum = 0
salarys = []
while True:
    s = input("Please enter employee's salary(Press Q or q end)")
    if s.upper() == 'Q':
        print("After entry, exit")
        break
    if float(s)<0:
        continue
    empNum += 1
    salarys.append(float(s))
    salarySum += float(s)
print("Number of employees{0}".format(empNum))
print("Enter salary:",salarys)
print("Average salary{0}".format(salarySum/empNum))

#else statement
'''
While and for loops can be accompanied by an else statement (optional). If the for and while statements are not ended by the break statement, the else statement will be executed, otherwise it will not be executed. The syntax format is as follows:
while conditional expression:
Circulatory body
else:
Statement block
perhaps
for variable in iteratable object:
Circulatory body
else:
Statement block
'''
#There are 4 employees in total. Enter the salary of these 4 employees. After all are entered, you will be prompted "you have entered the salary of all 4 employees". Finally, print out the entered salary and average salary

salarySum = 0
salarys = []
for i in range(4):
    s = input("Please enter the salary of a total of 4 employees(Press Q or q Midway end)")
    if s.upper() == 'Q':
        print("After entry, exit")
        break
    if float(s)<0:
        continue
    salarys.append(float(s))
    salarySum += float(s)
else:
    print("You have entered the salary of all 4 employees")
print("Enter salary:",salarys)
print("Average salary{0}".format(salarySum/4))

#Loop code optimization
'''
1. Minimize unnecessary calculations inside the cycle
2. In the nested loop, the calculation of the inner loop shall be reduced as much as possible and lifted outward as much as possible
3. Local variable query is fast. Try to use local variables
'''

import time
start = time.time()
for i in range(1000):
    result = []
    for m in range(10000):
        result.append(i*1000+m*100)
end = time.time()
print("Time consuming:{0}".format(end-start))

start2 = time.time()
for i in range(1000):
    result = []
    c = i*1000
    for m in range(10000):
        result.append(c+m*100)
end2 = time.time()
print("Time consuming:{0}".format(end2-start2))

Topics: Python Back-end