- Mastering Python Networking
- Eric Chou
- 183字
- 2021-07-02 21:42:33
Python control flow tools
The if, else, and elif statements control conditional code execution. As one would expect, the format of the conditional statement is as follows:
if expression:
do something
elif expression:
do something if the expression meets
elif expression:
do something if the expression meets
...
else:
statement
Here is a simple example:
>>> a = 10
>>> if a > 1:
... print("a is larger than 1")
... elif a < 1:
... print("a is smaller than 1")
... else:
... print("a is equal to 1")
...
a is larger than 1
>>>
The while loop will continue to execute until the condition is false, so be careful with this one if you don't want to continue to execute:
while expression:
do something
>>> a = 10
>>> b = 1
>>> while b < a:
... print(b)
... b += 1
...
1
2
3
4
5
6
7
8
9
The for loop works with any object that supports iteration; this means all the built-in sequence types such as lists, tuples, and strings can be used in a for loop. The letter i in the following for loop is an iterating variable, so you can typically pick something that make sense within the context of your code:
for i in sequence:
do something
>>> a = [100, 200, 300, 400]
>>> for number in a:
... print(number)
...
100
200
300
400
You can also make your own object that supports the iterator protocol and be able to use the for loop for this object:
Constructing such an object is outside the scope of this chapter, but it is a useful knowledge to have; you can read more about it https://docs.python.org/3/c-api/iter.html.
推薦閱讀
- AngularJS Web Application Development Blueprints
- Spring Boot+Spring Cloud+Vue+Element項(xiàng)目實(shí)戰(zhàn):手把手教你開(kāi)發(fā)權(quán)限管理系統(tǒng)
- PhpStorm Cookbook
- D3.js 4.x Data Visualization(Third Edition)
- Extending Puppet(Second Edition)
- Mastering Linux Security and Hardening
- iPhone應(yīng)用開(kāi)發(fā)從入門(mén)到精通
- Python+Tableau數(shù)據(jù)可視化之美
- Java高級(jí)程序設(shè)計(jì)
- Python滲透測(cè)試編程技術(shù):方法與實(shí)踐(第2版)
- 高性能MVVM框架的設(shè)計(jì)與實(shí)現(xiàn):San
- Android Application Programming with OpenCV 3
- JavaWeb入門(mén)經(jīng)典
- Spark Streaming技術(shù)內(nèi)幕及源碼剖析
- Web測(cè)試囧事