0% found this document useful (0 votes)
5 views20 pages

Python Conditions and Loops Overview

The document is a project charter for a Python programming project focused on implementing control structures, specifically conditional statements and loops. It outlines the project goal, scope, structure, and includes explanations of loops and conditions in Python, along with their importance and usage. Additionally, it provides examples and procedures for implementing these programming concepts.

Uploaded by

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

Python Conditions and Loops Overview

The document is a project charter for a Python programming project focused on implementing control structures, specifically conditional statements and loops. It outlines the project goal, scope, structure, and includes explanations of loops and conditions in Python, along with their importance and usage. Additionally, it provides examples and procedures for implementing these programming concepts.

Uploaded by

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

1

Project Charter
Project Name Introduction to Control Structure
Project Team Faculty Advisor: Muthal Raj Sir
Team Members:
– Aaruush
– Gokul
– Kiran Karthik
Project Goal implement a Python-based solution using
conditional statements and looping
statements
Project Description This project explores Python’s conditions
and loops to develop a program

Project Scope This project focuses on basic Python


programming with conditions and loops. It
includes:
 Focus on Python programming
 Use of conditional statements and
loops
 Simple user input/output
interactions
 Well-commented code and
structured function
 Simple logic-based programs

Project Structure The Subtitles which this project is focused


on:
 Mind Map
 Introduction
 4W Canvas
 How to Handle
 Basic procedure to Implement
 Uses of Loops and Conditions
 Example Programs
3

Mind Map
4

Introduction

Loop
“In programming, we often need to perform a task repeatedly — whether it’s printing
numbers, checking conditions, or processing data. Instead of writing the same code
again and again, we use loops to make our programs efficient and smart.”

Python provides two main types of loops:

 for loop – used when the number of repetitions is known.

 while loop – used when the number of repetitions is not known, but depends on a
condition.

Example,

Think of a loop like washing 10 plates: instead of saying "wash plate 1", "wash plate 2", ...,
you just say:
"Repeat washing until all 10 plates are clean."
That's what a loop does in code!

We use loop for:

 Avoid code repetition


 Make code cleaner and shorter
 Useful for data processing, automation, searching, and more

Python also supports loop control statements like:

 break: exit the loop early

 continue: skip current iteration

 else: execute after loop finishes naturally


5

Conditions
“Programming is not just about doing things — it's about making decisions."
Conditional statements allow a program to choose different paths of execution based on
whether a condition is true or false.

Python Conditional Keywords:

 if – checks a condition

 elif – checks another condition if the previous was false

 else – executes when all previous conditions are false

Example,
Think of a traffic signal:

 If the light is green, you go.

 Elif it's yellow, you slow down.

 Else (if it's red), you stop.

That’s exactly how conditions work in Python — making smart decisions based on different
situations.

Conditions importance:

 Add intelligence to your programs


 Help create interactive and dynamic outputs
 Allow multiple outcomes in one program

Conditions develop computer program:

 They Enable Decision-Making


 They Allow Flexibility
 They Simulate Human-Like Logic
 They Help with Validation and Control
6

4W Canvas
What?
1. What happens if the condition in an if statement is false?

If the condition in an if statement is false, the code


block immediately following the if statement is skipped,
and the program proceeds to the next statement after
the if block or the corresponding else or elif block if they

2. What is the difference between if-elif-else and nested if-else?

if-elif-else:
This structure is used when you have multiple
conditions to check sequentially and only one block of
code (first one whose condition evaluates to true)
will be executed. It's a single decision structure.

Nested-if-else:
This involves placing
An if or if-else statement inside another if or else block. This is
used when a condition depends on the outcome of a
previous condition, creating a hierarchical decision
structure.

3. What is the difference between a for loop and a while loop?

For loop:
Typically used when the number of iterations is known
or can be determined beforehand (e.g., iterating through a list,
range, or string). It iterates over a sequence of items.
While loop:
Used when the number of iterations is unknown
and the loop continues as long as a specified condition remains
true. It's condition-controlled.

4. . What are nested loops

Nested loops are loops within loops, meaning one loop is


placed inside the body of another loop. The inner loop executes
completely for each iteration of the outer loop. They are
commonly used for tasks like processing two-dimensional data
structures (e.g., matrices) or generating combinations.
7

Where?
1. Where do we commonly use nested if-else conditions?

Nested if-else conditions are commonly used when you


need to check multiple conditions sequentially, were the
evaluation of a subsequent condition depends on the
outcome of a preceding one. particularly used in decision
making process and input validation.

2. Where will the program jump if the if condition is false?

If an if condition is false, the program will jump to the


code block associated with the else statement (if one exists)
or, if there is no else block, it will jump to the statement
immediately following the if or if-else block.

3. . Where can you place an if condition inside a loop?

You can place an if condition anywhere inside the body of


a loop (e.g., for, while, do-while). This allows you to perform
conditional actions or checks during each iteration of the
loop.

4. Where should you initialize a counter variable when using a while loop?

When using a while loop, you should initialize a counter


variable before the while loop begins. This ensures that the
counter has a starting value before the loop's condition is
evaluated for the first time.
8

When?
1. When should we use elif instead of multiple if statements?

You should use elif when you have multiple conditions


that are mutually exclusive, meaning only one of them can
be true at a time. This ensures that only one block of code
is executed, even if multiple conditions might technically
evaluate to true if they were separate if statements. It also
improves readability and efficiency by preventing
unnecessary checks after a condition is met.

2. When do we use nested if-else structures?

Nested if-else structures are used when a condition


depends on the outcome of another condition. This means
you need to check an inner condition only if an outer
Condition is true. For example, you might check if a user is
logged in (outer condition) and then, if they are, check them
specific user role (inner condition) to determine access.

3. When should you use a while loop instead of a for loop?

You should use a while loop when the number of


iterations are not known beforehand, and the loop continues
as long as a certain condition remains true. A for loop is
typically used when you know the number of iterations in
advance, such as iterating over elements in a sequencer
a specific range.

4. When should the loop condition be updated to avoid errors?

The loop condition in a while loop must be updated


within the loop's body to ensure that the condition
eventually becomes false, preventing an infinite loop. This
update should happen at a point where it logically
progresses towards the termination of the loop, such as
incrementing/decrementing a counter or modifying a flag
variable.
9

Why?
1. Why is indentation important in an if-else block?

Indentation in an if-else block is crucial for readability and


Understanding the code's structure. In some languages (like
Python), it's syntactically significant and defines the scope of
The if and else blocks, directly affecting program execution. In
others, while not strictly required for execution, it vastly improves
code clarity and maintainability, making it easier for developers
to follow the logical flow and identify errors.

