SoFunction
Updated on 2025-03-01

Python full stack single-item loop

1. Multiple_Nest-shaped branch

Multiple branches (choose one more)

"""
 if conditional expression 1:
	 code1
 elif conditional expression 2:
	 code2
 elif conditional expression 3:
	 code3
 else:
	 `code4
 If condition expression 1 is true, execute the corresponding branch code1, otherwise determine whether condition expression 2 is true
 If condition expression 2 is true, execute the corresponding branch code2, otherwise determine whether condition expression 3 is true.
 If condition expression 3 is true, execute the corresponding branch code3. If it is not true, go directly to the else branch and execute the program.
 elif can be 0 or multiple
 else can be 0 or one
 """
youqian = False
youfang = False
youche = False
if youqian == True:
	print("It means this person is very powerful")
elif youfang == True:
	print("Can you give it to your friends?")
elif youche == True:
	print("We'll touch you after driving the Yadi Emma drives the car.")	
else:
	print("You'd better be a Meituan rider")
print("<=======================>")
###Nest-shaped branch"""Single-item branch, bidirectional branch, and inter-needing combination of multiple branches"""
youqian = True
youfang = True
youche = True
youyanzhi = True
youtili = False
if youqian == True:
	if youfang == True:
		if youche == True:
			if youyanzhi == True:
				if youtili == True:
					print("I want to marry you~")
				else:
					print("You go and have some big waist before you come~")
			else:	
				print("You go to Thailand + South Korea and have a plastic surgery")
else:
	print("You are a good person~")
	
print("<=======================>")
#Quoting height#Girls find a partner	# Boys are between 1 meter and 1.5 meters. Xiaoqiang Where are you?	# Boys are between 1.5 and 1.7 meters and feel insecure~	# Boys 1.7~1.8 meters handsome guy, leave a phone number	# Boys between 1.8~2 meters handsome guy, do you suggest you have an extra girlfriend?# python-specific (note: Because the numbers accepted by input are strings, and because we can enter decimals, we can only use float here)"""
height = float(input("Please enter your height:"))
if 1 <= height < 1.5:
	print("Xiaoqiang Where are you?")
elif 1.5 <= height < 1.7:
	print("Insecure~")
elif 1.7 <= height < 1.8:
	print("Handsome guy, leave a phone number")
elif 1.8 <= height < 2:
	print("Do you suggest an extra girlfriend?")
else:
	print("Sorry, there is no suitable option")
"""
# General writingheight = float(input("Please enter your height:"))
if 1 <= height and height < 1.5:
	print("Xiaoqiang Where are you?")
elif 1.5 <= height and height < 1.7:
	print("Insecure~")
elif 1.7 <= height and height < 1.8:
	print("Handsome guy, leave a phone number")
elif 1.8 <= height and height < 2:
	print("Do you suggest an extra girlfriend?")
else:
	print("Sorry, there is no suitable option")
"""
 tab indents right
 shift + tab indent left
 """

2. Circular structure

2.1 Circular structure

"""Features: Reduce redundant code and improve execution efficiency"""
"""
grammar:
while Conditional expression:
	code1
