timerring

Python Control Structure

December 21, 2024 · 1 min read · Page View:
Tutorial
Python
If you have any questions, feel free to comment below.

This blog will review the control structure of Python.

CH4 Program Control Structure #

Condition Test #

Logical Operation #

  • Priority of compound logical operations
    Non > And > Or
print((a > b) and (b > c))    # And
print((a > b) or (b > c))     # Or
print(not(a > b))             # Not

Existence Operation #

Element in list/string

Branch Structure if Statement #

Simple Version #

if age > 7:
    print("if")
else:
    print("else")

Multiple Branch #

if age < 7:
    print("7")
elif age < 13:
    print("13")
elif age < 60:
    print("60")
else: # Sometimes for clarity, it can also be written as elif age >= 60:
    print("60") 

No matter how many branches, only one branch is executed

Iteration Loop for Loop #

Execution Process #

  • Extract each element from the iterable object and perform the corresponding operation

List[ ], tuple( ), set{ }, string" "

graduates = ("apple", "google", "timerring")
for graduate in graduates:
    print("Congratulations, "+graduate)

Dictionary

students = {201901: 'apple', 201902: 'google', 201903: 'timerring'}
for k, v in students.items():
    print(k, v)
for student in students.keys():
# for student in students is equivalent to above

range()

res = []
for i in range(1, 10, 2):
    res.append(i ** 2)
print(res)

break and continue #

  • break End whole cycle
  • continue End this cycle

for and else #

If for loop is executed completely without being interrupted by break, then run else block

product_scores = [89, 90, 99, 70, 67, 78, 85, 92, 77, 82]
i = 0
for score in product_scores:
    if score < 75:
        i+=1 
    if i == 2:
        print("Product sampling fails")
        break
else:
    print("Product sampling qualified")

while #

while and else #

If while loop is executed completely without being interrupted by break, then run else block

count = 0
while count <= 2 :
    count += 1
    print("Loop",count)
else:
    print("over")
#     Loop 1
#     Loop 2
#     Loop 3
#     over

Related readings


<< prev | Python... Continue strolling Python Function... | next >>

If you find this blog useful and want to support my blog, need my skill for something, or have a coffee chat with me, feel free to: