Chapter 3
Chapter 3
Chapter 3
Abstract
This guide offers a comprehensive overview designed for beginners stepping into the world of
Python programming. The document navigates through the foundational concepts of computer
systems, focusing on hardware and software components, and delves into the intricacies of
programming languages, with a spotlight on Python. Readers will be introduced to the language's
history, features, applications, and its distinction for simplicity and versatility. The document
provides a blend of theoretical insights and practical examples to foster a robust learning
experience, preparing readers to explore the expansive world of opportunities that Python
programming unveils. Whether the reader aims to delve into web development, data analysis,
artificial intelligence, or simply seeks to acquire a new skill, this guide serves as a stepping stone
into the realm of Python programming.
neili zakaria
Neili Zakaria
Python
Chapter 3: Control Flow in Python (02 weeks)
A simple table explaining the basics of Boolean logic, which typically involves the
logical operators: AND, OR, and NOT.
Explanation:
AND: This operator is used to ensure that a set of conditions are all true at the same time. For
example, if (is_sunny AND is_weekend) would only be true if it is both sunny and the day is a
weekend.
OR: This operator is used when you need any one of multiple conditions to be true. For example,
if (is_sunny OR is_holiday) would be true if either it is sunny, or it is a holiday, or both.
NOT: This operator is used to reverse the logical state of its operand. If a condition is true, then
NOT will make it false; if it is false, NOT will make it true. For example, if NOT is_raining would
be true if it is not raining.
Neili Zakaria
Example:
Let's consider a practical example to understand these operators:
Explanation:
Imagine you are trying to decide what to do on your weekend. You're considering going hiking, to
the cinema, or swimming.
1. Is it the weekend?
2. Do you have tickets for an event?
3. Is it raining outside?
1. Going Hiking:
• To go hiking, it should be the weekend, and it should not be raining.
• We use the and logical operator because both conditions must be true to go hiking.
• We use not with is_raining because we want to go hiking only when it's not raining.
Neili Zakaria
• If it's the weekend (True) and not raining (not is_raining), then can_go_hiking will be
True. Otherwise, it will be False.
• In our scenario, since it is raining, we cannot go hiking, and the code prints False.
3. Going Swimming:
• For swimming, let's assume you can't go if all the conditions are true: It's the weekend, you
have tickets for a swimming event, and it's not raining.
• Here we are using not with a combination of conditions wrapped in parentheses.
• If all conditions inside the parentheses are True, the entire not (...) expression becomes
False.
• In our case, you don't have tickets, so the inside condition is False, making
cannot_go_swimming True.
• The code prints True, which paradoxically means we cannot go swimming because of the
negative phrasing of the variable.
By using variables and logical operators (and, or, not), we can make decisions based on multiple
conditions in Python, much like making decisions in real life. The print statements are just a way
for the program to tell us the outcome of our decision-making process.
Neili Zakaria
Section 3.1: Conditional Statements
Conditional statements are the backbone of decision-making in Python. They allow a program to
execute certain blocks of code based on whether a condition is true or not.
Example:
This example checks if the temperature is greater than 25 degrees. If it is, it prints out a message
about the hot day.
Example:
The elif (short for else if) clause is used to check multiple expressions for TRUE and execute a
block of code as soon as one of the conditions evaluates to TRUE.
Neili Zakaria
Example:
Example:
Example:
Neili Zakaria
This uses the and operator to ensure that both conditions must be true for the whole condition to
be true. The or operator can be used when only one of the conditions must be true, and not can be
used to negate a condition.
Keep in Mind:
• Pay attention to indentation, as Python uses indentation to define the scope in the code.
• Conditions are always followed by a colon (:).
• Remember to use comparison operators (==, !=, >, <, >=, <=) to compare values in
conditions.
•
Background:
A movie theater charges different ticket prices depending on a person's age and the day of the
week. On regular days, children under the age of 12 receive a discount, and seniors (people aged
60 and over) receive a discount. On Tuesdays, there is an additional discount for everyone.
Ticket Prices:
Task:
Write a Python program that prompts the user for their age and the current day of the week. The
program should then output the price of the movie ticket.
Neili Zakaria
Requirements:
• Use if, elif, and else statements to determine the ticket price based on the input.
• Consider all possible scenarios: a child on a Tuesday, a senior on a Tuesday, and a regular
price for any other age and day combination.
• Print out the final ticket price in a format such as: "Your ticket price is: $X.XX"
Hints:
• Assume the input for the day of the week will be a string, such as "Monday", "Tuesday",
etc.
• Use input() to collect user data.
• Convert the age input to an integer before performing comparisons.
• Remember to consider case sensitivity when comparing the day of the week.
This code snippet takes into consideration the age of the person and the day of the week to calculate
the price of the movie ticket. If it's Tuesday, everyone gets the Tuesday discount price, regardless
Neili Zakaria
of age. If it's not Tuesday, children under 12 and seniors aged 60 or over get their respective
discounts. Anyone else pays the regular price. The use of .lower() ensures that the program
correctly identifies Tuesdays regardless of how the user inputs the day of the week (e.g., "tuesday",
Basic Structure:
How It Works:
• The condition is checked before the execution of the loop body.
• If the condition evaluates to True, the code inside the loop's body is executed.
• After the code execution, the condition is checked again, and this process continues until
the condition becomes False.
• If the condition is False initially, the body of the loop is not executed at all.
Infinite Loops:
If the condition never becomes False, the while loop will continue indefinitely, resulting in an
infinite loop.
Neili Zakaria
Example 1: Basic while Loop
• This loop will print "Count is X" (where X is a number from 0 to 4) and increment
count by 1 after each iteration. The loop stops when count reaches 5.
• Here, the loop continues to ask the user to type 'exit'. If the user types 'exit', keep_looping
becomes False, and the loop stops.
The number variable is incremented each time the loop runs. Without number += 1, the condition
number <= 10 would always be true, resulting in an infinite loop.
Neili Zakaria
Important Points to Remember:
• Ensure that the loop has a way to stop. Otherwise, you might create an infinite loop.
• Be cautious with the conditions used in while loops. The variables involved in the condition
must be initialized before the loop and usually updated within the loop.
• while loops are ideal when the number of iterations is not known in advance and depends
on some conditions evaluated during each iteration.
Using break:
Place the break statement within a conditional (if) block to stop the loop based on a specific
condition.
Neili Zakaria
Example
Using continue
Skipping the Rest of the Loop's Body and Returning to the Condition
The continue statement skips the rest of the loop's current iteration and returns to the loop's
condition. It’s used to skip over part of a loop when a certain condition is met.
Place the continue statement within a conditional (if) block to skip the rest of the loop under
specific circumstances.
Example
In this example, continue is used to skip even numbers. The loop prints only odd numbers
between 0 and 9.
Neili Zakaria
Key Takeaways:
Infinite Loops: Ensure that your loops have a clear exit condition to prevent them from running
indefinitely.
Using break: Utilize the break statement to exit a loop immediately under certain conditions.
Using continue: Employ the continue statement to skip over certain iterations of a loop while
letting the loop continue to run.
Basic Structure:
This loop will print each fruit in the fruits list: apple, banana, and cherry.
Neili Zakaria
Iterating Over a String:
This loop will print numbers from 0 to 4. The range(5) function generates a sequence of numbers
from 0 up to (but not including) 5.
the sequence with each iteration of the loop. It can be used within the loop to access or perform
• Here, index is used to iterate over the indices of the fruits list, and fruits[index] accesses
each fruit.
Neili Zakaria
Modifying Values in a Sequence:
Nested Loops:
Nested loops involve placing one loop inside another loop. This structure allows you to perform
more complex iterations and is particularly useful in scenarios where you need to work with
Neili Zakaria
Using Loops Inside Loops
When It's Useful:
Nested loops are commonly used for tasks that require iterating over multiple dimensions, such as
matrices, grids, or more complex data structures.
They are also used in algorithms that require a series of nested operations, like sorting or searching
in multi-dimensional arrays.
Basic Structure:
• This nested loop will iterate through each row of the matrix, and then through each element
Neili Zakaria
• Here, the outer loop iterates over each word, and the inner loop iterates over each letter in
conjunction with for loops to iterate over a sequence for a set number of times.
Syntax Variations:
range(stop): Generates numbers from 0 to stop-1.
range(start, stop): Generates numbers from start to stop-1.
range(start, stop, step): Generates numbers from start to stop-1, incrementing by step.
Neili Zakaria
Example with Start and Stop:
• This loop will run exactly 3 times, printing "Iteration 1", "Iteration 2", and "Iteration
3".
Neili Zakaria
Example: Indexing Through a List:
• This uses range() to create indices for iterating through the colors list, allowing access to
List Comprehensions:
List comprehensions in Python provide a concise way to create lists. It's a more streamlined and
Basic Syntax:
Neili Zakaria
Example: Creating a List of Squares:
• This list comprehension generates a list of square numbers from 0 to 9. It's equivalent to
‘squares = []; for x in range(10): squares.append(x**2)’
• This creates a list of squares of even numbers only. The if clause filters out numbers that
are not even.
بطريقة موجزة لتعيين قيمة لمتغير، والتي تُعرف غالبًا باسم العوامل الثالثية في لغات البرمجة األخرى،تسمح التعبيرات الشرطية
if-else هذه عبارة عن تعيينات شرطية مكونة من سطر واحد والتي غالبًا ما تكون أكثر انسيابية من كتلة.بنا ًء على الشرط
.متعددة األسطر
Basic Syntax:
Neili Zakaria
Example of a Conditional Expression:
executed, nothing happens, but it avoids getting an error when empty code is not allowed.
Empty code blocks (like functions or loops) are not permissible in Python, so pass can be used to
Use of pass:
Neili Zakaria
• In each of these examples, pass is used to indicate a place where code will or can be added
in the future.
Neili Zakaria