1 of 19

Control Statements

Team Emertxe

2 of 19

Single Control Statements

3 of 19

If Statements

If-Else

  • Syntax

if condition:

statements else:

statements

λ

Example

if num % 2:

print("ODD") else:

print("EVEN")

4 of 19

If Statements

If-Elif-Else

  • Syntax

if condition1:

statements elif condition2:

statements else

statements

λ

Example

if num == 1:

print("You

entered

1")

elif num == 2:

print("You

entered

2")

else:

print("You entered 3")

5 of 19

Multiple Control Statements

6 of 19

Multiple Statements

While

  • Syntax

while condition: statements

λ

Example

i = 1

while i <= 10: print(i)

i = i + 1

7 of 19

Multiple Statements

For

  • Syntax

for var in sequence: statements

λ

Example-v1.1

str = "Hello"

for ch in str: print(ch, end='')

λ

Example-v1.2

n = len(str)

for i in range(n): print(str[i])

8 of 19

Else Suite

9 of 19

Multiple Statements

For with Else suite

  • Syntax

for var in sequence: statement / statements

else:

statement / statements

λ

Example

for i in range(5):

print(i) else:

print("Over")

10 of 19

Multiple Statements

While with Else suite

  • Syntax

while condition:

statement / statements else:

statement / statements

λ

Example

i = 0

while i < 5

print(i) i += 1

else:

print("Over")

While searching an elemnt in the sequence is not found, else will be the best option to display the item not found

11 of 19

Misc Statements

12 of 19

Misc Statements

Break

  • Example

x = 10

while x >= 1:

print("x = ", x) x -= 1

if x == 5:

break

13 of 19

Misc Statements

Continue

  • Example

x = 10

while x >= 1:

if x == 5:

x -= 1

continue print("x = ", x) x -= 1

14 of 19

Misc Statements

Pass

  • Example-1

x = 0

while x < 10: x += 1

if x == 5:

pass print(x)

15 of 19

Misc Statements

Pass

Example-2: Program to retrieve only the negative numbers from the list

num = [1, 2, 3, -4, -5, -6, 7, 8]

for i in num:

if (i > 0): pass

else:

print(i)

Pass does nothing

16 of 19

Misc Statements

Assert

  • Syntax:

assert expression, message

Example-1

num = int(input("Enter the number greater than zero: ")) assert num > 0, "Wrong input"

print("Num: ", num)

17 of 19

Misc Statements

Assert: Try Except

  • Example-1

num = int(input("Enter the number greater than zero: ")) try:

assert num > 0, "Wrong input" print("Num: ", num)

except AssertionError:

print("You entered wrong input") print("Enter positive number")

18 of 19

Misc Statements

Return

Example-1: To add two numbers & return the result

def sum(a, b):

return a + b

res = sum(5, 10) print(res)

19 of 19

THANK YOU