Week 2-3 Control Structures and Loops
Week 2-3 Control Structures and Loops
26 SEPTEMBER 2024
PREPARED BY BÜLENT
HERDEM
Introduction to Decision-Making in Programs
What is Decision-Making?
Programs need to make decisions based on conditions.
It helps the program choose different paths of execution.
Why is it Important?
Allows for more dynamic and flexible programs.
Essential for user interactions, data processing, and algorithmic decision-making.
Key Concepts:
Conditions: Expressions that evaluate to either True or False.
Control Flow: Directing the program to execute certain blocks of code depending on the
condition.
Real-Life Analogy:
Think of decision-making as choosing what to wear based on the weather:
o If it’s raining, take an umbrella.
o Else, you wear sunglasses.
Control Structure & An Example
if condition:
# Execute this block if condition is True
elif another_condition:
# Execute this block if another_condition is
True
else:
# Execute this block if all conditions are
False
age = 18
if age >= 18:
print("You are eligible to vote.")
else:
print("You are not eligible to
vote.")
Class Activity - 1
x = -34
if x > 0:
print ("Positive") Ternary Conditional Expressions:
elif x < 0:
print ("Negative") x=23
else:
print ("Zero") result = "Positive" if x > 0 else "Negative or
Zero"
print (result)
Class Activity - 2
temperature = 30
Key Point: Indentation: Python uses indentation (spaces or tabs) to define the scope of
control structures like if, else, and elif.
INDENTATION EXAMPLES:
A B C D
x = -34 x = -34 x = -34 x = -34
import time
start_time = time.time()
run_duration = 5 # seconds
Use Cases:
Lists and Arrays: Processing elements one by one.
Strings: Iterating over each character in a string.
Ranges: Running a loop for a specific number of times.
Activity-2 :
Take a string from user in a loop,
if string length <=10 or >=15
Print «please enter min.11, max.14
character »
Continue
else;
Print the length of the string
Break the loop
Class Activity Codes
Activity-1 :
# Get an integer number from the user
user_number = int(input("Enter an integer number: "))
number = user_number
while number > 1:
if number % 2 == 0:
break;
number -= 1
print("The largest power of 2 less than or equal to", user_number, "is", number)
Activity-2 :
while True:
user_input = input("Please enter a string between 11 and 14
characters: ")
if 11 <= len(user_input) <= 14:
print("Your string is", len(user_input), "characters long.")
break
else:
continue
Flowchart Loop Example
Homework time
HW-2: Write a number guessing game:
Week 4-5:
Functions
Modular Programming
Packages
Error Handling
Thank You!
Any Question?
[email protected]