2. Why is nesting if-else sometimes a bad practice?

Excessive nesting of if-else statements can lead to "callback


hell" or "pyramid of doom, "making the code difficult to read,
debug, and maintain. It increases complexity, reduces
readability, and can make it harder to reason about the
program's logic, potentially introducing subtle bugs.

3. Why do we use loops in programming?

Loops are used in programming to execute a block of code


repeatedly. This is essential fort asks that involve iteration, such
as processing elements in a list, repeating a calculation a specific
number of times, or continuously checking for user input until a
certain condition is met.

4. Why can infinite loops be dangerous in a program?

Infinite loops occur when the loop's termination condition is


never met, causing the program to execute the loop's body
indefinitely. This can lead to resource exhaustion (e.g., CPU
cycles, memory), making the program unresponsive or even
causing it to crash. In some cases, it can also freeze the entire
system, requiring a forced restart.
10

How to Handle Loops & Conditions

1. How do conditional statements help in decision-making in Python?

Conditional statements (like if, elif, and else) allow a


program to execute different blocks of code based on
whether specified conditions are true or false. This enables
decision-making by controlling the flow of execution,
allowing the program to respond dynamically to different
inputs or situations.

2. How does a for loop work when iterating through a list?

When a for loop iterates through a list in Python, it


assigns each element of the list, one by one, to a
temporary variable within the loop's scope. The code
inside the loop then executes for each element, allowing
you to perform operations on each it’s in the list
sequentially.

3. How does a for loop work in Python?

A for loop in Python is used for iterating over a sequence


(like a list, tuple, string, or range) or other Iterable
objects. It repeatedly executes a block of code for each
item in the sequence, providing a concise way to perform
repetitive tasks or process collections of data.

4. How can we use nested if statements inside loops to control complex conditions?

Nested if statements inside loops allow for the


evaluation of multiple, hierarchical conditions during
iteration. This is useful for handling complex scenarios
where a decision depends on an initial condition being
met, and then further conditions need to be checked
within that context. For example, you might iterate
through a list of objects and, foreach object, check
multiple properties using nested if statements to
determine specific actions.
11

Procedure & Rules


Procedure:
CONDITIONAL STATEMENT:
1. Start at the if – Python checks the first condition.

2. If if is True, it runs that block and exits the entire structure.

3. If if is False, it moves to the first elif.

4. It checks each elif in order, executing the first one that's True.

5. Only one block runs – the first one with a True condition.

6. If none of the if or elif conditions are True, it runs the else block.

7. If there's no else, and no condition is True, the whole block is skipped.

Example,

x = 75

if x > 90:

("Excellent")

elif x > 75:

("Good")

elif x > 50:

("Average")

else:

("Fail")
12

L OOPING S TATEMENT :
Feature ‘For’ Loop ‘While’ Loop

You know how many times to You don’t know how many times to
Used when
repeat repeat

Structure for variable in sequence: while condition:

Sequence needed? Yes (list, range, string, etc.) No (just a condition)

Condition check Built-in with the sequence Explicitly checked

Variable update Automatic Manual (must update in loop)