(1) Initialize a variable
(2) Write the condition for looping
(3) The value of self-increasing and self-decreasing
"""
# ### Print 1 ~ 100# (1) Initialize a variablei = 1
# (2) Write the condition for loopingwhile i <= 100:
	# (4) Write the logic of looping	print(i)
	# (3) Values ​​that increase and decrease	i += 1 # i = i + 1
"""
Code parsing:
First cycle
i = 1  i<=100 Decide true,Execute the loop body print(1)
i += 1 i => 2 
The second cycle
Code back to17OK,重新进OK条件判定 
i = 2  i<=100 Decide true,Execute the loop body print(2)
i += 1 i => 3
The third cycle
Code back to17OK,重新进OK条件判定 
i = 3  i<=100 Decide true,Execute the loop body print(3)
i += 1 i => 4
....
And so on 
untili = 101  i <= 100 Decided as false,不Execute the loop body,End of this cycle...
1 ~ 100
"""
#### 1 ~ 100 cumulative sum# (1) Initialize a variablei = 1
total = 0
# (2) Write the condition for loopingwhile i <= 100 :
	# (4) Write custom logic	total += i
	# (3) Values ​​that increase and decrease	i += 1
print(total)
"""
Code parsing:
First cycle
i = 1 i <= 100 Determined as trueTrue Execute the loop body total += i => total = total + i => 0 + 1
i += 1  => i = 2
The second cycle
i = 2 i <= 100 Determined as trueTrue Execute the loop body total += i => total = total + i => 0 + 1 + 2
i += 1  => i = 3
The third cycle
i = 3 i <= 100 Determined as trueTrue Execute the loop body total += i => total = total + i => 0 + 1 + 2 + 3 
i += 1  => i = 4
...
Analogous in sequence
wheni = 101 101 <= 100 Decided as falseFalse 不Execute the loop body,Here,End of the loop..
total += i => total + i => 0 + 1 + 2 + 3 + 4 + .... + 100 => 5050
"""

#Ending cycle"""
while True:
	print(1)
"""

#### Use the method of a dead loop to achieve 1 to 100 cumulative sumi = 1
total = 0
sign = True
while sign:
	total += i
	i+=1
	# Determine whether i is added to 101, and do not participate in the loop	if i == 101:
		# Terminate the loop		sign = False
print(total) #1 ~ 100 = 5050

2.2 Exercises for single loops

# (1) Print a line of ten small stars* help(print)# help View a method's documentationhelp(print)
"""
# print("*",end='')
# print("*",end='')
# print("*",end='')
# print("*",end='')
# print("*",end='')
# print("*",end='')
# print("*",end='')
# print("*",end='')
# print("*",end='')
# print("*",end='')
"""
i = 0
while i<10:	
	# end='' When printing, no line breaks are added at the end by default	print("*",end='')	
	i += 1
# Default line break# print()
# (2) Display a row of ten small stars by printing a variableprint("<======>")
i = 0
strvar = ""
while i < 10:
	# Write the logic of loop	strvar += "*" # strvar = strvar + "*"
	i +=1
print(strvar)
"""
strvar += "*" => strvar = "*"
strvar += "*" => strvar = "*" + "*"  = "**"
strvar += "*" => strvar = "**" + "*" = "***"
...
strvar += "*" => strvar = "********" + "*" = "*********"
"""
# (3) Ten color-changing stars in a row ★☆★☆★☆★☆★☆★☆★☆★☆"""
# Method 1i = 0
while i < 5:
	print("★☆",end="")
	i+=1
"""
# Method 2i = 0
while i < 10:
	if i % 2 == 0 :
		print("★",end="")
	else:
		print("☆",end="")
	i+=1
print("<=============>")
# Method 3i = 0
strvar = ""
while i < 10:
	if i % 2 == 0 :
		strvar += "★"
	else:
		strvar += "☆"
	i+=1
print(strvar)
"""
***formula: Any number and n Take the remaining,Range of remainder: 0 ~ (n-1)***
0 % 2 = 0
1 % 2 = 1
2 % 2 = 0
3 % 2 = 1
Divided % 2 => 0 or 1
0 % 5 = 0 
1 % 5 = 1
2 % 5 = 2
3 % 5 = 3
4 % 5 = 4
5 % 5 = 0 
6 % 5 = 1
7 % 5 = 2
Divided % 5 => 0 or 1,2,3,4
"""
# (4) Use a loop to print ten rows and ten columns of small stars"""
★★★★★★★★★★
★★★★★★★★★★
★★★★★★★★★★
★★★★★★★★★★
★★★★★★★★★★
★★★★★★★★★★
★★★★★★★★★★
★★★★★★★★★★
★★★★★★★★★★
★★★★★★★★★★
"""
# Method 1i = 0 
while i < 100:
	# Logic is written here	print("*" , end="")
	# Print newline (on 9 19 29 .. 99 )	if i % 10 == 9:
		print()
	i += 1 

"""
0123456789
**********
10111213141516171819
**********
20212223242526272829
**********
...
90919293949596979899
**********
9 19 29 39 49 59 69 79 89 99
9 % 10  = 9
19 % 10 = 9
29 % 10 = 9
...
99 % 10 = 9
"""

print("<======>")
# Method 2i = 1
while i <= 100:
	# Logic is written here	print("*" , end="")
	# Print newline (on 9 19 29 .. 99 )	if i % 10 == 0:
		print()
	i += 1 
"""
12345678910
**********
11121314151617181920
**********
21222324252627282930
**********
...
919293949596979899100
**********
10 20 30 ... 100
"""
# (5) A loop implements the small stars with ten rows and ten columns, and the color of the grid is replaced."""
★☆★☆★☆★☆★☆
★☆★☆★☆★☆★☆
★☆★☆★☆★☆★☆
★☆★☆★☆★☆★☆
★☆★☆★☆★☆★☆
★☆★☆★☆★☆★☆
★☆★☆★☆★☆★☆
★☆★☆★☆★☆★☆
★☆★☆★☆★☆★☆
★☆★☆★☆★☆★☆
"""
i = 0 
while i < 100:
	# (1) Print stars	if i % 2 == 0 :
		print("★",end="")
	else:
		print("☆",end="")
	# (2) Print newline (on 9 19 29 .. 99 )	if i % 10 == 9:
		print()
	i += 1 
# (6) A loop implements ten rows and ten columns, interlaced colors and small stars"""
★★★★★★★★★★
☆☆☆☆☆☆☆☆☆☆
★★★★★★★★★★
☆☆☆☆☆☆☆☆☆☆
★★★★★★★★★★
☆☆☆☆☆☆☆☆☆☆
★★★★★★★★★★
☆☆☆☆☆☆☆☆☆☆
★★★★★★★★★★
☆☆☆☆☆☆☆☆☆☆
*** formula:Any numberandnDelete the floor,Will appearnThe same number
0 // 10 = 0
1 // 10 = 0
2 // 10 = 0
..
9 // 10 = 0
0 ~ 9 // 10 => 0 (10 same 0)10 // 10 = 1
11 // 10 = 1
12 // 10 = 1
...
19 // 10 = 1
10 ~ 19 // 10 => 1 (10 same 1).... And so on
20 ~ 29 // 10 => 2 (10 same 2)30 ~ 39 // 10 => 3 (10 same 3)40 ~ 49 // 10 => 4 (10 same 4)...
90 ~ 99 // 10 => 9 (10 same 9)0~ 100 Will appear10The same0,1,2 , 3 ... 9 
0 // 3 0
1 // 3 0
2 // 3 0
3 // 3 1
4 // 3 1
5 // 3 1 
"""
""""""
# Method 1i = 0 
while i < 100:
	# (1) Print stars	if i // 10 % 2 == 0:
		print("★",end="")
	else:
		print("☆",end="")
	# (2) Print newline (on 9 19 29 .. 99 )	if i % 10 == 9:
		print()
	i += 1 
# Method 2print("<=================>")
i = 10
while i < 110:
	# Print stars	num = int(str(i)[-2])
	if num % 2 == 0 :
		print("★",end="")
	else:
		print("☆",end="")
	# Print line break	if i % 10 == 9:
		print()
	i+=1
"""
10 ~ 100 101 102 103 110...
10 ~ 19 => 1
20 ~ 29 => 2
30 ~ 39 => 3
90 ~ 99 => 9
100 ~ 109 => 0
"""

3. Slicing of strings

String related operations

# (1) String splicing +str1 = "Zhao Shenyang,"
str2 = "so strong"
res = str1 + str2
res = "Zhao Shenyang," + "so strong"
print(res)
# res = res + ", the classmates next to him like him very much ~"res += ", the classmates next to him like him very much~"
print(res)
# (2) Repeat of string *strvar = "Say important things three times~"
res = strvar * 3
print(res)
# (3) String cross-line splicing \str1 = "kskfjskjfklsjfklasdjklfjaskldjfaskljfklasjdfklasjdklfjaskldfjaskldjflasjfsf" \
"1122334"
print(str1)
# (4) Index of strings#          0 1 2 3 4 5
strvar = "Zhao Shichao is so handsome"
#         -6-5-4-3-2-1
print(strvar[1])
# (5) Slice of string: (intercepted)"""
grammar => String[::]  Full format:[Start indexing:End index:Interval value]
	(1)[Start indexing:]  从Start indexing截取到String的最后
	(2)[:End index]  从开头截取到End index之前(End index-1)
	(3)[Start indexing:End index]  从Start indexing截取到End index之前(End index-1)
	(4)[Start indexing:End index:Interval value]  从Start indexing截取到End index之前按照指定的间隔截取字符
	(5)[:]or[::]  截取所有String
