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 somethingelif expression:  do something if the expression meetselif 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 (and crash your process):

while expression:  do something
>>> a = 10>>> b = 1>>> while b < a:... ...

Get Mastering Python Networking - Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.