1. Conditional Judgment Statement
The keywords for conditional selection statements in Python are: If, elif, else three. Its basic form is as follows:
123456789 |
age_of_cc
=
27
age
=
int
(
input
(
"guessage:"
))
if
age
=
=
age_of_cc:
print
(
"Yes,you got it!"
)
elif
age > age_of_cc:
print
(
"猜大啦!"
)
else
:
print
(
"猜小啦!"
)
|
If statement execution is characterized by judging from the top down;
Where the elif and else statement blocks are optional. The branch statement executes only if and elif are judged true, and the Else branch is executed only if and all of the elif's judgments are false. Note in the conditional selection statement in Python, there is a colon behind the judgment.
2. Looping statements2.1 While Loop
Usage:
The while loop executes the statement that is subordinate to it until the condition is False (false)
2.1.1 Break Skip Loop
code example:
AGE_OF_CC = 27count =0while Count < 3: Age = Int (Input ("Guessage:")) if age = = age_of_cc: print ("Yes,you go T it! ") Break Elif Age > AGE_OF_CC: print ("Big guess!") Else: print ("Guess small!") ") count + = 1else: if Count = = 3: print (" error too many times! ") ")
2.1.2 Continue skip the cycle
code example:
123456 |
i
=
1
while
i <
10
:
i
+
=
1
if
i
%
2
>
0
:
# 非双数时跳过输出
continue
print
(i)
# 输出双数2、4、6、8、10
|
2.2 for Loop
The For loop requires a pre-set number of cycles (n), and then executes the statement that is subordinate to the for (n) times.
code example:
12 |
for i in range ( 10 ): print (i) #输出0 1 2 3 4 5 6 7 8 9 |
The while Loop Judgment statement code example:
12345678910111213141516 |
age_of_cc
=
27
count
=
0
while
count <
3
:
age
=
int
(
input
(
"guessage:"
))
if
age
=
=
age_of_cc:
print
(
"Yes,you got it!"
)
break
elif
age > age_of_cc:
print
(
"猜大啦!"
)
else
:
print
(
"猜小啦!"
)
count
+
=
1
else
:
if
count
=
=
3
:
print
(
"错误太多次啦!"
)
|
For condition Judgment code example:
123456789101112131415 |
age_of_cc
=
27
count
=
0
for
i
in
range
(
3
):
age
= int
(
input
(
"guessage:"
))
if
age
=
=
age_of_cc:
print
(
"Yes,you got it!"
)
break
elif
age > age_of_cc:
print
(
"猜大啦!"
)
else
:
print
(
"猜小啦!"
)
count
+
=
1
else
:
if
count
=
=
3
:
print
(
"错误太多次啦!"
)
|
3.1 Input
Input is a function in which the user can enter a string to be saved into a variable
code example:
1 |
name = input ( "Please input your name" ) |
3.2 Print
Using print () to add a string to the parentheses, you can output the specified text to the screen
code example:
3.3 Type Conversions
As you can see above, input inputs are considered to be strings (see) in Python, so we need to type-convert the contents of input:
Convert to int example:
1 |
age = int ( input ( "age is:" )) |
Convert back string: str ()
Python conditional loop judgment