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

Chapter1(Introduction)

The document serves as an introduction to Python, covering fundamental concepts such as indentation, comments, data types, variables, and the use of built-in functions. It explains how to create and manipulate variables, perform type casting, and utilize input and output statements in Python. Additionally, it provides examples of mathematical expressions and their outputs.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15 views

Chapter1(Introduction)

The document serves as an introduction to Python, covering fundamental concepts such as indentation, comments, data types, variables, and the use of built-in functions. It explains how to create and manipulate variables, perform type casting, and utilize input and output statements in Python. Additionally, it provides examples of mathematical expressions and their outputs.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 31

Introduction to Python

Python is an Open-source language that can be implemented using several Open-source editors:
✓ Anaconda (Jupyter Notebook, Spider, VS code, PyCharm, etc.)
✓ Google Collaboratory
After you have selected the option that you will follow to program Python, now you must know
the Roadmap that includes the topics that you will learn in this course:

Python Indentation
Python uses new lines to complete a command, as opposed to other programming languages which
often use semicolons or parentheses.
Indentation refers to the spaces at the beginning of a code line.
Python uses indentation to indicate a block of code.

Prepared By: Enas Abu Samra


Comments
Comments are notes of explanation that document lines or sections of a program. Comments
are part of the program, but the Python interpreter ignores them. They are intended for
people who may be reading the source code.
Comments are short notes placed in different parts of a program, explaining how those parts of the
program work. There are two types of comment statements:

1. An end-line comment or single-statement comment is a comment that appears at the end


of a line of code. It usually explains the statement that appears in that line.
It starts with #

Ex: Single-statement comment Output:

i=3 #This is integer variable


OR
Nothing
#This is integer variable

i=3

