Fundamentals 16 min read

Master Python Statements: From Basics to Advanced Control Flow

This article provides a comprehensive guide to Python statements, covering assignment, function calls, control structures, loops, exception handling, and iteration techniques, complete with syntax rules, examples, and best practices for writing clean, efficient code.

Ops Development Stories
Ops Development Stories
Ops Development Stories
Master Python Statements: From Basics to Advanced Control Flow
子曰:论笃是与?君子者乎?色庄者乎?——《论语》

Python Statement Formatting

Statement Start

In Python, statements are not delimited by braces; a new line ends a simple statement. Indentation must be consistent and cannot start with arbitrary spaces.

>> print(1)
  File "<stdin>", line 1
    print (1)
    ^
IndentationError: unexpected indent

Statement Alignment

In compound statements, indentation must be uniform.

>> def add(str):
...     str = str
...     print(str)
  File "<stdin>", line 3
    print(str)
        ^
IndentationError: unindent does not match any outer indentation

Compound Statements

Compound statements can be written in single-line or multi-line form. A colon starts the block.

# Single-line statement
>>> if 1>0: print(1)
... # Multi-line statement
>>> if 1>0:
...     int = 1
...     print(int)
1

Statement Termination

Simple statements end at the line break; multiple statements can be separated by semicolons.

>> a=3;b=3;print(a+b)
6

Error Handling

Use try to catch exceptions without stopping the program.

>> while True:
...     _input = input("please input digit:")
...     try:
...         print("{:d} *10 is {:d}".format(int(_input), int(_input)*10))
...         break
...     except:
...         print("{} is not a number")
please input digit:a
a is not a number
please input digit:1
1 *10 is 10

Variable Assignment

Naming Rules

Variable names may contain letters, digits, and underscores but must start with a letter or underscore. They are case‑sensitive and cannot be Python reserved words (e.g., False, class, def, if, raise, etc.). Special names surrounded by double underscores (e.g., __init__) have special meanings.

Printing

print Function

Since Python 3, print is a function returning None. Its signature is print(*objects, sep=' ', end='\n', file=sys.stdout).

>> print(1,2,3,sep=';')
1;2;3
>>> print(1,2,3,sep=':')
1:2:3
>>> print(1,2,3,end='')
1 2 3>>> print(4,5,6,end='')
456

Conditional Statements

Truth Testing

Expressions in if evaluate to True or False. Comparison, logical, membership, and identity operators are used.

>> 1<2
True
>>> True and True
True
>>> 1 in [1,2]
True
>>> 1 in {"1":1}
False

Logical Operators

and

returns the first falsy value or the last truthy value; or returns the first truthy value or the last falsy value.

>> False and [] and {}
[]
>>> 1 and 2 and True
True
>>> 0 or [1] or {"1":1}
[1]
>>> 0 or [] or {}
{}

Conditional Expression (Ternary)

>> 1 if True else 2
1
>>> 1 if False else 2
2
>>> 'True' if 1>2 else 'False'
'False'

Loops

while Loop

The loop continues while the test expression is true. Use break, continue, or modify the test variable to exit.

>> a=0;b=10
>>> while a<b:
...     print(a,end='')
...     a+=1
0123456789

break and continue

>> a=0;b=10
>>> while a<b:
...     a+=1
...     if a==3: continue
...     if a==7: break
...     print(a,end='')
12456

pass Statement

pass

acts as a placeholder where no action is needed.

>> if True:
...     print('true')
... else: pass
true

else Clause

The else block runs after a for or while loop completes normally.

>> a=0;b=10
>>> while a<b:
...     print(a,end='')
...     a+=1
... else:
...     print('end')
0123456789end

for Loop

for

iterates over any iterable object.

>> for i in a:
...     print(i,end='')
12345

Range Function

>> a=range(10)
>>> for i in a:
...     print(i,end='')
0123456789

Nested Loops

>> for l in [(1,2,3),(4,5,6),(7,8,9)]:
...     for i in l:
...         print(i,end='')
...     print()
123
456
789

Iterators and Comprehensions

File Iterator

File objects are their own iterators. Use .read(), .readline(), .readlines(), or the built‑in next() function.

>> file=open('1.txt')
>>> file.__next__()
'hello,world'
>>> next(file)
Traceback (most recent call last):
  StopIteration

Manual Iteration

>> li=[1,2,3]
>>> i=iter(li)
>>> next(i)
1
>>> next(i)
2
>>> next(i)
3
>>> next(i)
Traceback (most recent call last):
  StopIteration

Dictionary Iteration

>> dic={'a':1,'b':2,'c':3}
>>> for key in dic:
...     print(key,dic[key])
a 1
b 2
c 3

List Comprehension

>> li=[1,2,3,4,5]
>>> li=[i+10 for i in li]
[11, 12, 13, 14, 15]
>>> li=[i+10 for i in li if i!=13]
[11, 12, 14, 15]
>>> [x+y for x in [1,2,3] for y in [10,20,30]]
[11, 21, 31, 12, 22, 32, 13, 23, 33]

Other Iterable Utilities

Functions like map, sorted, enumerate, sum, any, all, max, and min operate on iterables.

>> list(map(str.upper, open('1.txt')))
['HELLO,WORLD']
>>> sorted(open('1.txt'))
['hello,world']
>>> list(enumerate(open('1.txt')))
[(0, 'hello,world')]
>>> max([3,5,1,6,4]), min([3,6,8,2,4])
(6, 2)
>>> any([1, [], 'True']), all([1, [], 'True'])
(True, False)

Generators in Python 3

Functions using yield produce lazy iterables.

>> def printlist(lst):
...     for i in lst:
...         print('function print:{}'.format(i))
...         yield 'Result: {}'.format(i)
>>> s=printlist([1,2,3])
>>> next(s)
function print:1
'Result: 1'
>>> next(s)
function print:2
'Result: 2'
Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

PythonprogrammingTutorialsyntaxControl Flow
Ops Development Stories
Written by

Ops Development Stories

Maintained by a like‑minded team, covering both operations and development. Topics span Linux ops, DevOps toolchain, Kubernetes containerization, monitoring, log collection, network security, and Python or Go development. Team members: Qiao Ke, wanger, Dong Ge, Su Xin, Hua Zai, Zheng Ge, Teacher Xia.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.