Introduction to conditional selection and looping in Python

  • 2020-04-02 09:49:24
  • OfStack

Like C and Java, there are also conditional selection and loop statements in Python. The style is very similar to that of C and Java, but there are some differences in writing and usage. Let's take a look today.
A. Conditional selection statement
The keywords for conditional selection statements in Python are: if, elif, and else. Its basic form is as follows:
 
if condition: 
block 
elif condition: 
block 
... 
else 
block 

Where elif and else statement blocks are optional. For if and elif, the branch is executed only if the condition is True, and the else branch is executed only if the if and all elif conditions are False. Notice the difference between the condition selection statement in Python and the condition selection statement in C. Condition must be enclosed in parentheses in C, which is not used in Python, but condition must be followed by a colon.
The following is an example of grading :
 
score=input() 
if score<60: 
print "D" 
elif score<80: 
print "C" 
elif score<90: 
print "B" 
else: 
print "A" 

Two. Circular statement
Like C, Python provides a for loop and a while loop (there is no do in Python.. While loop) two. But the use of the for loop in Python is quite different from that in C (similar to the use of the for loop in Java and C#), and the use of the while loop is roughly similar to that in C.
The basic form of the for loop is as follows:
 
for variable in list: 
block 

For example, calculate the sum from 1 to 100:
 
sum=0 
for var in range(1,101): 
sum+=var 
print sum 

Range () is a built-in function that generates a list of Numbers in a range. For example, range(1,6) produces a list like [1,2,3,4,5], while range(8) produces a list like [0,1,2,3,4,5,6,7].
Of course, you can have nested loops, such as a list=['China','England','America'], to iterate over each letter.
 
list=['China','England','America'] 
for i in range(len(list)): 
word=list[i] 
for j in range(len(word)): 
print word[j] 

The built-in function len() can be used to calculate not only the length of a string but also the number of members in a list or collection.
Here's a look at the basic form of the while loop:
 
while condition: 
block 

The loop is executed only if condition is True. Once condition is False, the loop terminates.
For example:
 
count=2 
while count>0: 
print "i love python!" 
count=count-1 

If you want to terminate the loop in a statement block, you can use break or continue. Break is out of the entire loop, and continue is out of the loop.
 
count=5 
while True: 
print "i love python!" 
count=count-1 
if count==2: 
break 

 
count=5 
while count>0: 
count=count-1 
if count==3: 
continue 
print "i love python!" 

So much for conditionals and loops for now, so much for basic usage. If you are interested, you'd better do it yourself.

Related articles: