Starting today , Xiaobai, I will lead you to learn Python Introduction to zero foundation . This column will explain + Practice mode , Let's get familiar with it Python The grammar of , application , And the basic logic of the code .
Loop statements can help us repeat a block of code many times , Improve the reuse rate and simplicity of code .
Python Type of loop in :
example 1:
# utilize for Cyclic output 0-9
for i in range(10):
print(i)
Output results :
0
1
2
3
4
5
6
7
8
9
example 2:
# Create a list of
list1 = [1, 2, 3, 4, 5]
# utilize for Loop through the list
for num in list1:
print(num)
Output results :
1
2
3
4
5
Example :
# Defining variables i
i = 0
# while Cyclic output 0-9
while i < 10:
print(i) # Debug output i
i += 1 # Each cycle i+1
Output results :
0
1
2
3
4
5
6
7
8
9
The judgment statement determines the code block to be executed later by judging and formulating conditions .
Format :
if Judge the condition :
Execute statement
Example :
# if Judgment statement
if 1 < 2:
print(" Hello, motherland 1") # Condition is True, perform
if 2 < 1:
print(" Hello, motherland 2") # Condition is False, Not execute
Output results :
Hello, motherland 1
Format :
if Judge the condition :
Condition is True Execute statement
else:
Condition is False Execute statement
Example :
# Create variables
num1 = 1
num2 = 2
# if...else... Judgment statement
if num1 > num2:
print(" Numbers num1 > Numbers num2")
else:
print(" Numbers num2 > Numbers num1")
Output results :
Numbers num2 > Numbers num1
Format :
Condition is True perform if Conditions else Condition is False perform
Example :
# Create variables
num1 = 1
num2 = 2
# Ternary expression
result = " Numbers num1 > Numbers num2" if num1 > num2 else " Numbers num2 > Numbers num1"
print(result) # Debug output
Output results :
Numbers num2 > Numbers num1
By using break
sentence , python The code can jump out of the loop in advance .
Example :
# for loop
for i in range(10):
# When i by 3 Jump out of the loop
if i == 3:
break
# Debug output
print(i)
Output results :
0
1
2
Compared to using break
Statement directly jumps out of the loop , Use contine
Statement will jump out of this loop , The rest of the code will not be executed .
Example :
# for loop
for i in range(10):
# When i by 3 Skip this cycle when
if i == 3:
continue
# Debug output
print(i)
Output results :
0
1
2
4
5
6
7
8
9
We can see , When i = 3 When , Skipped the current loop , i No printing .
pass
Statements in python The role of is to occupy space .
Example :
# Defined function
def func():
pass # placeholder