0% found this document useful (0 votes)
9 views17 pages

Control Statements - Python

The document provides a comprehensive overview of control flow statements in Python, including decision control statements like if, else, and elif, as well as iterative statements such as for and while loops. It includes examples and explanations of various patterns that can be created using these control flow structures. Additionally, it covers the use of logical operators, transfer statements, and the significance of indentation in Python programming.
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)
9 views17 pages

Control Statements - Python

The document provides a comprehensive overview of control flow statements in Python, including decision control statements like if, else, and elif, as well as iterative statements such as for and while loops. It includes examples and explanations of various patterns that can be created using these control flow structures. Additionally, it covers the use of logical operators, transfer statements, and the significance of indentation in Python programming.
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

TABLE OF CONTENTS

CONTROL FLOW STATEMENTS IN PYTHON .................................................................................................... 2


1. DECISION CONTROL STATEMENTS ............................................................................................................. 2
PYTHON CONDITIONS AND INDENTATION .....................................................................................................................2
2. SIMPLE IF FLOW ...................................................................................................................................................2
Why Use if: ..................................................................................................................................................3
3. IF-ELSE FLOW ......................................................................................................................................................3
Use Cases: ......................................................................................................................................................3
4. NESTED IF FLOW ................................................................................................................................................4
When to Use: ..................................................................................................................................................4
5. IF-ELIF-ELSE FLOW ..............................................................................................................................................4
Use Case: ........................................................................................................................................................5
6. ELIF LADDER .......................................................................................................................................................5
Explanation: ..................................................................................................................................................6
Why Use Elif Ladder: ....................................................................................................................................6
7. SHORT-HAND IF AND IF-ELSE FLOW ...................................................................................................................6
Use Case: ........................................................................................................................................................7
8. MULTIPLE CONDITIONS IN IF USING AND/OR OPERATORS ...........................................................................................7
Why Use Multiple Conditions: ......................................................................................................................7
9. TRANSFER STATEMENTS ........................................................................................................................................7
Use Case: ........................................................................................................................................................8
10. ITERATIVE STATEMENTS .......................................................................................................................................8
11. PATTERN PROGRAMS IN PYTHON ..........................................................................................................................9
PATTERN 1: RIGHT-ANGLED TRIANGLE OF STARS .........................................................................................................10
PATTERN 2: INVERTED RIGHT-ANGLED TRIANGLE.........................................................................................................11
PATTERN 3: PYRAMID OF STARS ...............................................................................................................................11
PATTERN 4: INVERTED PYRAMID OF STARS .................................................................................................................12
PATTERN 5: DIAMOND OF STARS ..............................................................................................................................13
PATTERN 6: RIGHT-ANGLED NUMBER TRIANGLE .........................................................................................................14
PATTERN 7: PASCAL’S TRIANGLE ...............................................................................................................................14
PATTERN 8: HOLLOW SQUARE .................................................................................................................................15
PATTERN 9: HOLLOW PYRAMID ................................................................................................................................16
Conclusion .....................................................................................................................................................17

1
CONTROL FLOW STATEMENTS IN PYTHON

Control flow statements dictate the order in which instructions are executed in a program. These instructions
help your program make decisions, repeat actions, or transfer control based on certain conditions.

1. DECISION CONTROL STATEMENTS

These statements allow the program to take decisions based on conditions. They are primarily based on if,
else, and elif.

PYTHON CONDITIONS AND INDENTATION

Python uses indentation (whitespace at the start of lines) to define the scope of blocks of code. This is very
different from languages like C or Java, where {} braces are used.

Example:

if condition:

# Indented code belongs to the if block

statement_1

statement_2

If the indentation is incorrect, Python will raise an IndentationError.

2. SIMPLE IF FLOW

The if statement checks a condition. If the condition evaluates to True, the indented block of code below it is
executed.

Syntax:

if condition:

# This block executes only if the condition is True

statement_1

Example:

age = 18

if age >= 18:

print("You are an adult.")

2
Explanation:

• The condition age >= 18 checks if age is greater than or equal to 18.
• If True, "You are an adult." is printed.

Why Use if:

• You want certain parts of your program to run only when specific conditions are met.

3. IF-ELSE FLOW

An if-else statement provides two pathways: one if the condition is True, and the other if it’s False.

Syntax:

if condition:

# Executes if the condition is True

statement_1

else:

# Executes if the condition is False

statement_2

Example:

temperature = 30

if temperature > 25:

print("It's hot outside.")

else:

print("It's cool outside.")

Explanation:

• The condition temperature > 25 is checked.


• If True, "It's hot outside." is printed; otherwise, "It's cool outside." is printed.

Use Cases:

• When you need to take an alternative action when a condition is false.

3
4. NESTED IF FLOW

A nested if is an if statement inside another if. It allows for more complex decision making.

Syntax:

if condition1:

if condition2:

# Executes if both conditions are True

statement_1

Example:

age = 20

if age >= 18:

if age >= 65:

print("You are a senior citizen.")

else:

print("You are an adult.")

Explanation:

• The first if checks if age is at least 18.


• The nested if checks if age is 65 or more.
• Based on the conditions, the appropriate message is printed.

When to Use:

• When decisions need to depend on multiple conditions.

5. IF-ELIF-ELSE FLOW

The if-elif-else flow allows for multiple conditions to be checked sequentially, and only the first True
block is executed. If none of the conditions are True, the else block is executed.

Syntax:

if condition1:

# Executes if condition1 is True

statement_1

4
elif condition2:

# Executes if condition2 is True

statement_2

else:

# Executes if neither condition1 nor condition2 is True

statement_3

Example:

marks = 75

if marks >= 90:

print("Grade: A")

elif marks >= 80:

print("Grade: B")

elif marks >= 70:

print("Grade: C")

else:

print("Grade: D")

Explanation:

• The first condition marks >= 90 is checked.


• If it's False, the next condition marks >= 80 is checked, and so on.
• If none of the conditions are True, the else block executes.

Use Case:

• When you have multiple possible outcomes depending on different conditions.

6. ELIF LADDER

The elif ladder is a form of multiple conditions arranged in an increasing or decreasing sequence. The code
jumps down the ladder until one of the conditions evaluates to True.

Example:

score = 92

if score >= 90:

5
print("Excellent")

elif score >= 80:

print("Very Good")

elif score >= 70:

print("Good")

elif score >= 60:

print("Average")

else:

print("Needs Improvement")

Explanation:

• You can imagine the elif statements forming a ladder where the conditions are tested one by one,
starting from the top.
• If a condition is met, no further conditions are checked.

Why Use Elif Ladder:

• When you need to test multiple conditions, all of which are mutually exclusive.

7. SHORT-HAND IF AND IF-ELSE FLOW

Short-hand if and if-else flow allow you to write simple conditions in a single line, making the code more
concise.

Syntax (Short-hand if):

if condition: statement

Example:

x = 5

if x > 0: print("x is positive")

Syntax (Short-hand if-else):

statement1 if condition else statement2

Example:

age = 16

6
print("Adult") if age >= 18 else print("Minor")

Use Case:

• When you want to simplify code for small, simple conditions.

8. MULTIPLE CONDITIONS IN IF USING AND / OR OPERATORS

You can combine multiple conditions using logical operators like and (all conditions must be true) or or (at
least one condition must be true).

Syntax:

if condition1 and condition2:

# Executes if both conditions are True

statement_1

Example:

age = 25

income = 50000

if age > 18 and income > 40000:

print("You are eligible for a loan.")

Explanation:

• The condition checks if age is greater than 18 and income is greater than 40,000. Both conditions
must be True.

Why Use Multiple Conditions:

• To check complex conditions where more than one factor needs to be considered.

9. TRANSFER STATEMENTS

Transfer statements are used to alter the normal flow of execution, particularly within loops or conditional
blocks.

BREAK STATEMENT

Exits a loop entirely when encountered.

7
for i in range(5):

if i == 3:

break

print(i)

Explanation:

• The loop will stop as soon as i equals 3.

CONTINUE STATEMENT

Skips the current iteration of the loop and moves to the next iteration.

for i in range(5):

if i == 2:

continue

print(i)

Explanation:

• The loop will skip the iteration when i equals 2, but continue for the other values.

PASS STATEMENT

A placeholder for future code; it does nothing but is syntactically necessary to avoid errors.

if True:

pass

Use Case:

• Use pass when a block of code is syntactically required but no action is needed yet.

10. ITERATIVE STATEMENTS

Loops are used to repeat blocks of code.

FOR LOOP

Repeats over a sequence of items (e.g., lists, strings, or ranges).

Syntax:

8
for item in sequence:

# Code to execute for each item

statement

Example:

for i in range(3):

print(i)

Explanation:

• The loop iterates over the range (0, 1, 2), printing each number.

WHILE LOOP

Repeats as long as a condition is True.

Syntax:

while condition:

# Code to execute while condition is True

statement

Example:

i = 0

while i < 3:

print(i)

i += 1

Explanation:

• The loop will continue as long as i is less than 3. Each iteration increments i by 1.

11. PATTERN PROGRAMS IN PYTHON

Pattern programs are a common exercise in programming, where you use loops to create various designs of
symbols or numbers. This is a good way to practice control flow and loop concepts.

EXAMPLE: PYRAMID PATTERN

9
rows = 5

for i in range(1, rows + 1):

print(' ' * (rows - i) + '*' * (2 * i - 1))

Explanation:

for i in range(1, rows + 1): Iterates from 1 to the number of rows (5 in this case).

• ' ' * (rows - i): Prints leading spaces to align the stars in a pyramid shape.
• '*' * (2 * i - 1): Prints an increasing number of stars, forming the pyramid.

OUTPUT:

***

*****

*******

*********

PATTERN 1: RIGHT-ANGLED TRIANGLE OF STARS

This pattern forms a right-angled triangle using * symbols.

Pattern:

**

***

****

*****

Program:

rows = 5

for i in range(1, rows + 1):

print('*' * i)

Explanation:

Outer Loop: for i in range(1, rows + 1) starts from 1 and runs until 5.

10
Print Statement: In each iteration, the print('*' * i) prints the * symbol i times.

In the first iteration, i = 1, so it prints *.

In the second iteration, i = 2, so it prints **.

This continues until i = 5, printing *****.

PATTERN 2: INVERTED RIGHT-ANGLED TRIANGLE

This pattern prints an inverted triangle.

Pattern:

*****

****

***

**

Program:

rows = 5

for i in range(rows, 0, -1):

print('*' * i)

Explanation:

Outer Loop: for i in range(rows, 0, -1) starts from 5 and decreases until it reaches 1.

Print Statement: Each iteration prints i stars.

In the first iteration, i = 5, so it prints *****.

In the second iteration, i = 4, so it prints ****.

This continues until i = 1, printing *.

PATTERN 3: PYRAMID OF STARS

This pattern forms a pyramid, with the number of stars increasing in the middle.

Pattern:

11
***

*****

*******

*********

Program:

rows = 5

for i in range(1, rows + 1):

print(' ' * (rows - i) + '*' * (2 * i - 1))

Explanation:

Outer Loop: for i in range(1, rows + 1) controls the rows, starting from 1 and going to 5.

Print Statement:

print(' ' * (rows - i)): Prints leading spaces. For example, in the first row, there are 4 spaces
before the stars to align them centrally.

print('*' * (2 * i - 1)): Prints stars. For example, in the first row, i = 1, so 2 * i - 1 = 1


star is printed. In the second row, i = 2, so 3 stars are printed, and so on.

PATTERN 4: INVERTED PYRAMID OF STARS

This pattern forms an inverted pyramid.

Pattern:

*********

*******

*****

***

Program:

rows = 5

for i in range(rows, 0, -1):

print(' ' * (rows - i) + '*' * (2 * i - 1))

Explanation:

12
Outer Loop: for i in range(rows, 0, -1) controls the rows, starting from 5 and decreasing until 1.

Print Statement:

print(' ' * (rows - i)): Prints leading spaces to center the stars.

print('*' * (2 * i - 1)): Prints stars. For example, in the first row, i = 5, so 9 stars are printed. In
the second row, i = 4, so 7 stars are printed, and so on.

PATTERN 5: DIAMOND OF STARS

This pattern combines the pyramid and inverted pyramid to form a diamond shape.

Pattern:

***

*****

*******

*********

*******

*****

***

Program:

rows = 5

# Upper Pyramid

for i in range(1, rows + 1):

print(' ' * (rows - i) + '*' * (2 * i - 1))

# Lower Inverted Pyramid

for i in range(rows - 1, 0, -1):

print(' ' * (rows - i) + '*' * (2 * i - 1))

Explanation:

Upper Pyramid: The first loop constructs the upper part of the diamond using the same logic as the previous
pyramid example.

13
Lower Inverted Pyramid: The second loop constructs the lower part of the diamond using the inverted
pyramid logic. We use range(rows - 1, 0, -1) because the middle row shouldn't be repeated.

PATTERN 6: RIGHT-ANGLED NUMBER TRIANGLE

Instead of stars, this pattern uses numbers.

Pattern:

12

123

1234

12345

Program:

rows = 5

for i in range(1, rows + 1):

for j in range(1, i + 1):

print(j, end="")

print()

Explanation:

Outer Loop: for i in range(1, rows + 1) controls the rows.

Inner Loop: for j in range(1, i + 1) prints numbers from 1 to i.

In the first row, i = 1, so it prints 1.

In the second row, i = 2, so it prints 12.

This continues until the last row prints 12345.

PATTERN 7: PASCAL’S TRIANGLE

Pascal's triangle is a triangular array where each entry is the sum of the two directly above it.

Pattern:

1 1

14
1 2 1

1 3 3 1

1 4 6 4 1

Program:

rows = 5

for i in range(rows):

# Print leading spaces for alignment

print(' ' * (rows - i), end='')

# Calculate and print Pascal's triangle numbers

num = 1

for j in range(i + 1):

print(num, end=' ')

num = num * (i - j) // (j + 1)

print()

Explanation:

Outer Loop: for i in range(rows) controls the rows.

Inner Loop: The inner loop calculates the Pascal's triangle numbers using the formula:

num = num * (i - j) // (j + 1)

Spaces: The spaces are added for alignment to make it look like a triangle.

PATTERN 8: HOLLOW SQUARE

This pattern prints a hollow square with a border of stars.

Pattern:

*****

* *

* *

* *

*****

15
Program:

rows = 5

for i in range(rows):

if i == 0 or i == rows - 1:

print('*' * rows)

else:

print('*' + ' ' * (rows - 2) + '*')

Explanation:

First and Last Row: if i == 0 or i == rows - 1: prints a full line of stars (*).

Middle Rows: For the rows in between, it prints a * at the beginning and end, with spaces in the middle.

PATTERN 9: HOLLOW PYRAMID

This pattern prints a hollow pyramid of stars.

Pattern:

* *

* *

* *

*********

Program:

rows = 5

for i in range(1, rows + 1):

if i == rows:

print('*' * (2 * i - 1))

else:

print(' ' * (rows - i) + '*' + ' ' * (2 * i - 3) + '*' * (i != 1))

Explanation:

Outer Loop: Controls the rows.

If Condition:

16
If it’s the last row, print a full row of stars.

Otherwise, print stars at the beginning and end of the row, with spaces in between to create the hollow effect.

CONCLUSION

Python provides a rich set of control flow tools, making it versatile and beginner-friendly. Here's a summary of
the key points:

• if, else, and elif: Enable decision-making in your program.


• Nested if statements: Allow for more complex decision trees.
• for and while loops: Help repeat tasks, either a set number of times or while a condition is true.
• Transfer statements: Change the flow of loops (break, continue, pass).

17

You might also like