"""
strvar = "Wang Wen is the most perfect, flawless, kind, beautiful, handsome, handsome, handsome, handsome, elegant, and suave mysterious boy in this universe."
# (1)[Start Index:] Intercept from the start index to the end of the stringres = strvar[3:]
print(res)
# (2)[:End Index] Before intercepting from the beginning to the end index (End Index-1)"""The maximum value of 4 itself cannot be obtained. To obtain the data before 4: take the head and leave the tail"""
res = strvar[:5]
print(res)
# (3) [Start Index: End Index] Before intercepting from the start index to the end index (end index-1)res = strvar[10:16]
print(res)
# (4)[Start Index: End Index: Interval Value] Snap characters at the specified interval before intercepting the start index to the end index# Intercept from left to rightres = strvar[::3]
# 0 3 6 9 12 15 ... 
print(res)
# Intercept from right to leftres = strvar[::-1]
# -1 -2 -3 -4 -5 -6 .... 
print(res)
res = strvar[-3:-10:-2]
# -3 -5 -7 -9 The Secret Painprint(res)
print("<====>")
"""From left to right, the interval value is positive, and conversely, the interval value is negative, so that the data can be intercepted"""
"""
res = strvar[-3:-10:10] # Error logicprint(res)
res = strvar[1:10]
print(res)
"""

4. Small exercises

question:

1.A game that guesses the size:
Set an ideal number, for example:66,Let the user enter numbers,If66big,则显示猜测的结果big了;If66Small,则显示猜测的结果Small了;Only equal to66,Show correct guess results。
2.Output 1-100 All odd numbers within
3.Output 1-100 All even numbers within
4.User login(Three chances of losing wrong)And each time an error is entered, the remaining error count is displayed(hint:Format using string)
5.Write code,There are the following strings that use slices to achieve each function
strvar = "132a4b5c"
1)Slice the string to form a new string "132"
2)Slice the string to form a new string "a4b"
3)Slice the string to form a new string "1245"
4)Slice the string to form a new string "3ab"
5)Slice the string to form a new string "c"
6)Slice the string to form a new string "ba3"
6.International chessboard effect

Answer:

# 1. Guess the size of the game:# Set an ideal number such as: 66, let the user enter the number. If it is larger than 66, the guess result will be larger; if it is smaller than 66, the guess result will be smaller; if it is smaller than 66, the guess result will be correct."""
num = 66
str_num = input("Please enter the ideal number")
num_new = int(str_num)
if num_new > num:
	print("The guess is big")
elif num_new == num:
	print("Show the guess results are correct")
elif num_new < 66:
	print("The result of the guess is smaller")
"""

# 2. Output all odd numbers within 1-100"""
i = 1
while i <= 100:
	if i % 2 == 1:
		print(i)
	i +=1
"""
# 3. Output all even numbers within 1-100"""
i = 1
while i <= 100:
	if i % 2 == 0:
		print(i)
	i +=1
"""
# 4. User login (there are three chances of error input) and the remaining error count is displayed every time the error input is entered (tip: use string formatting)"""
times = 1
while times <= 3:
	pwd = input("Please enter your password:")
	if pwd == "111":
		print("Congratulations on logging in successfully~")
		break
	# Remaining times = Total times - Number of times already used	print("Your remaining input is %d" % (3 - times))	
	times +=1
"""
"""
sign = True
times = 1
while sign:
	pwd = input("Please enter your password:")
	if pwd == "111":
		print("Congratulations on logging in successfully~")
		sign = False
	else:
		# Remaining times = Total times - Number of times already used		print("Your remaining input is %d" % (3 - times))
	# If the number of times is already 3 times, force the loop to be terminated;	if times == 3:
		print("You no longer have a chance...")
		sign = False	
	times +=1
"""
# 5. Write code, with the following strings to implement each function using slicesstrvar = "132a4b5c"
# 1) Slice the string to form a new string "132"print(strvar[0:3])
# 2) Slice the string to form a new string "a4b"print(strvar[3:6])
# 3) Slice the string to form a new string "1245"print(strvar[::2])
# 4) Slice the string to form a new string "3ab"print(strvar[1:6:2])
#5) Slice the string to form a new string "c"print(strvar[-1:])
# 6) Slice the string to form a new string "ba3"print(strvar[-3::-2]) # -3 -5 -7 
# 6. International chessboard effects# Method 1j = 0
while j < 8:	
	# □■□■□■□■
	if j % 2 == 0:
		print("□■□■□■□■",end="")			
	# ■□■□■□■□
	else:
		print("■□■□■□■□",end="")
	print()
	j +=1
"""
# □■□■□■□■
i = 0		
while i < 8:
	if i % 2 == 0:
		print("□",end="")
	else:
		print("■",end="")
	i +=1 
# ■□■□■□■□
i = 0		
while i < 8:
	if i % 2 == 0:
		print("■",end="")				
	else:
		print("□",end="")
	i +=1 
"""
print("<=====>")
j = 0
while j < 8:	
	# □■□■□■□■
	if j % 2 == 0:
		i = 0		
		while i < 8:
			if i % 2 == 0:
				print("□",end="")
			else:
				print("■",end="")
			i +=1 		
	# ■□■□■□■□
	else:
		i = 0		
		while i < 8:
			if i % 2 == 0:
				print("■",end="")				
			else:
				print("□",end="")
			i +=1 
	print()
	j +=1

# Method 2"""
□■□■□■□■
■□■□■□■□
□■□■□■□■
■□■□■□■□
□■□■□■□■
■□■□■□■□
□■□■□■□■
■□■□■□■□
"""
print("<=====>")
i = 0
while i < 64:
	# Determine whether it is an odd or even line	if i // 8 % 2 == 0:
		# □■□■□■□■
		if i % 2 == 0:
			print("□",end="")
		else:
			print("■",end="")
	else:
		# ■□■□■□■□
		if i % 2 == 0:
			print("■",end="")			
		else:
			print("□",end="")
	#Eighth block line break	if i % 8 == 7:
		print()		
	i +=1
print("<=====>")
# Method 3i = 0
while i < 4:
	strvar = ""
	j = 0
	# Print small squares in black and white	while j < 8:
		if j % 2 == 0:
			strvar += "□"
		else:
			strvar += "■"
		j +=1
	# Forward printing	print(strvar)
	# Reverse printing	print(strvar[::-1])
	i +=1

Summarize

That’s all for this article. I hope it can help you and I hope you can pay more attention to more of my content!