Python Basics

1. Circulation structure

A loop structure is used to repeatedly execute one or more statements. If the conditions are met, the statements in the loop body are executed repeatedly. After each execution, it will judge whether the condition is True. If it is True, the statements in the loop body will be executed repeatedly

1.1 while loop

The syntax format of the while loop is as follows:

while Conditional expression:
	Loop body statement

[operation] use the while loop to print numbers from 0 to 10

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

[operation] use the while loop to calculate the cumulative sum of numbers between 1-100; Calculate the cumulative sum of even numbers between 1-100 and odd numbers between 1-100

num = 0
sum_all = 0  #1-100 accumulation of all numbers
sum_even = 0  #Cumulative sum of 1-100 even numbers
sum_odd = 0  #Cumulative sum of 1-100 odd numbers
while num<=100:
	sum_all += num
	if num%2==0:
		sum_even += num
	else:
		sum_odd += num
	num += 1  #Iteration, change the conditional expression to make the loop tend to end
print("1-100 Sum of all numbers",sum_all)
print("1-100 Cumulative sum of even numbers",sum_even)
print("1-100 Cumulative sum of odd numbers",sum_odd)

1.2 for loop and iteratable object traversal

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 objects:
	Loop body statement

[operation] traverse a tuple or list

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

1.3 iteratable objects

Python contains the following iteratable objects:

  1. Sequence. Include: string, list, tuple
  2. Dictionaries
  3. Iterator object (iterator)
  4. Generator function (generator)
  5. File object

[operation] traverse the characters in the string

for x in "sxt001":
	print(x)

[operation] traverse dictionary

d = {'name':'gaoqi','age':18,'address':'Building 001, Xisanqi'}
for x in d: #Traverse all key s in the dictionary
	print(x)
for x in d.keys():#Traverse all key s in the dictionary
	print(x)
for x in d.values():#Traverse all value s in the dictionary
	print(x)
for x in d.items():#Traverse all "key value pairs" in the dictionary 
	print(x)

1.4 range object

The range object is an iterator object used to generate a sequence of numbers in a specified range. The format is:

range(start, end [,step]
for i in range(10)  #Generation sequence: 0 1 2 3 4 5 6 7 8 9
for i in range(3,10)  #Generation sequence: 3 4 5 6 7 8 9
for i in range(3,10,2)  #Generation sequence: 3 5 7 

[operation] use the for loop to calculate the cumulative sum of numbers between 1-100; Calculate the cumulative sum of even numbers between 1-100 and odd numbers between 1-100.

sum_all = 0  #1-100 cumulative sum of all numbers
sum_even = 0  #Cumulative sum of 1-100 even numbers
sum_odd = 0  #Cumulative sum of 1-100 odd numbers
for num in range(101):
	sum_all += num
if num%2==0:
	sum_even += num
else:
	sum_odd += num
print("1-100 Cumulative sum{0},Odd sum{1},Even sum{2}".format(sum_all,sum_odd,sum_even))

1.5 nested loops

One loop can be embedded in another loop, which is generally called "nested loop" or "multiple loop"
[operation] print the following pattern

for x in range(5):
	for y in range(5):
		print(x,end="\t")
	print() #Wrap only

[operation] print 99 multiplication table using nested loop

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

Operation results:

2. Circular statement

2.1 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.
[operation] use the break statement to end the loop

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

2.2 continue statement

The continue statement is used to end this cycle and continue the next one. When multiple loops are nested, continue is also applied to the nearest loop.
[operation] 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 the employee's salary by Q or q (end)")
	if s.upper()=='Q':
		print("Exit after entry")
		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))

2.3 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, they will be executed. The syntax structure is as follows:

while Conditional expression:
	Circulatory body
else:
	Statement block
 Or:
for variable in Iteratable objects:
	Circulatory body
else:
	Statement block

[operation] there are 4 employees in total. Enter the salary of these four employees. After all entries are made, the prompt "you have entered the salary of all 4 employees" will be printed. Finally, print out the entered salary and average salary

salarySum= 0
salarys = []
for i in range(4):
	s = input("Please enter the salary of 4 employees in total (press Q or q (end halfway)")
	if s.upper()=='Q':
		print("Exit after entry")
		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))

3. Loop code optimization

Although the computer is faster and faster and the space is larger and larger, we still have to "haggle over" over performance. When writing a cycle, following the following three principles can greatly improve the operation efficiency and avoid unnecessary inefficient calculation:

  1. Minimize unnecessary calculations within 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
#Loop code optimization test
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)))

Other optimization means

  1. Concatenate multiple strings, using join() instead of+
  2. Insert and delete elements in the list, and try to operate at the end of the list

4. Use zip() to iterate in parallel

We can iterate over multiple sequences in parallel through the zip() function
[operation] test zip() parallel iteration

names = ("Gao Qi","Gao Laoer","Gao Laosan","Gao Laosi")
ages = (18,16,20,25)
jobs = ("teacher","programmer","civil servant")
for name,age,job in zip(names,ages,jobs):
	print("{0}--{1}--{2}".format(name,age,job))

5. Create sequence by derivation

Derivation is a way to quickly create a sequence from one or more iterators. It can combine loops with conditional judgment to avoid lengthy code

5.1 list derivation

List objects are generated by list derivation. The syntax is as follows:

[expression for item in Iteratable object ]
Or:{expression for item in Iteratable object if Conditional judgment}
>>> [x for x in range(1,5)]
[1, 2, 3, 4]
>>> [x*2 for x in range(1,5)]
[2, 4, 6, 8]
>>> [x*2 for x in range(1,20) if x%5==0 ]
[10, 20, 30]
>>> [a for a in "abcdefg"]
['a', 'b', 'c', 'd', 'e', 'f', 'g']
>>> cells = [(row,col) for row in range(1,10) for col in range(1,10)] #Two loops can be used
>>> for cell in cells:
	print(cell)

5.2 dictionary derivation

The dictionary object is generated from the derivation of the dictionary. The format is as follows:
{key_expression: value_expression for expression in iteratable object}
Similar to list derivation, dictionary derivation can also add if condition judgment and multiple for loops.
Count the number of occurrences of characters in the text:

>>> my_text = ' i love you, i love sxt, i love gaoqi' 
>>> char_count = {c:my_text.count(c) for c in my_text}
>>> char_count
{' ': 9, 'i': 4, 'l': 3, 'o': 5, 'v': 3, 'e': 3, 'y': 1, 'u': 1, ',': 2, 's': 1, 'x': 1, 't': 1, 'g': 1, 'a': 1, 'q': 1}

5.3 set derivation

Set derivation generates a set, which is similar to the syntax format of list derivation:

{expression for item in Iteratable object }
Or:{expression for item in Iteratable object if Conditional judgment}
>>> {x for x in range(1,100) if x%9==0}
{99, 36, 72, 9, 45, 81, 18, 54, 90, 27, 63}

5.4 generator derivation (generating tuples)

Many students may ask, "there are derivations. Are there tuples?", Can you use parentheses?

>>> (x for x in range(1,100) if x%9==0)
<generator object <genexpr> at 0x0000000002BD3048>

Tuples have no derivation. A generator can only run once. The first iteration can get the data, and the second iteration finds that the data is gone.

>>> gnt = (x for x in range(1,100) if x%9==0)
>>> for x in gnt:
		print(x,end=' ')
9 18 27 36 45 54 63 72 81 90 99
>>> for x in gnt:
		print(x,end=' ')
>>>

6. Comprehensive exercises

[operation] draw multiple concentric circles

import turtle
t = turtle.Pen()
my_colors = ("red","green","yellow","black")
t.width(4)
t.speed(1)
for i in range(10): #0 1 2 3 4
	t.penup()
	t.goto(0,-i*10) #0, -100,-200,-300,-400
	t.pendown()
	t.color(my_colors[i%len(my_colors)])
	t.circle(15+i*10) #100,200,300, 400, 500
turtle.done() #After the program is executed, the window is still

Operation results:

[operation] draw 18 * 18 chessboard

#Draw a chessboard
import turtle
width = 30
num = 18
x1 = [(-400,400),(-400+width*num,400)]
y1 = [(-400,400),(-400,400-width*num)]
t = turtle.Pen()
t.speed(10)
# t.goto(x1[0][0],x1[0][1])
# t.goto(x1[1][0],x1[1][1])
for i in range(0,19):
	t.penup()
	t.goto(x1[0][0],x1[0][1]-30*i)
	t.pendown()
	t.goto(x1[1][0],x1[1][1]-30*i)
for i in range(0,19):
	t.penup()
	t.goto(y1[0][0]+30*i,y1[0][1])
	t.pendown()
	t.goto(y1[1][0]+30*i,y1[1][1])
t.hideturtle() #Hide brush
turtle.done() #Ensure that the running window is not automatically closed

Operation results:

Keywords: Python

Added by Wynder on Sat, 19 Feb 2022 10:56:37 +0200