INTRO   O

PROBLEM SOLVING AND

PROGRAMMING IN PYTHON

 

(use the Space key to navigate through all slides)

Prof. Andrea Gallegati
tuj81353@temple.edu

Prof. Dario Abbondanza
tuk96119@temple.edu

CIS 1051 - FOR LOOP

Understanding the

statement

 REPEATING Actions in Code

for

Every day life, we often repeat tasks:

 

  • Checking emails (one by one).
  • Taking steps while walking.
  • Counting down before a rocket launch.

Wouldn’t it be GREAT
to make Python

repeat actions for us?

That’s exactly what
a for loop does!

Syntax:

write Python programs that
repeat the same code execution

for variable in sequence:
    # Code to repeat 
	pass

it  allows us to execute a block of code multiple times, iterating over items in a sequence.

  • The variable takes one value from the sequence at a time.
  • The loop body runs once per item in the sequence.

Example: Printing Names in a List

names = ["Alice", "Bob", "Charlie"]

for name in names:
    print(name)
  1. The loop picks the first name 
    ("Alice") and prints it.

  2. Then, it picks "Bob" ...

  3. Then, ...

Each iteration automatically
moves to the next item!

Example: Looping Over a String

word = "Python"

for letter in word:
    print(letter)

What Happens?

The loop prints each letter
one at a time!
 

(a string is also a sequence of characters)

Using the range() Function

# Starts at 1, stops before 6

for num in range(1, 6):
    print(num)

How It Works

  • range(1, 6) generates
    a List [1, 2, 3, 4, 5]

We can use range(n) to repeat an action n times.

# `_` is a placeholder (we 
# don't need the variable)

for _ in range(3): 
    print("Hello!")

Using for With if to find even numbers

Operator Meaning Example (x = 10, y = 5)
> Greater than x > y True
< Less than x < y → False
>= Greater than or equal to x >= 10 → True
<= Less than or equal to y <= 5 → True
== Equal to x == y → False
!= Not equal to x != y → True

in Conditions

Example: Grading Exams

import random

# Define the list of scores
grades = [20, 45, 56, 68, 75, 100]

# Pick a random value from the list
score = random.choice(grades)

# Print the random score
print("Score: " + str(score))

if score >= 60:
    print("Congratulations!")
    print(" You passed the exam.")

The else Statement

an alternative

import random

# Define the range of possible scores
min_score = 20
max_score = 100

# Pick a random score
score = random.randint(min_score, 
                       max_score)

# Print the random score
print("Score: " + str(score))

# Check if score meets the condition
if score >= 60:
    message_1 = "Congratulations! "
    message_2 = "You passed the exam."

else:
    message_1 = "Sorry, you didn't pass."
    message_2 = " Try Again!"

print(message_1 + message_2)

The elif Statement

multiple conditions

import random

# Define the range of possible scores
min_score = 20
max_score = 100

# Pick a random score
score = random.randint(min_score, 
                       max_score)

# Print the random score and
# the corresponding Grade

if score >= 90:
    print("Grade: A")
elif score >= 80:
    print("Grade: B")
elif score >= 70:
    print("Grade: C")
else:
    print("Grade: F")

What Happens?

  • If score >= 90, it prints "Grade: A".
  • Otherwise, it checks if score >= 80... and so forth!

 

The program stops checking after the first True condition.

Operator Meaning Example (x = 8, y = 5)
and Both conditions must
be True
x > 5 and y > 2 
True
or At least one condition
is True
x > 10 or y < 10 
True
not Negates the condition not (x > 10) → True

Logical operators

Age Verification for Discount

age = 17
is_student = True

if age < 18 and is_student:
    print("You get a student discount!")

Checking for Even Numbers

number = 7

if number % 2 == 0:
    print(str(number) + " is even.")
else:
    print(str(number) + " is odd.")

NESTED if Statements

age = 20
citizenship = "US"

if age >= 18:
    if citizenship == "US":
        print("You are eligible to vote.")
    else:
        print("You must be a US citizen to vote.")
else:
    print("You must be at least 18 to vote.")

How It Works

  1. Checks if age >= 18 is True.
  2. Checks if the person is a US citizen is True.
  3. If both are True, it prints "You are eligible to vote."
    Otherwise, it prints "You must be a US citizen."
  4. If age < 18, it prints "You must be at least 18 to vote."

Recap

  • if statement executes a code block (condition True).
  • else statement provides an alternative action.
  • elif statement allows multiple conditions.
     
  • Comparison operators (==, !=, >, <, >=, <=) 
    help define conditions.
  • Logical operators (and, or, not) 
    combine multiple conditions.
     
  • Nested if statements allow deeper decision-making.

Try It Yourself!

write a Python program that checks the temperature and prints different messages

temperature = 15  # Try changing this value!

if temperature > 30:
    print("It's hot outside! Stay hydrated.")
elif temperature > 20:
    print("The weather is nice and warm.")
elif temperature > 10:
    print("It's a bit chilly, grab a sweater.")
else:
    print("Brrr! It's freezing outside!")

Great Work! 🎉

Now you understand if statements and conditional logic in Python!


Ready to try them out? 🚀

This was crafted with

A Framework created by Hakim El Hattab and contributors
to make stunning HTML presentations

for-loop

By Andrea Gallegati