match, while loop, break, continue, pass

 match keyword is defined in python as soft keyword and introduced in latter version of python. (Python 3.10) to cater similar requirement as switch.   


>>> import keyword
>>> keyword.softkwlist
['_', 'case', 'match']

Soft keyword are keywords which can be used as normal identifier. 

Example - 

>>> match = 10
>>> match
10

Syntax 

match expression:

            case 1:

            case 2:

            ...

Example 

x = 3

match x:
    case 1: print("ONE")
    case 2: print("TWO")
    case 3: print("THREE")
    case 4: print("FOUR")
print("Outside match")
   

Output

THREE
Outside match

In match, break and default are not used. Only the matched case number would be executed. If there are multiple case number than the first one is executed.

Default case can be written as follow. 
 case _: print("Other")

Other exception in match compared to languages like C is 

i) Real constants are allowed
ii) Bool type constants are allowed
iii) .. all types are supported
iv) Expressions are also allowed. 
x = "abcd"

match x:
    case x if len(x) == 3 : print("ONE")
    case x if len(x) == 4 : print("THREE")
    case _ : print("FOUR")
print("Outside match")

Output
THREE
Outside match

Iterative Control

There are two types of loops in python 

i) while loop
ii) for loop

Syntax of while loop is similar to C language

i = 0
while i <= 4:
    print("Hello")
    i+=1

Note: there is no i++ operator in python.

i = 1
while i <= 10:
    print(i,end=' ')
    i+=1


output - 1 2 3 4 5 6 7 8 9 10 

**

In python we can use else statement with loop, to perform activity at normal execution 

if condition is false without break, then else will continue. If break is encountered than else block will not be executed.

i = 1
while i <= 10:
    print(i,end=' ')
    if i==9 :
        break
    i+=1
else:
    print("\nBreak not encountered")

Transfer control statements:

i) break
ii) continue
iii) pass

These keywords are used to transfer control within the program. There are only 3 transfer control statements.

Both break and continue works same as C language and must be used with if condition.

Break - moves control to last line of loop, continue skip the iteration and let the loop continue. So break cuts the flow and continue let the loop execute for certain condition.

More on pass:

Pass keyword provides dummy logic if there is nothing to be done. 
i = 1
while i <= 10:
    print(i,end=' ')
    if i==9 :
        pass
    i+=1
else:
    print("\nBreak not encountered")


If C there can be Block with curly bracket and ends with semicolon. But there is no way to write empty condition/block in python, then pass is used.

Comments