0% found this document useful (0 votes)
12 views

Week 2-3 Control Structures and Loops

Uploaded by

do.ebrarr
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views

Week 2-3 Control Structures and Loops

Uploaded by

do.ebrarr
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 21

CENG103 - COMPUTER PROGRAMMING

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

if temperature > 25: # If the temperature is greater than 25


print("It's hot today!") # Print a message indicating it's hot
print("Wear light clothes.") # Suggest wearing light clothes
drink_water = True # Set a variable to indicate that drinking water is necessary
if drink_water: # If the drink_water variable is True
print("Make sure to stay hydrated!") # Print a reminder to drink water
else: # If the temperature is 25 or less
print("The weather is moderate.") # Print a message indicating the weather is moderate

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

if x > 0: if x > 0: if x > 0: if x > 0:


print print print ("Positive") print ("Positive")
("Positive") ("Positive") print ("// +
print ("// + print + //") print ("// ++ //")
+ //") ("// ++ //") elif x < 0:
elif x < 0: elif x < 0: print elif x < 0:
print print ("Negative") print
("Negative") ("Negative") print ("// + ("Negative")
print ("// + print ("// ++ //") + //") print
+ //") else: ("// ++ //")
else: else: print ("Zero") else:
printbackgrounds
The codes with green printthey
("Zero") must be aligned since ("Zero")
are a group. print ("// + print ("Zero")
print
The codes with blue ("// +
backgrounds print
must be aligned since ("//are
they ++ //")
a group. + //") print ("// ++ //")
+ //") print("test-1")
A Syntax OK, No problem, good coding
print("test-2") print("test-1")
print("test-2")
B Syntax ERROR, group codes must be at the same vertical
print("test-3")
C Syntax Ok, No problem, good coding print("test-3")
D Syntax Ok, But it is not good coding. elif group codes are not vertically aligned with if and else
INDENTATION EXAMPLE OUTPUTS:

x = -34 x = -34 x = -34 x = -34

if x > 0: if x > 0: if x > 0: if x > 0:


print print print ("Positive") print ("Positive")
("Positive") ("Positive") print ("// +
print ("// + print + //") print ("// ++ //")
+ //") ("// ++ //") elif x < 0:
elif x < 0: elif x < 0: print elif x < 0:
print print ("Negative") print
("Negative") ("Negative") print ("// + ("Negative")
print ("// + print ("// ++ //") + //") print
+ //") else: ("// ++ //")
else: else: print ("Zero") else:
OUTPUT: print ("Zero") OUTPUT: print ("Zero") print ("// + print ("Zero")
print ("// + print ("// ++ //") + //") print ("// ++ //")
+ //") print("test-1")
print("test-2") print("test-1")
OUTPUT: print("test-2")
OUTPU
print("test-3")
T:
print("test-3")
Class Activity - 3

import time

start_time = time.time()
run_duration = 5 # seconds

while (time.time() - start_time) < run_duration:


print("Simulating time-based operation...")
time.sleep(1) # Wait for 1 second in each iteration

print("Time-based operation complete")


Class Activity – 4, part-1
# Ask the user how many subjects they have
num_of_subjects = int(input("How many subject grades will you enter? "))

# Initialize total score to calculate the average


total_score = 0

# Loop to collect grades


for each subject for i in range(num_of_subjects):
score = float(input(f"Enter your grade for subject {i+1} (0-100): "))
# Check if the entered grade is valid
if score < 0 or score > 100:
print("Invalid grade! Please enter a value between 0 and 100.")

score = float(input(f"Please re-enter your grade for subject {i+1}: "))

total_score += score # Update the total score

# Calculate the average grade


average_score = total_score / num_of_subjects
Class Activity – 4, part-2

# Determine the letter grade based on the average


if average_score >= 90:
grade = "A"
elif average_score >= 80:
grade = "B"
elif average_score >= 70:
grade = "C"
elif average_score >= 60:
grade = "D"
elif average_score >= 50:
grade = "E"
else:
grade = "F" # Print the results

print(f"\nYour average score: {average_score:.2f}")


print(f"Your letter grade: {grade}")
Boolean logic: and, or, not operators
AND Operator: OR Operator: NOT Operator:
 True AND True = True  True OR True = True  NOT True = False
 True AND False = False  True OR False = True  NOT False = True
 False AND True = False  False OR True = True
 False AND False = False  False OR False = False

Using operators together:


A = True A = True A = True
(A AND B) OR (C AND NOT B= B= B=
D) False False False
C= C= C = True
False False D=
RESULT: RESULT: ? RESULT: ?
D = True D= False
False False
Boolean Logic Examples
# Both conditions need to be true # At least one condition needs to be true
a = 10 a = 10
b=5 b=2
if a > 5 and b > 3: if a > 5 or b > 3:
print("Both conditions are true!") print("At least one condition is
else: true!")
print("One or both conditions are false.") else:
print("Both conditions are false.")

# More complex conditions combining and & or


a=7
b = 10
c=3
if (a > 5 and b > 8) or c > 5:
print("At least one of the conditions is true!")
else:
print("All conditions are false.")
LOOP CONCEPT
For loops: (Great for Iterating Over Sequences)
Designed to iterate over a finite set of elements, like lists, strings, or ranges.
Each element in the sequence is processed one at a time, making it ideal when you
know the exact number of iterations needed.

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.

While Loops: (Useful When the Number of Iterations Is Unknown)


Keeps running as long as the specified condition is True. This makes it useful in
situations where the exact number of iterations isn't known beforehand, and it
depends on the logic inside the loop.
Use Cases:
 Waiting for user input or some external condition.
 Running loops that depend on variable conditions (e.g., simulating processes or time-based
operations).
For Loop Examples
Lists, Tuples or Dictionaries: Processing elements one by one. Strings: Iterating over each character in a string.

student_grades = {"Alice": 85, "Bob": 90, name = "Python"


"Charlie": 95} for letter in name:
print(letter)
for student, grade in student_grades.items():
print(f"{student} scored {grade}")
Ranges: Running a loop for a specific number of times.

# Loop from 0 to 4 (5 iterations in # Another range example:


total) # range(start, stop, step)
for index in range(5): for index in range(1, 7, 2):
print(index) print("i = ",i)
total += i
print("Total = ",total)
While Loop Example

attempts = 0 Control Keywords:


max_attempts = 3  break
 continue
while attempts < max_attempts:  else

pin = input("Enter your PIN: ")


break: Immediately exits the loop, no further iterations occur.
if pin == "1234":
print("Correct PIN!") continue: Skips the current iteration and jumps to the next one.
break
else:
attempts += 1 else: Executes after the loop completes,
but only if the loop is not terminated by a break.
print("Incorrect, try This is unique to Python and can be used for post-loop actio
again.")
else:
print("Too many failed
attempts!")
Class Activities
Activity-1 :
 Take an integer number from user
 Divide the number by 2 in a loop
 If the result is not integer;
 Decrease the number taken from the user by 1
 Continue to the loop
 If the result is integer;
 Print the result
 Break the loop

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:

1. set a random number to a variable between 1 and 100


(use this code: secret number = random.randint(1, 100), you should write ‘import random’ on the first line )
2. Inform the user: «Welcome to the Number Guessing Game! Guess a number between 1 and 100»
3. Within a loop;
a) Get an integer input from the user.
b) If the guessed number is greater than what we set, display the message: 'Your guess is
HIGH. Try again.’
c) Else If the guessed number is less than what we set, display the message: 'Your guess is
LOW. Try again.’
d) Else display the message: ‘Congratulations! You found the number {secret_number} in
{attempts} attempts’ (You have to count the trials in the loop and show the attempts).
4. Draw the Flowchart

!!! Beware of infinite loop !!!

 Write your codes in a text file or word document


 Upload your homework to Aybuzem until October 10th
 Everyone will run their codes on https://www.online-python.com/
Summary and Next Week's Topics

Recap of Week 2-3:


 Decission making
 Control structure
 Boolean logic
 Loops

Week 4-5:
 Functions
 Modular Programming
 Packages
 Error Handling
Thank You!
Any Question?
[email protected]

You might also like