2. Multi-statements comments start with triple quotes (either """ or ''').

Ex: Multi-statements comment Output:

""" This is second example


In Python course""" Hello

Print(""Hello"")

*********************************

Data Types:

Prepared By: Enas Abu Samra


Variables
- A variable is a name that represents a value stored in the computer’s memory.
- When a variable represents a value in the computer’s memory, we say that the variable
references the value. Each variable has a data type and value.
- In Python, the data type is set when you assign a value to a variable
- Python has no command for declaring a variable.
Strings can contain single quotes, double quotes, and triple quotes as part of the string.
Ex: ['Hi', "Hi" , """Hi""" ].

➢ Creating Variables with Assignment Statements


You use an assignment statement to create a variable and make it reference a piece of data.
An assignment statement is written in the following general format:

variable = expression

The equal sign (=) is known as the assignment operator. In the general format, variable is the
name of a variable and expression is a value, or any piece of code that results in a value.
Here is an example of an assignment statement:

age = 25

Ex: Variable Declaration

name = “Enas” #This is a string variable


age = 33 #This is an integer variable
income = 850.30 #This is a float variable
g_state = True #This is a boolean variable

❖ Identifier: the names that given to variables, functions, classes, etc.


When choose identifier you must follow these rules:
1. You cannot use one of Python’s key words.
2. An identifier cannot contain spaces.
3. The first character must be one of the letters a through z, A through Z, or an underscore
character (_).
4. After the first character you may use the letters a through z or A through Z, the digits 0
through 9, or underscores.
Notes:
✓ Uppercase and lowercase characters are distinct.
✓ You should choose names for your variables that give an indication of what they are used
for.

Prepared By: Enas Abu Samra


Table 1: lists several sample variable names and indicates whether each is legal or illegal in
Python.

Table1: Samples of variable names

➢ Variable Reassignment
Variables are called “variable” because they can reference different values while a program is
running. When you assign a value to a variable, the variable will reference that value until you
assign it a different value.
Note: when you change the value of the variable, the data type of the variable will be changed
based on the new value.

Ex: Variable Reassignment Output:


x = 3
print(x, type(x)) 3 <class 'int'>
x = 10 10 <class 'int'>
print(x, type(x))
9.5 <class 'float'>
x = 9.5
print(x, type(x)) True <class 'bool'>
x = True Hello <class 'str'>
print(x, type(x))
x = "Hello"
print(x, type(x))

➢ Declare Multiple Variables


Python allows you to assign values to multiple variables in one line:
Ex: Declare Multiple Variables Output:

x, y, z ="Orange", "Banana", "Cherry" Orange


print(x)
print(y) Banana
print(z)
Cherry

Prepared By: Enas Abu Samra


Ex: Assign one value to multiple variables Output:

x = y = z = 10 10
print(x)
print(y) 10
print(z)
10

➢ Built-in type Function

you can use the built-in type function to get the data type of a value/variable.

Format: type(variable or value)

Ex: Variable Reassignment Output:


print(type(1)) <class 'int'>
print(type(1.0)) <class 'float'>
print(type("Hi")) <class 'str'>
print(type(True)) <class 'bool'>
x = 5
<class 'int'>
print(type(x))

*********************************
Python Casting

Casting

Implicit Explicit

➔Casting in python is therefore done using constructor functions:


✓ int() -constructs an integer number from an integer literal, a float literal (by rounding down
to the previous whole number), or a string literal (providing the string represents a whole
number)
✓ float() -constructs a float number from an integer literal, a float literal or a string literal
(providing the string represents a float or an integer).
✓ str() -constructs a string from a wide variety of data types, including strings, integer literals
and float literals.

Prepared By: Enas Abu Samra


Ex: Implicit Casting Ex: Explicit Casting (int)
x = 3 x = int(3)
print(x) #3 (int) print(x) #3
x = 8.9 x = int(8.9)
print(x) #8.9 (float) print(x) #8
x = int("66")
x = "Hi"
print(x) #66
print(x) #”Hi” (string) x = 5.2
x = True x = int(x)
print(x) #True (bool) print(x) #5
x = True + 5 x = int("5.6") #error
y = False + 5 print(x)
print(x, type(x)) #6 <class 'int'>
print(y, type(y)) #5 <class 'int'> All types here are integer.

Ex: Explicit Casting (float) Ex: Explicit Casting (string)

x = float(3) x = str(3)
print(x) #3.0 print(x) #”3.0”
x = float(8.9) x = str(8.9)
print(x) #8.9 print(x) #”8.9”
x = float("66") x = str("66")
print(x) #”66”
print(x) #66.0
x = "Hi"
x = 50 x = str(x)
x = float(x) print(x) #”Hi”
print(x) #50.0
x = float("5.6")
print(x) #5.6

All type here are float. All type here are string.

Example1 (important): Output:

x = 50.5
x = int(x) 50
print(x) <class 'int'>
print(type(x))

Example2 (important): Output:

y = 50.5
x = int(y)
print(x) 50
print(type(x)) <class 'int'>
print(y) 50.5
print(type(y)) <class 'float'>

Prepared By: Enas Abu Samra


Output Statement
➢ Displaying Output with the print Function
You use the print function to display output in a Python program.

Ex1: Output statement Output:


print("Hi1") Hi1
print(5)
print(8.5) 5
print(True)
print(False) 8.5
print(1.1 + 2.5)
print(2 + 3) True
print("2+3")
False
name = "Enas"
print(name) 3.6
print("Hi" + "Students")#concatination
print("Hi" + 1) #error 5
2+3
Enas
HiStudents

Note: Each of the statements displays a string and then prints a newline character.

print(item1, ithem2, ….) print(item1, ithem2, …., end ="\n")

➢ Displaying Multiple Items with the print Function


Python allows us to display multiple items with one call to the print function. We simply have to
separate the items with commas.
Ex2: Output statement Output:
name = "Enas"
print("Hi1", 2, 5.33, True, name) Hi1 2 5.33 True Enas

➢ Suppressing the print Function’s Ending Newline


The end parameter in the print function is used to add any string. At the end of the output of
the print statement in python. By default, the print function ends with a newline.
If you do not want the print function to start a new line of output when it finishes displaying its
output, you can pass the special argument end=" " to the function.

Prepared By: Enas Abu Samra


Output:
Ex3: Output statement
print("Hi1", end ="$") Hi1$99##2.3
print(99, end ="##")
print(2.3)

Output:
Ex4: Output statement
print("Hi1", end =" ")
Hi1 99 2.3
print(99, end =" ")
print(2.3)

Output:
Ex5: Output statement
a, b, c = 2, 5, 7 2 5 7$$2 5 7
print(a,b,c,end = "$$")
print(a,b,c) 2 5 72 5 7
print(a,b,c,end= "")
print(a,b,c)

➢ Specifying an Item Separator


When multiple arguments are passed to the print function, they are automatically separated by a
space when they are displayed on the screen.
Ex6: Output statement without separator Output:
print("One", "Two", "Three") One Two Three

print(item1, ithem2, ….) print(item1, ithem2, …., sep= " ",end ="\n")

The sep parameter of the print() function is used to specify the separator between the strings. If
you do not want a space printed between the items, you can pass the argument sep=" "to the print
function, as shown here:

Ex7: Output statement with separator Output:

print("One","Two","Three", sep="$") One$Two$Three


print(88)
88

Prepared By: Enas Abu Samra


Ex8: Output statement with separator Output:

x, y, z = 10, 15, 20
print(x,y,z, sep = "Hi", end = "$") 10Hi15Hi20$10 15 20
print(x,y,z, sep = " ")
print(x,y,z, end = "***")
10 15 20***10----15----20
print(x,y,z, sep = "----")

➢ Escape Characters
An escape character is a special character that is preceded with a backslash (\), appearing inside
a string literal. When a string literal that contains escape characters is printed, the escape characters
are treated as special commands that are embedded in the string.
Python recognizes several escape characters, some of which are listed in the following table.

Ex: Output statement with escape character

Output:
One
print("One\nTwo\nThree")
print("One\\Two\\Three") Two
Three
One\Two\Three

*********************************

Input Statement
Programs commonly need to read input typed by the user on the keyboard.
We use Python’s built-in input function to read input from the keyboard. The input function reads
a piece of data that has been entered at the keyboard and returns that piece of data, as a string,
back to the program

Format: variable = input(prompt)

Prepared By: Enas Abu Samra


In the general format, prompt is a string that is displayed on the screen. The string’s purpose is to
instruct the user to enter a value; variable is the name of a variable that references the data that was
entered on the keyboard.
Note➔ prompt is not necessary, you can write input statement like this: x = input()

Output:
Ex1: Input string values
name = input("Please enter your name: ") Please enter your name: Enas
age = input("Please enter your age: ")
income = input("Please enter your income: ") Please enter your age: 40
g_state = input("Please enter your graduate state: ")
print("Done!") Please enter your income: 500.20
Please enter your graduate state: true
Done!

➢ Reading Numbers with the input Function


The input function always returns the user’s input as a string, even if the user enters numeric data.
Fortunately, Python has built-in functions that you can use to convert a string to a numeric type:
int(item) → converts item to integer number.
float(item) → converts item to float number.

Ex2: Input values with different types Output:

name = input("Please enter your name: ")


age = int(input("Please enter your age: ")) Please enter your name: Enas
income = float(input("Please enter your income: "))
g_state = bool(input("Please enter True or False: ")) Please enter your age: 40
Please enter your income: 500.5
print(type(name))
print(type(age)) Please enter True or False: True
print(type(income))
print(type(g_state))
<class 'str'>
<class 'int'>
<class 'float'>
<class 'bool'>

*********************************

Prepared By: Enas Abu Samra


Expressions
An expression: is any legal combination of symbols that represents a value.
Every expression consists of at least one operand (number) and can have one or more operators.
Operands are values, whereas operators are symbols that represent particular actions. The
following figure shows types of expressions.

Math Expression: performs a calculation and gives a value, it contains operands(numbers) and
math operators (+, -, *, /, //, **, %).
Math expression can be categorized into three types: Integer Expressions, Floating Expressions,
and Mixed-Type Expressions.
Integer Expressions: an operation is performed on two or more int values then the result will be
an int.
Float Expressions: an operation is performed on two or more float values then result will be a
float.
Mixed-Type Expressions: an operation is performed on different data types (int and a float), the
int value will be temporarily converted to a float and the result of the operation will be a float, then
the result will be float.

Prepared By: Enas Abu Samra


The following examples of math expression:

Ex1: Math Expressions Output:

print(5 + 3 * 2) #integer expression 11


print(2.2 / 1.1 *5.3) #floating-point expression 10.6
print(1 + 2.3 * 6) #mixed-type expression
print(5/2) #floating-point division 14.7999999999
print(5//2) #integer division with positive numbers
print(-10//6) #integer division with negative numbers 2.5
print(-10//3) #integer division with negative numbers 2
print(2**3) #exponent
print(5%2) #modulus or remainder operator -2
-4
8
1

Python has two different division operators. The / operator performs floating-point division, and
the // operator performs integer division. Both operators divide one number by another. The
difference between them is that the / operator gives the result as a floating-point value, and the //
operator gives the result as an integer value.

The // operator works like this:


• When the result is positive, it is truncated, which means that its fractional part is thrown away.
• When the result is negative, it is rounded away from zero to the nearest integer.

➢ Operators Precedence
The precedence of the math operators, from highest to lowest, are:
1. Between Brackets ()
2. Exponentiation: **
3. Multiplication, division, and remainder: * / // %
4. Addition and subtraction: + −
5. Relational Operators: == != <= >= < >
6. Logical Operators: not and or
If the precedence is, the execution is from left to right.
The following figure shows the execution of an expression.

Prepared By: Enas Abu Samra


Boolean Expression: the expression that its result is true or false, and it contains relational and
logical operators with operands.

Relational (comparison) operators: >, >=, <, <=, ==, !=

Logical operators: and, or, not

(and, or, not) operators allow you to connect multiple boolean expressions to create a compound
expression.
The followings tables show the truth table for (and, or, not) operators respectively.
The truth table for and operator

The truth table for or operator

The truth table for not operator

Prepared By: Enas Abu Samra


Now, we can say that we are ready to write the first Python program.

Program1: average.py

Write a program that do the following:


- Allow the user to enter three float numbers.
- Calculate the sum of these numbers.
- Calculate the average of these numbers.

Output Sample:
Enter 3 numbers: 3
5
3

Average = 3.6666666666666665

Code:

n1,n2,n3=float(input("Enter 3numbers:")),float(input()),float(input())
average=(n1+n2+n3)/3
print("average=",average)

Program2: Exponent.py

Write a Python program that reads the basic salary of an employee, calculates his tax(6% of his
basic salary and calculates the Netsalary by the following equation:
Note: Net Salary = Basic Salary –TaxSolution:

Prepared By: Enas Abu Samra


Output Sample:
Please,enter the basic salary: 1000
NetSalary= 940.0

Code:
basicSalary = float(input("Please,enter the basic salary: "))
tax = 0.06 * basicSalary
NetSalary = basicSalary-tax
print("NetSalary= ",NetSalary)

*********************************

Decision Structures (Selection Structures)


Types of Control Structures:
1. Sequence structure: is a set of statements that execute in the order in which they appear.
2. Decision structure: is a logical design that controls the order in which a statement or set
of statements only execute under certain conditions.
3. Repetition structure: is a logical design that controls the order in which a statement or set
of statements execute repeatedly.

Decision structures have many forms:

✓ One-Way Selection OR Single Alternative Decision Structure (if Statement)


✓ Two-Ways Selection OR Dual Alternatives Decision Structure (if-else Statement)
✓ Multiple Selections (Nested if: if-else-if-else…, if-elif-else)

➢ Single Alternative Decision Structure (if Statement)


This one is the simplest decision structure’s form, a specific action is performed only if a certain
condition exists. If the condition does not exist, the action is not performed.
The general format of the if statement:

if (condition):
statement
statement
etc.

Prepared By: Enas Abu Samra


A block is simply a set of statements that belong together as a group.
Notice in the general format that all of the statements in the block are indented.

Ex1: if statement
sales = int(input("Please enter your sales:"))
if(sales > 500):
bonus = 30
print("The bonus is:", bonus)
print("Done!")

➢ Dual Alternative Decision Structure (if Statement)

In Python, we use the if-else statement to write the dual alternative decision structure, which
has two possible paths of execution—one path is taken if a condition is true, and the other path is
taken if the condition is false.
The general format of the if-else statement:

if (condition):
statement
statement
etc.
else:
statement
statement
etc.

Ex2: if-else statement

temperature = int(input("Please enter the temperature:"))


if(temperature < 40):
print("A little cold, isn't it?")
print("Turn up the heat!")
else:
print("Nice weather we're having.")
print("Pass the sunscreen.")

print("Done!")

Prepared By: Enas Abu Samra


Figure 8: if-else aligning

➢ Nested Decision Structures and the if-elif-else Statement


To test more than one condition, a decision structure can be nested inside another decision
structure.
In Python, you can use many forms: if else- if else …etc or if-elif-else.

The if-elif-else Statement


Python provides a special version of the decision structure known as the if-elif-else statement,
which makes this type of logic simpler to write.
The general format of the if-elif-else statement:

if (condition1):
statement
statement
etc.
elif (condition2):
statement
statement
etc.
else: #optional (executed when all previous conditions are false)
statement
statement
etc.

Ex3: nested if (if-elif-else)


score = int(input("Enter your test score: "))
if(score >= 90):
print("Your grade is A.")
elif(score >= 80):
print("Your grade is B.")
elif(score >= 70):
print("Your grade is C.")
elif(score >= 60):
print("Your grade is D.")
else:
print("Your grade is F.")
Prepared By: Enas Abu Samra
Ex4: nested if (Multi-ways)

score = int(input("Enter your test score: "))


if(score >= 90):
print("Your grade is A.")
else:
if(score >= 80):
print("Your grade is B.")
else:
if(score >= 70):
print("Your grade is C.")
else:
if(score >= 60):
print("Your grade is D.")
else:
print("Your grade is F.")

Ex5: nested if (Multi-ways)

x, y = 5, 6
if(x<y): #if the condition is false, all the following if will not execute
print("x is greater than y")
print("here, is if(1)")
if(x == 5): #if the condition is false, the following if will not execute
print("here, is if(2)")
if(y == 6):
print("here, is if(3)")
print("Finished")

Ex6: nested if (Multi-ways)

x, y = 5, 6
if(x<y): #if the condition is false, all the following if will not execute
print("x is greater than y")
print("here, is if(1)")
if(x == 5): #this if is independent of the following if
print("here, is if(2)")
if(y == 6):
print("here, is if(3)")
print("Finished")

Note: Please try all possible conditions in the previous two examples to understand the difference
between them correctly.

Prepared By: Enas Abu Samra


Examples of Selection Statements
Example1:

The program should ask the user to input two integer operands and an operation (+, -, *, /, //,
**), your program should print the result of performing the required operation on the input
operands.

Output Sample:
Please enter the first operand:100
Please enter the second operand:22
Please enter the operation:/
The result of 100 / 22 is: 4.54545

Code:
firstOperand = int(input("Please enter the first operand (number): "))
secondOperand = int(input("Please enter the second operand (number): "))
operation = input("Please enter the operation: ")
if (operation == "+"):
print("The result of ", firstOperand, operation, secondOperand, "is:",
firstOperand + secondOperand)
elif (operation == "-"):
print("The result of ", firstOperand, operation, secondOperand, "is:",
firstOperand - secondOperand)
elif (operation == "*"):
print("The result of ", firstOperand, operation, secondOperand, "is:",
firstOperand * secondOperand)
elif (operation == "/"):
print("The result of ", firstOperand, operation, secondOperand, "is:",
firstOperand / secondOperand)
elif (operation == "//"):
print("The result of ", firstOperand, operation, secondOperand, "is:",
firstOperand // secondOperand)
elif (operation == "**"):
print("The result of ", firstOperand, operation, secondOperand, "is:",
firstOperand ** secondOperand)
else:
print("OHH, your input is incorrect!!")

Example2:

Write a Python program that reads two integers and divides the first over the second. Make sure
that the second integer is not zero, otherwise, give an error message.

Output Sample:
Enter two integers: 10
3
The result is: 3.3333333333333335

Prepared By: Enas Abu Samra


Code:

n1,n2=int(input("Enter two integers: ")),int(input())


if (n2!=0):
print("The result is:",n1/n2)
else:
print("Error: Divide by Zero")

Example3:

Write a Python program that reads an integer and decides wither it is divisible of 3 or not.

Output Sample:
Enter an integer: 5
5 is not divisible by 3

Code:
num=int(input("Enter an integer: "))
if (num%3==0):
print(num,"is divisible by 3")
else:
print(num,"is not divisible by 3")

Example4:

Write a Python program that reads a day in a week from the user, and prints the following:
Working day: if the user enters (Sunday, Monday, Tuesday, Wednesday or Thursday)
Weekend: if the user enters (Friday or Saturday)

Output Sample:
Please, enter a weekday: Monday
Working day
Please, enter a weekday: Friday
Weekend

Code:
day=input("Please, enter a weekday: ")
if (day=="Sunday") or (day=="Monday") or (day=="Tuesday") or
(day=="Wednesday") or (day=="Thursday"):
print("Working day")
elif (day=="Friday") or (day=="Saturday"):
print("Weekend")
else:
print("Wrong day name or wrong spelling")

Prepared By: Enas Abu Samra


Example5:

Output Sample:
Enter an integer: 5
R= 25

Code:

x= int(input("Enter an integer: "))


if (x>0):
R= x**2
else:
R= x**3
print("R=",R)

The pass Statement


if statements cannot be empty, but if you for some reason have an if statement with no content,
put in the pass statement to avoid getting an error.

Example1:
x= int(input("Enter an integer: "))
if (x>0):
pass
else:
print("x is less than zero")

Example2: (Not Ideal Use)


x= int(input("Enter an integer: "))
if (x>0):
pass
print("x is greater than zero")
else:
print("x is less than zero")

*********************************

Prepared By: Enas Abu Samra


Repetition Structures
Repetition structures have many forms:
✓ Condition-Controlled Loop: uses a true/false condition to control the number of times
that it repeats. (while Loop)
✓ Count-Controlled Loop: repeats a specific number of times (for Loop, you can use while)
✓ Nested Loop: for-for, for-while, while-while, while-for.

➢ Condition-Controlled Loop (while loop)


A condition-controlled loop causes a statement or set of statements to repeat as long as a condition
is true. In Python, you use the while statement to write a condition-controlled loop.
The general format of the while loop in Python:

while (condition):
statement
statement #it can be a counter-update statement
etc.

Ex1: while loop Ex2: while loop


num = 1 num = 1
while(num <= 3): while(num <= 3):
print(num, end =" ") print(num, end =" ")
num += 1 num += 1
print("Finished!") print("Hi", end = " ")

print("Finished!")
Output:
1 2 3 Finished! 1 Hi 2 Hi 3 Hi Finished!

How to Track a While Loop?


Step1: check the condition, if it true move to step2 else move to first statement outside the loop.
Step2: execute the while body.

Prepared By: Enas Abu Samra


❖ Sentinel value with while loop
A sentinel is a special value that marks the end of a sequence of values. You can use sentinel
value to control the condition in while loop.

Ex3: while loop with sentinel value


sentinel_value = input("Do you have sold goods? enter Yes or No: ")
while(sentinel_value == "Yes"):
number_of_goods = int(input("Please enter a number of the sold Goods: "))
if(number_of_goods >= 0):
print("Your enter a valid number, Excellent")
else:
print("Ohhh, Your enter an invalid number, Try again!")
sentinel_value = input("if you want to enter another number,
enter Yes else enter No: ")
print("----------------------------------------")

Ex4:
Write a Python program that receives positive values then prints them, the loop will stop if the
user enters negative value.
Solutions:

number = int(input("Please enter a positive num: "))


while(number >= 0):
print(number)
number = int(input("Please enter a positive num: "))

flag = True
while(flag):
number = int(input("Please enter a positive num: "))
if(number >= 0):
print(number)
else:
flag = False

while(True):
number = int(input("Please enter a positive num: "))
if(number >= 0):
print(number)
else:
break

Prepared By: Enas Abu Samra


➢ Count-Controlled Loop (for loop)
A count-controlled loop iterates a specific number of times. In Python, you use the for statement
to write a count-controlled loop.
The general format of the for loop in Python:

for variable in range(start, stop, step):


statement
statement
etc.

❖ Built-in Function: Range()


The range function creates a sequence of values that can be iterated over with something
like a loop.

The general format of range() function:


range(start, stop, step)
Note: By default: start➔ 0, step ➔ 1

Examples: Output:
range(0, 5, 1) #[0, 1, 2, 3, 4] #(start, stop, step)
range(0, 5) #[0, 1, 2, 3, 4] #(start, stop)
range(5) #[0, 1, 2, 3, 4] #(stop)

Note: when step is positive, the start must be less than stop (start < stop)
range(0, 11, 2) #[0, 2, 4, 6, 8, 10]
range(1, 10, 2) #[1, 3, 5, 7, 9]

➔How range function works when the step is positive?


Step1: counter = start
Step2: check the condition, if (start < stop) move to step3 then step4 else move to first
statement outside the loop.
Step3: execute the body.
Step4: increase the counter by step value.

Note: when step is negative, the start must be greater than stop (start > stop)
range(10, 0, -1) #[10, 9, 8, 7, 6, 5, 4, 3, 2, 1]
range(10, 0, -2) #[10, 8, 6, 4, 2]
range(9, 0, -2) #[9, 7, 5, 3, 1]

Prepared By: Enas Abu Samra


➔How range function works when the step is negative?
Step1: counter = start
Step2: check the condition, if (start > stop) move to step3 then step4 else move to first
statement outside the loop.
Step3: execute the body.
Step4: decrease the counter by step value.

Note: the start, stop, and step can be variable


a, b, c = 2, 5, 3
for i in range(a,b,c):
print(i, end= " ")

Examples:
Ex1:

print("All Numbers from 0 to 10")


#for num in range(0, 11): #for num in range(0,11, 1):
for num in range(11):
print("The number is: ", num)

Ex2:
print("Even Numbers from 0 to 10")
for num in range(0, 10, 2):
print("The number is: ", num)

Ex3:
print("Odd Numbers from 0 to 10")
for num in range(1, 10, 2):
print("The number is: ", num)

Ex4:
print("All Numbers from 10 to 1")
for num in range(10, 0, -1):
print("The number is: ", num)

Prepared By: Enas Abu Samra


Ex5:
print("Odd Numbers from 9 to 1")
for num in range(9, 0, -2):
print("The number is: ", num)

Ex6:

print("print Hello world 5 Times!!")


for x in range(5):
print("Hello world")

Ex7:

for i in range(15, 4, 3): #condition is false


print("Hi")

Ex8:

for i in range(2, 10, -2): #condition is false


print("Hi")

Ex9:

start = int(input("Please enter the start value: "))


stop = int(input("Please enter the stop value: "))
step = int(input("Please enter the step value: "))
for i in range(start, stop, step):
print(i)

Prepared By: Enas Abu Samra


Examples of Repetition Statements
Example1:

The program prints the numbers 1 through 10 and their squares.

Output Sample:

Number Square
------------------------
1 1
2 4
3 9
4 16
5 25
6 36
7 49
8 64
9 81
10 100

Code:
print ("Number\tSquare")
print ("------------")
#Print the numbers 1 through 10 and their squares.
for number in range (1, 11):
square = number ** 2
print (number, "\t\t", square)

Example2:
Write a python program that prints the following sequence:

5 9 13 17 21
Code:
for i in range(5, 22, 4):
print(i, end= " ")

Example3:
Write a Python program reads an integer from the user and prints its factorial.

Output Sample:
Please, Enter an integer: 5
5! = 120

Prepared By: Enas Abu Samra


Code:
n = int(input ("Please, Enter an integer: "))
prod = 1
for i in range(n, 1, -1):
prod *= i
print(n, "! = ", prod, sep= "")

Example4:
Write a Python program that reads a sequence of positive integers and sums them. A negative
integer should stop the input.
Output Sample:
Enter a positive value: 5
Enter a positive value: 4
Enter a positive value: -3
Summation = 9
Code:
sum = 0
num= int(input ("Enter a positive value: "))
while (num>=0):
sum += num
num= int(input ("Enter a positive value: "))
print ("Summation = ", sum)

Example5:
Write a Python program that reads integer numbers and finds their product, each time keep asking
the user to continue or not.
Output Sample:
Please, enter an integer: 11
Do you want to continue? (Y/N): y
Please, enter an integer: 5
Do you want to continue? (Y/N): n
Result = 55

Code:
prod = 1
finished = False
while (not finished):
num = int(input("Please, enter an integer: "))
prod *= num
respond = input ("Do you want to continue? (Y/N): ")

Prepared By: Enas Abu Samra


if respond == "n" or respond == "N":
finished = True
print ("Result = ", prod)

➢ Nested Loop
There are many forms for nested loop: (for-for, while-while, for-while, while-for), you can
choose any one. Try to solve these problems:

1. Print the following Pyramid:

Code:
for row in range (1, 6):
for star in range(row):
print("*", end = "")
print(" ")

2. Print the sum of the following series:

Code:
sum = 0
for i in range(6):
for j in range(11):
sum += (i + 2 * j)
print("The sum is: ", sum)

Prepared By: Enas Abu Samra


➢ Infinite Loop
An infinite loop continues to repeat until the program is interrupted. Infinite loops usually occur
when the programmer forgets to write code inside the loop that makes the test condition false.

Ex: infinite while loop


num = 0
while(num >= 0):
print(num)
num += 1
print("Finished!")

➢ Break and Continue Statements


Break Statement
The break statement terminates the loop containing it. Control of the program flows to the
statement immediately after the body of the loop.

Ex1: break_statement

for i in range(6):
if(i == 3):
break
print(i)
print("Done!!")

Continue Statement
The continue statement is used to skip the rest of the code inside a loop for the current iteration
only. Loop does not terminate but continues on with the next iteration.

Ex1: continue_statement

for i in range(6):
if(i == 3):
continue
print(i)
print("Done!!")

Prepared By: Enas Abu Samra


Re-write the code in Example 5, by using Break command.

Code:
prod = 1
while (True):
num= int(input("Please, enter an integer: "))
prod *= num
respond = input ("Do you want to continue? (Y/N): ")
if respond == "n" or respond == "N":
break
print("Result = ", prod)

Re-write the code in the previous example, but by ignoring the negative numbers.
Hint: you can use break and continue commands.

Code:
prod = 1
while (True):
num= int(input ("Please, enter an integer: "))
if (num<0):
print("Negative integers are ignored, try again")
continue
prod *= num
respond = input ("Do you want to continue? (Y/N): ")
if respond == "n" or respond == "N":
break
print ("Result = ", prod)

*********************************

Prepared By: Enas Abu Samra

You might also like