Risk of infinite
Very low High if condition is never False
loop

Example for i in range(5): while i < 5:

Use case Iterating through items, counting Repeating until a condition is met

Example,

‘For’ Loop ‘While’ Loop

Input: Input:
for i in range(3): i=0
print(i) while i < 3:
print(i)
i += 1

Output: Output:
0 0
1 1
2 2

Rules:
13

CONDITIONAL STATEMENT:
1. Every conditional structure must begin with an if statement.
2. The condition inside if, elif must return True or False.
3. You can have zero or more elif blocks.
4. Only one else is allowed
5. Don't forget the colon at the end of if, elif, and else lines.
6. Indentation is mandatory
7. The order of conditions matters.

8. One if-else can be inside another (called nested if-else).

LOOPING STATEMENT:
1. Indentation is required
2. Use break, continue, if-else if necessary .
3. Use range in ‘for loop’.
4. Condition must be updated manually inside the loop in ‘while loop’.
5. A loop repeats a block of code multiple times.

Uses Of Conditional & Looping


Statement
14

CONDITIONAL STATEMENT:
Use Case Description

Allows the program to choose between different paths based


Decision Making
on a condition.

Menu Selection Systems Used in apps or games to choose options from menus.

Grading / Evaluation
Used to classify results (e.g., if marks > 90 → A grade).
Systems

Applies logic like: if it's raining, take an umbrella (like real


Real-Life Conditions
decisions).

Authentication Logic Checks usernames, passwords, and access rights.

Game Rules and Logic Helps make decisions like who wins, loses, or gets points.

LOOPING STATEMENT:
Use Case Description

Repeating Tasks Loops help repeat a block of code without rewriting it many
Automatically times.

Traversing Data Used to iterate over lists, strings, tuples, dictionaries, etc.

Useful for counting items, summing numbers, finding


Counting and Calculations
averages, etc.

Generating Patterns Helpful in printing stars, number pyramids, or shapes.

Automating Repetitive Logic Automates tasks like sending emails, checking values, etc.

Loops help in finding items that match a condition inside a


Searching and Filtering Data
list.

Used in menus that keep repeating until user chooses to


Menu-Driven Programs
exit.

Games and Animations Keeps the game running until it's over (like game loops).

Helps simulate real-time processes like stopwatches, clocks,


Simulations / Timers
etc.
15

Example Programs
1. Check if a number is even or odd?
Input:

# Program to check if a number is even or odd

# Take input from user

num = (input("Enter a number: "))

# Check if the number is even or odd using modulus operator

if num % 2 == 0:

(f "{num} is an even number.")

else:

(f "{num} is an odd number.")

Output:

Enter a number: 7

7 is an odd number.

2. Use if-else to decide pass/fail from marks?

Input:

# Program to decide pass or fail based on marks

# Take input from the user

marks = int(input("Enter your marks (out of 100): "))

# Use if-else to check pass/fail


16

if marks >= 40:

print("You passed! ")

else:

print("You failed. 😞 Better luck next time.")

Output:

Enter your marks (out of 100): 75

You passed!

3. Use if-else and for loop to remove punctuations?

Input:

str1=",./;'[]!^*()&$@?{}\|''"""
str2=str(input("enter the sentence: "))
def rmv_punc(s,p=str1):

#remove the punctuation


for i in s:
if i in p:

# check if punctuation comes in the string if yes remove


s = [Link](i, '')
print(s)
rmv_punc(str2)

Output:

Enter the sentence: Hello!

Hello

4. Check if a number is positive, negative, or zero (with nested if)?

Input:

num = int(input("Enter a number: "))

# get the number from user

if num >= 0:

if num == 0:
17

# check if number is zero or greater

print("The number is zero.")

else:

print("The number is positive.")

else:

print("The number is negative.")

Output:

Enter the number: 7

The number is positive

5. Grade Evaluation Using Nested if ?

Input:

marks = int(input("Enter your marks (0 to 100): "))

if marks >= 0 and marks <= 100:

if marks >= 90:

print("Grade: A+")
18

elif marks >= 80:

print("Grade: A")

elif marks >= 70:

print("Grade: B")

elif marks >= 60:

print("Grade: C")

elif marks >= 40:

print("Grade: D")

else:

print("Grade: F (Fail)")

else:

print("Invalid marks entered!")

Output:

Enter your marks (0 to 100): 64

Grade B

6. Count Vowels and Consonants in a Sentence ?

Input:

sentence = input("Enter a sentence: ")

vowels = "aeiouAEIOU"

vowel_count = 0

consonant_count = 0
19

for char in sentence:

if [Link]():

if char in vowels:

vowel_count += 1

else:

consonant_count += 1

print(f"Vowels: {vowel_count}")

print(f"Consonants: {consonant_count}")

Output:

Enter the sentence: My name is Kiran

Vowels: 5

Consonant: 8
20

You might also like