1
Python
What is python 2
Python is a programming language that was created by Guido van
Rossum, and releases in 1991
It is used for:
➢ Software development
➢ Web development
➢ Mathematics
➢ System scripting
What can Python do? 3
Python can be used on a server to create web applications.
Python can be used alongside software to create workflows.
Python can connect to database systems. It can also read and
modify files.
Python can be used to handle big data and perform complex
mathematics.
Python can be used for rapid prototyping, or for production-ready
software development.
Why Python? 4
Python works on different platforms (Windows, Mac, Linux, Raspberry Pi, etc).
Python has a simple syntax similar to the English language.
Python has syntax that allows developers to write programs with fewer lines
than some other programming languages.
Python runs on an interpreter system, meaning that code can be executed
as soon as it is written. This means that prototyping can be very quick.
Python can be treated in a procedural way, an object-oriented way or a
functional way.
You should know 5
The most recent major version of Python is Python 3, which we shall
be using in this tutorial. However, Python 2, although not being
updated with anything other than security updates, is still quite
popular.
In this course Python will be written in a text editor. It is possible to
write Python in an Integrated Development Environment, such as
Thonny, Pycharm, Netbeans or Eclipse which are particularly useful
when managing larger collections of Python files.
Python Software Foundation 6
You can download the latest version for Windows (Python 3.12.2) by following this link:
https://www.python.org/downloads/
https://drive.google.com/drive/folders/18rgT9kGrrAXVWkqLsoIBixjstVN-c2gf?usp=sharing
This course uses Python 3.
Python Syntax compared to other 7
programming languages
Python was designed for readability, and has some similarities to the
English language with influence from mathematics.
Python uses new lines to complete a command, as opposed to
other programming languages which often use semicolons or
parentheses.
Python relies on indentation, using whitespace, to define scope;
such as the scope of loops, functions and classes. Other
programming languages often use curly-brackets for this purpose.
First program in python 8
If you type >>> print("Welcome to Python") and press the Enter key.
The string Welcome to Python appears on the console. Note that
Python requires double or single quotation marks around strings to
delineate them from other code.
Type exit()to exit Python and return to the command prompt.
Creating Python source code file 9
Entering Python statements at the statement prompt >>> is
convenient, but the statements are not saved. To save statements
for later use, you can create a text file to store the statements and
use the following command to execute the statements in the file:
python filename.py
The text file can be created using a text editor such as Notepad.
The text file, filename, is called a Python source file or script file, or
module. By convention, Python files are named with the extension
.py.
Python indentation 10
Indentation refers to the spaces at the beginning of a code line.
Where in other programming languages the indentation in code is
for readability only, the indentation in Python is very important.
Python uses indentation to indicate a block of code.
Syntax Error
Ex:
Note:
• The number of spaces is up to you as a programmer, but it has to be at least one.
• You have to use the same number of spaces in the same block of code, otherwise
Python will give you an error:
2 or more statement 11
Syntax error(Indentation Error : unexpected indent)
• Don’t put any punctuation at the end of the statement
• Python is case sensitive
• String variables can be declared either by using single or double quotes:
Comments 12
Comments can be used to explain Python code.
Comments can be used to make the code more readable.
Comments can be used to prevent execution when testing code.
Comments 13
Python has commenting capability for the purpose of in-code
documentation.
Comments start with a #, and Python will render the rest of the line
as a comment:
Multiline Comments 14
Python does not really have a syntax for multi line comments.
Solution is:
Since Python will ignore string literals that are not assigned to a
variable, you can add a multiline string (triple quotes) in your code,
and place your comment inside it:
Note: Don’t assign variable to this string
Variables 15
Python has no command for declaring a variable.
A variable is created the moment you first assign a value to it.
Output
Casting 16
If you want to specify the data type of a variable, this can be done
with casting.
Ex:
Output:????
Variable names 17
A variable can have a short name (like x and y) or a more descriptive name
(age, carname, total_volume). Rules for Python variables' variable name must
start with a letter or the underscore character
A variable name cannot start with a number
A variable name can only contain alpha-numeric characters and underscores
(A-z, 0-9, and _ )
Variable names are case-sensitive (age, Age and AGE are three different
variables)
Legal Illegal
Variables - Assign Multiple Values 18
Python allows you to assign values to multiple variables in one
line:
And you can assign the same value to multiple variables in one line:
Unpacking collection of variables 19
List, tuple(Array)
Mathematical computations 20
Python programs can perform all sorts of mathematical
computations and display the result.
To display the addition, subtraction, multiplication, and division of
two numbers, x and y, use the following code:
print(x + y)
print(x – y)
print(x * y)
print(x / y)
Example: print((10.5 + 2 * 3) / (45 – 3.5))
Exercise : Average of 3 students 23
eval: to evaluate and convert it to a numeric value.
Ex: write a program to calculate the area of circle
Arithmetic operators 25
Augmented assignment operators. 26
Additional built in function 27
Math Functions 28
Math Functions 29
The math module provides the mathematical functions listed in the following table. To use these
functions in a program, the math module must be imported (import math). Example of use:
math.sqrt
Interpreter 30
the Python interpreter cannot determine the end of the statement
written in multiple lines. You can place the line continuation symbol
(\) at the end of a line to tell the interpreter that the statement is
continued on the next line.
For example, the following statement
sum = 1 + 2 + 3 + 4 + \
5+6
is equivalent to
sum = 1 + 2 + 3 + 4 + 5 + 6
Relational Operator 31
Logical operator 32
Logical operators, also known as Boolean operators:
Control Structures 33
Like all high-level programming languages, Python provides
selection statements that let you choose actions with two or more
alternative courses. Example:
The statement(s) must be
indented at least one space to
the right of the if keyword
and each statement must be
indented using the same
number of spaces
Nested if and Multi-Way if-elif-else 34
Statements
Another way 35
Ex2: 36
Nested if and Multi-Way if-elif-else Statements
Priority of operators: 37
Loops 38
There are two loop structures in Python: while and for.
While loop
The syntax for the while loop is:
while condition:
Statements
For loop 39
Syntax:
− for i in range(initialValue, endValue):
# Loop body
Output
Note :numbers in range function should be integer
40
# Example of a for loop using range() function
initial_value = 1
end_value = 6
for i in range(initial_value, end_value):
print("Iteration", i)
Break in loop 41
42
# Example of using a for loop with range(6) and break statement
for x in range(6):
if x == 3:
print("Encountered 3. Exiting loop.")
break
print("Value of x:", x)
Nested loops 43
Output
44
# Example of nested loops with printing x
for i in range(3): # Outer loop
for j in range(2): # Inner loop
print(“+”, end=“ “)
print(“\n”)
Ex: Prime numbers between 2 and 30 45
Output
46
i=2
while i < 20:
j=2
while j <= (i / j):
if i % j == 0:
break
j=j+1
if j > i / j:
print(i, "is prime")
i=i+1
Functions 47
A function is a block of code which only runs when it is called.
You can pass data, known as parameters, into a function.
A function can return data as a result.
1. Creating a Function
2. Calling a Function
3. Arguments
4. Default Parameter Value
Function 48
The syntax for defining a function is as follows:
def functionName(list of parameters):
# Function body
Example: 49
Function with return value 50
51
# Function to perform addition
def add(x, y):
return x + y
# Function to perform subtraction
def subtract(x, y):
return x - y
# Example usage of the functions
num1 = 10
num2 = 5
# Adding num1 and num2
result_addition = add(num1, num2)
print("Result of addition:", result_addition)
# Subtracting num2 from num1
result_subtraction = subtract(num1, num2)
print("Result of subtraction:", result_subtraction)
Example of defining and calling a 52
function:
53
# Function to return the maximum of two numbers
def max_of_two(x, y):
if x > y:
return x
else:
return y
# Example usage of the function
num1 = 10
num2 = 5
maximum = max_of_two(num1, num2)
print("Maximum of", num1, "and", num2, "is:", maximum)
Call a function in a separate 54
program:
Program 1 Program 2
Python allows a function to return 55
multiple values
56
# Function to calculate the sum and difference of two numbers
def sum_and_difference(x, y):
sum_result = x + y
difference_result = x - y
return sum_result, difference_result
# Example usage of the function
num1 = 10
num2 = 5
sum_result, difference_result = sum_and_difference(num1, num2)
print("Sum of", num1, "and", num2, "is:", sum_result)
print("Difference of", num1, "and", num2, "is:", difference_result)
Default Arguments 57
Python allows you to define functions with default argument values.
The default values are passed to the parameters when a function is
invoked without the arguments.
58
# Function to calculate the area of a rectangle with default arguments
def calculate_area(width=1, height=1):
area = width * height
return area
# Example usage of the function
area1 = calculate_area() # Using default values for width and height
area2 = calculate_area(10) # Providing width, using default height
area3 = calculate_area(5, 3) # Providing both width and height
print("Area 1 (default width and height):", area1)
print("Area 2 (width=10, default height):", area2)
print("Area 3 (width=5, height=3):", area3)
Python Collections (Arrays) 59
There are four collection data types in the Python programming language:
1. List is a collection which is ordered and changeable. Allows duplicate
members.
2. Tuple is a collection which is ordered and unchangeable. Allows duplicate
members.
3. Set is a collection which is unordered and unindexed. No duplicate
members.
4. Dictionary is a collection which is unordered and changeable. No
duplicate members.
When choosing a collection type, it is useful to understand the properties of that
type. Choosing the right type for a particular data set could mean retention of
meaning, and, it could mean an increase in efficiency or security.
Array(List) 60
Arrays (also called lists) are used to store multiple values in one single
variable.
You can access the values by referring to an index number starting
from 0.
− You can create an array by using the following syntax:
A1 = []
A2 = [2, 3, 4]
A3 = ["red", "green"]
Array(List) 61
An array can contain elements of mixed types.
For example:
A4 = [2, "three", 4]
Access the elements of an array:
x = A2[0]
A3[1] = "blue“
Ex:
Array(List) 62
Python also allows the use of negative numbers as indexes to
reference positions relative to the end of the array. The actual
position is obtained by adding the length of the array with the
negative index.
Concatenating two arrays
For example:
63
# Example of using negative indices to reference positions relative to the
end of an array
my_list = ['a', 'b', 'c', 'd', 'e']
# Accessing elements using positive indices
print("Element at index 0:", my_list[0]) # Output: 'a'
print("Element at index 2:", my_list[2]) # Output: 'c'
# Accessing elements using negative indices
print("Element at index -1:", my_list[-1]) # Output: 'e' (last element)
print("Element at index -3:", my_list[-3]) # Output: 'c' (third element from the
end)
64
x = ["Rola", "Malek", "Ahmad","Mohamad"]
y = ["ENG","BIO","CHM","DATA SC"]
# Concatenating two arrays x and y
z = x + y
# Printing the concatenated result character by character
for index in range(len(z)):
print(z[index], end=" ")
Array(List) 65
How to display an array:
Ex: for i in range(0, len(myArray)):
print(myArray[i])
append() method: is to add an element to the end of an array:
z.append("Maya")
insert(i, Object) method to add an element at the specified position:
z.insert(1, “Ziad")
pop(i) method to remove an element from a specific index in the array:
z.pop(2)
remove(Object) method to remove an element from the array:
z.remove(Nour)
Array(List) 66
You may often need code that reads data from the console into an array. You
can enter one data item per line and append it to an array in a loop.
For example, the following code reads 5 numbers one per line into an array,
then it will display them in reverse order
Array(List) 67
Sometimes it is more convenient to enter the data in one line separated by spaces.
You can use the string’s split method to extract data from a line of input
Note: To copy the data in one array to another array, you have to copy individual elements
from the source array to the target array.
68
# Read numbers from a single line separated by spaces
input_str = input("Enter 5 numbers separated by space: ")
# Split the input string into individual numbers
arr = input_str.split()
# Initialize sum variable
s=0
# Convert strings to integers and print each number
for x in range(0, len(arr)):
num = eval(arr[x])
print(num, end=' ')
s = s + num
# Print the sum
print("\nSum =", s)
Array(List) 69
Passing arrays to functions:
Since array is an object, passing an array to a function is just like passing an
object to a function.
For example, the following function displays the elements in an array:
70
def read(arr):
for i in range(5):
arr[i] = eval((input("enter a number: ")))
return arr
def write (arr):
for i in range(5):
print(arr[i], end="")
arr = [None] * 5
arr = read(arr)
write(arr)
String 71
Strings are fundamental in computer science, and processing strings
is a common task in programming.
Strings are the objects of the str class.
So far, you have used strings in input and output.
The input function returns a string from the keyboard and the print
function displays a string on the monitor.
72
# Initializing empty strings
S1 = str()
S11 = " "
# Initializing strings with values
S2 = str("WelcomE")
S21 = "Faculty of Eng"
s11="Hello"
# Printing the strings
print(S2)
print(S21)
print(s11)
String 73
A character in the string can be accessed through the index
operator [] using the syntax: s[i]
len function to return the number of the characters in a string.
String 74
Displaying string character by character using loop
Since the indexes are 0 based; that is, they range from 0 to len(s)-1
Program
Ex: Output
String 75
assign a multiline string to a variable by using three quotes:
Note: you can use 3 single quotes
String 76
Check if “IUL" is present in the following text (str string):
String 77
Slicing
You can return a range of characters by using the slice syntax.
Specifythe start index and the end index, separated by a
colon, to return a part of the string.
Ex:
String 78
Concatenation: To concatenate, or combine, two strings you can
use the + operator.
Replace: The replace() method replaces a string with another string:
79
# Example of using the replace() method
original_string = "Hello, world! Hello, Python!"
# Replace "Hello" with "Hi"
new_string = original_string.replace("Hello", "Hi")
# Print the original and new strings
print("Original string:", original_string)
print("New string:", new_string)