0% found this document useful (0 votes)
4 views22 pages

Python Logic and Control Flow Basics

This document covers key concepts in Python programming, focusing on logic and control flow, including operators, conditional statements, and loops. It outlines learning goals such as using arithmetic and logical operators, writing conditional logic, and automating tasks with loops. Additionally, it emphasizes the importance of indentation in Python syntax and provides hands-on examples for practical understanding.

Uploaded by

Tezendra Thapa
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)
4 views22 pages

Python Logic and Control Flow Basics

This document covers key concepts in Python programming, focusing on logic and control flow, including operators, conditional statements, and loops. It outlines learning goals such as using arithmetic and logical operators, writing conditional logic, and automating tasks with loops. Additionally, it emphasizes the importance of indentation in Python syntax and provides hands-on examples for practical understanding.

Uploaded by

Tezendra Thapa
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

Logic and Control Flow

Topics: Arithmetic, Comparison, and Logical Operators, Conditional Statements (if/elif/else), and
Loops (for).
Learning Goals

By the end of this session, you will be able to:

1. Use Arithmetic, Comparison, and Logical Operators to perform calculations and data evaluation.
2. Write conditional logic using if, elif, and else statements to categorize data.
3. Apply the loop to automate repetitive tasks on a List of data.
4. Understand how Python uses indentation to define blocks of code (a critical syntax rule).
Review: Collections and Use Cases

Quick Review: Which structure for which job?


Warm-up Challenge (Hands-On): Dictionary Access

1. Create a dictionary for a transaction: transaction = {'Item': 'Monitor', 'Price': 300,


'Discount': 0.1}.
2. Calculate the Final_Price and print() it.
Data Output: String Formatting

Purpose: Combining data (variables) with descriptive text for clear reporting and logging.

● When you print(), you often need to show a result ($123.45) along with its label ("Total Revenue is: ").

The Best Method: F-Strings (Formatted String Literals)

● The most modern, readable, and flexible way to format strings.


● Syntax: Precede the string with an f and place the variables directly inside curly braces .
HANDS-ON: Reporting with F-Strings

Scenario: We need to output a clear, consolidated report line after a calculation.

product_id = "A405"

units_sold = 150

revenue = 4500.75

# Task: Print a consolidated report using an f-string

print(f"Product {product_id} sold {units_sold} units, generating ${revenue} in revenue.")


Operators - Part 1: Arithmetic & Comparison

1. Arithmetic Operators (Math)

● Used for calculations (just like Excel formulas).


2. Comparison Operators (Evaluation)

● Used for conditions; always return a Boolean (True or False).


Operators - Part 2: Logical Operators

Used to combine multiple Boolean conditions (the equivalent of AND, OR in SQL WHERE clauses).
HANDS-ON: Combining Conditions

Scenario: A discount applies only if the product is 'Electronics' AND the price is under 500.

category = "Electronics"

price = 450

# Task: Write the logical condition

is_eligible = (category == "Electronics") and (price < 500)

print(is_eligible)
Conditional Statements: if / elif / else

Purpose: To execute different code blocks based on whether a condition is True or False.
CRITICAL SYNTAX: INDENTATION (The Golden Rule)

● The colon : marks the start of a code block (like a traffic light turning yellow).
● Indentation (4 spaces or 1 Tab) defines what code belongs inside the block (the "if" section, the
"elif" section, etc.).
Visualizing the Flow:

score = 85

if score >= 90: # Condition 1: Is score >= 90? (False)

print("A Grade") # SKIP

elif score >= 80: # Condition 2: Is score >= 80? (True)

print("B Grade") # RUN THIS LINE

else: # SKIP (because an earlier condition was True)

print("C Grade")
HANDS-ON: Categorizing Transaction Risk

risk_score = 65

# Task: Assign a Risk Tier

if risk_score > 80:

print("Tier 1: High Risk - Hold Transaction")

elif risk_score > 60: # Checked only if score was NOT > 80

print("Tier 2: Medium Risk - Review Later")

else: # If score is 60 or below

print("Tier 3: Low Risk - Process Now")


Automation with Loops: The for Loop

Purpose: To automate a repetitive action for every item in a collection (List, Tuple, Dictionary, etc.).

● Analogy: Applying the same calculation or filter across an entire column of data.

CRITICAL SYNTAX: The for Loop Structure


DEMO & HANDS-ON: Processing Invoices

Scenario: We need to calculate a 5%

tax for every invoice total in a list.


Combining Logic: if within a for Loop

Purpose: The fundamental pattern for filtering data: Iterate and Filter/Categorize.

● This is the Python way to run a SQL SELECT * FROM Table WHERE Condition.

Concept: The loop gives you access to one item at a time. The if statement decides what to do with that item.
HANDS-ON: Filtering for Actionable Data

Scenario: Loop through sales and print only the amounts that exceed a threshold of 3000 (i.e., the
ones the Sales Manager needs to review).
sales_figures = [1500, 4200, 800, 6500, 2500]
review_threshold = 3000

print("Sales to Review:")

# Loop starts: 'sale' = 1500 (1st run)


for sale in sales_figures:

# IF statement runs for the current 'sale'


if sale > review_threshold:

# This code is double-indented, meaning it only runs


# IF the 'if' condition is TRUE.
print(f"High Sale Amount: ${sale}")

# The loop finishes when all items have been processed.


The while Loop (Condition-Driven)

Structure: while condition is True:

Scenario: We want to keep running a simulation until we hit our target.

Key Takeaway: With while loops, if you forget to change the condition, the loop will run forever (Infinite Loop). Always ensure
the condition will eventually become False!
inventory = 100
sales_target = 80

# The loop keeps running AS LONG AS inventory is ABOVE the


target
while inventory > sales_target:
print(f"Current Inventory: {inventory} - Still
running...")

# CRITICAL: We MUST change the condition inside the loop


inventory = inventory - 5 # Decrease inventory by 5 each
time

print("Inventory is at or below target. Loop stopped."


)
✅ Today We Mastered:

● Operators: Arithmetic, Comparison (==, !=), and Logical (and, or, in).
● Conditional logic: if, elif, and else for data categorization.
● Indentation as Python's mandatory syntax for defining logic blocks.
● Automation with the loop to process collections of data.

You might also like