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

Chapter 3

Download as pdf or txt
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 22

UNDERSTANDING PYTHON: A

COMPREHENSIVE GUIDE FOR


BEGINNERS
From Fundamentals to Advanced Concepts

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.

However, your decision depends on a few conditions:

1. Is it the weekend?
2. Do you have tickets for an event?
3. Is it raining outside?

In this code, we use variables to keep track of these conditions:

is_weekend tells us if it's the weekend.


has_tickets tells us if we have tickets.
is_raining tells us if it is raining.

Now, let's make some decisions based on these conditions:

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.

2. Going to the Cinema:


• To go to the cinema, it just needs to be the weekend or you must have tickets.
• The or logical operator is used because having either of these conditions true is enough.
• Since it is the weekend in our example, can_go_to_cinema will be True, even if we don't
have tickets.

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.

3.1.1: Understanding if Statements


The if statement is the simplest form of control flow statement. It tells the program to execute a
certain block of code only if a specified condition is true.

Example:

This example checks if the temperature is greater than 25 degrees. If it is, it prints out a message
about the hot day.

3.1.2: else and elif Clauses


The else statement can be used to execute a block of code when the condition of the if statement
is not true.

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:

3.1.3: Nested Conditional Statements


You can nest if statements inside another if statement to check for another condition after one
condition resolves as true.

Example:

3.1.4: Boolean Logic


Boolean logic is used to make more complex conditions for if statements that depend on more than
one condition.

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.

Exercise: Movie Ticket Pricing

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:

Regular price: $12.00

Children under 12: $8.00

Seniors (60 and over): $7.00

All tickets on Tuesday: $6.00

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.

Python program solution for the "Movie Ticket Pricing" exercise:

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",

"Tuesday", "TUESDAY", etc.).

3.2: The while Loop


1. Writing while Loops:
While loops are a fundamental part of Python that allow you to execute a block of code repeatedly
as long as a certain condition remains true.

The Structure and Flow of a while Loop

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.

Creating Loops That Run as Long as a Condition is True

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.

Example 2: Using a Boolean Flag

• Here, the loop continues to ask the user to type 'exit'. If the user types 'exit', keep_looping
becomes False, and the loop stops.

Example 3: Avoiding Infinite Loops

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.

3.2.1. Infinite Loops and How to Break Them


Recognizing and Avoiding Infinite Loops
Infinite loops occur when the loop's terminating condition is never met. This can lead to programs
that never terminate on their own and may require external intervention to stop. Recognizing and
preventing such loops is crucial.

Causes of Infinite Loops:

• The loop condition is always True.


• Failure to update the variables involved in the loop condition.

Example of an Infinite Loop:

Using break to Exit a Loop


The break statement provides a way to exit a loop from anywhere within the loop's body, regardless
of the loop's original condition.

Using break:
Place the break statement within a conditional (if) block to stop the loop based on a specific
condition.

Neili Zakaria
Example

This loop will stop running when count becomes 5 or greater.

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.

Section 3.3: The for Loop


Introduction to for Loops:
Iterating Over a Sequence
A for loop in Python is used for iterating over a sequence, which can be a list, a string, a tuple,
a range, or any other iterable object. It allows you to execute a block of code for each item in the
sequence.

Basic Structure:

Iterating Over a List:

This loop will print each fruit in the fruits list: apple, banana, and cherry.

Neili Zakaria
Iterating Over a String:

• Each character in the string "Python" will be printed, one by one.

Iterating Over a Range:

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 Role of the Loop Variable


The loop variable (fruit, letter, number in the above examples) takes the value of the next item in

the sequence with each iteration of the loop. It can be used within the loop to access or perform

operations on the current item.

Example with a List:

• 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:

This loop squares each number in the numbers list.

Key Points to Understand:


• The for loop is a powerful tool for iterating through sequences, making it essential for tasks
like processing items in a list, reading characters in a string, or generating a series of
numbers.
• The loop variable is a placeholder for the current item of the sequence being iterated over,
and it can be named anything.
• Understanding how to use for loops effectively is crucial for writing clean, efficient, and
readable code, especially when dealing with collections of items.

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

multi-dimensional data structures.

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:

Example with Lists:

• This nested loop will iterate through each row of the matrix, and then through each element

in a row, printing the elements in a matrix format.

Example with Strings:

Neili Zakaria
• Here, the outer loop iterates over each word, and the inner loop iterates over each letter in

the current word.

The range() Function


The range() function in Python is used to generate a sequence of numbers, and it is often used in

conjunction with for loops to iterate over a sequence for a set number of times.

Generating Sequences of Numbers with range()


Basic Usage:
• range(n) generates a sequence of numbers from 0 to n-1.
• It's commonly used when you need to perform an action a certain 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.

Example of Basic range():

• This will print numbers from 0 to 4.

Neili Zakaria
Example with Start and Stop:

• This will print numbers from 1 to 5.

Example with Step:

• This will print even numbers from 0 to 8 (0, 2, 4, 6, 8).

Using range() in for Loops for a Set Number of Iterations


Iterating a Set Number of Times:
• The range() function is especially useful when you know in advance how many times
you need to iterate.
Example: Looping a Specific Number of Times:

• 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

each element by its index.

Key Points to Understand:


• The range() function is invaluable for situations where you need to iterate a specific
number of times.
• It's flexible and can be customized with different start, stop, and step values to suit various
iteration needs.
• When used with for loops, range() provides a clear and concise way to control the number
of loop iterations, making your loops more predictable and manageable.

List Comprehensions:
List comprehensions in Python provide a concise way to create lists. It's a more streamlined and

readable alternative to creating lists using for loops.

Writing Concise for Loops to Generate Lists


Basic Idea:
• A list comprehension consists of brackets containing an expression followed by a for
clause, then zero or more for or if clauses.
• The expression can be anything, meaning you can put in all kinds of objects in lists.
• The result will be a new list resulting from evaluating the expression in the context of the
for and if clauses which follow it.

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)’

Example with Conditional Logic:

• This creates a list of squares of even numbers only. The if clause filters out numbers that
are not even.

Section 3.4: Control Flow Tools


Conditional Expressions (Ternary Operators)
Conditional expressions, often known as ternary operators in other programming languages, allow
for a concise way to assign a value to a variable based on a condition. These are one-line
conditional assignments that are often more streamlined than a multi-line if-else block.

‫ بطريقة موجزة لتعيين قيمة لمتغير‬،‫ والتي تُعرف غالبًا باسم العوامل الثالثية في لغات البرمجة األخرى‬،‫تسمح التعبيرات الشرطية‬
if-else ‫ هذه عبارة عن تعيينات شرطية مكونة من سطر واحد والتي غالبًا ما تكون أكثر انسيابية من كتلة‬.‫بنا ًء على الشرط‬
.‫متعددة األسطر‬

Basic Syntax:

Neili Zakaria
Example of a Conditional Expression:

The pass Statement


The pass statement in Python is used as a placeholder for future code. When the pass statement is

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

avoid syntax errors in such cases.

Use of pass:

• Commonly used in loops, functions, classes, or in conditional statements where code


will be added later.
• It helps in writing the structure of your program without having to implement all the
functionality immediately.

Example of Using 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

You might also like