0% found this document useful (0 votes)
10 views3 pages

Python Control Flow Basics

Uploaded by

Vimala Rajendran
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views3 pages

Python Control Flow Basics

Uploaded by

Vimala Rajendran
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Chapter: Control Flow

1. Introduction to Control Flow


A control flow statements in Python: - Conditional statements: if, elif, else - Loops: for, while -
Jump statements: break, continue, pass

2. Conditional Statements
2.1 if Statement
Executes a block of code if a condition is true.
age = 18
if age >= 18:
print("You are eligible to vote.")
2.2 if-else Statement
Executes alternative blocks based on a condition.
num = 10
if num % 2 == 0:
print("Even number")
else:
print("Odd number")
2.3 if-elif-else Statement
Handles multiple conditions sequentially.
marks = 85
if marks >= 90:
print("Grade A")
elif marks >= 75:
print("Grade B")
elif marks >= 60:
print("Grade C")
else:
print("Grade D")

3. Loops
3.1 while Loop
Executes as long as the condition is true.
i=1
while i <= 5:
print(i)
i += 1
3.2 for Loop
Iterates over a sequence or range.
for i in range(1, 6):
print(i)

sum of all odd numbers from 1 to 20


for num in range(1, 21): # Loop from 1 to 20
if num % 2 != 0: # Check if the number is odd
print(num, end=' ')
3.3 Nested Loops
A loop inside another loop.
for i in range(1, 4):
for j in range(1, 4):
print(f"i={i}, j={j}")

4. Jump Statements
4.1 break Statement
Terminates the loop immediately.
for i in range(1, 6):
if i == 3:
break
print(i)
4.2 continue Statement
Skips current iteration and proceeds to next.
for i in range(1, 6):
if i == 3:
continue
print(i)
4.3 pass Statement
A null operation used as placeholder.
for i in range(1, 6):
if i == 3:
pass
print(i)

5. Sample Programs
Example 1: Check Voting Eligibility
age = int(input("Enter your age: "))
if age >= 18:
print("You are eligible to vote.")
else:
print("You are not eligible to vote.")
Example 2: Print Multiplication Table
num = int(input("Enter a number: "))
for i in range(1, 11):
print(f"{num} x {i} = {num*i}")
Example 3: Sum of Natural Numbers
n = int(input("Enter a number: "))
sum = 0
for i in range(1, n+1):
sum += i
print(f"Sum of first {n} natural numbers is {sum}")

You might also like