Python Book
Python Book
1
2025 - 2026
Table of Contents
2
Chapter 1
Introduction to Python
"Every great coder started with a single line of code. Let’s write yours!"
3
Python overview and installation
What is Python?
Python is a versatile, high-level programming language that's easy to learn and use.
It was created by Guido van Rossum and first released in 1991. Python emphasizes
readability and simplicity, making it a great choice for beginners and professionals
alike. is a widely used high-level programming language.
It is used for:
History of python:
4
What can Python do?
Why Python?
5
Python installation
Select the appropriate installer for your Windows version (32-bit or 64-bit).
Deciding on a version depends on what you want to do in Python. The two major
versions are Python 2 and Python 3. Choosing one over the other might be better
depending on your project details. If there are no constraints, choose whichever one
you prefer.
For most users, the latest Python 3 version is recommended. as Python 2 reached
its end of life in 2020. Download Python 2 only if you work with legacy scripts and
6
older projects. Also, choose a stable release over the newest since the newest release
may have bugs and issues.
The download is approximately 25MB.
Step 2: Run Executable Installer:
Double-click the downloaded python .exe file.
Admin privileges. The parameter controls whether to install Python for the
current or all system users. This option allows you to change the
installation folder for Python.
Add Python to PATH. The second option places the executable in the PATH
variable after installation. You can also add Python to the PATH environment
variable manually later.
7
It includes IDLE (the default Python editor), the PIP package manager, and
additional documentation. The installer also creates necessary shortcuts and file
associations.
If you choose "Customize Installation", you can select additional features like pip
(package installer) and IDLE (integrated development environment).
Choose whether to install Python for all users. The option changes the install location
to C:\Program Files\Python[version]. If selecting the location manually, a common
choice is C:\Python[version] because it avoids spaces in the path, and all users can
access it. Due to administrative rights, both paths may cause issues during package
installation.
Other advanced options include creating shortcuts, file associations, and adding
Python to PATH.
8
After picking the appropriate options, click Install to start the installation.
Select whether to disable the path length limit. Choosing this option will allow
Python to bypass the 260-character MAX_PATH limit.
The option will not affect any other system settings, and disabling it resolves
potential name-length issues. We recommend selecting the option and closing the
setup.
9
Step 3: Add Python to Path (Optional)
If the Python installer does not include the Add Python to PATH checkbox or you
have not selected that option, continue in this step. Otherwise, skip to the next step.
Adding the Python path to the PATH variable alleviates the need to use the full path
to access the Python program in the command line. It instructs Windows to review
all the folders added to the PATH environment variable and to look for
the python.exe program in those folders
1. In the Start menu, search for Environment Variables and press Enter.
10
2.Click Environment Variables to open the overview screen.
11
4. Double-click the first empty field and paste the Python installation folder path.
Alternatively, click the New button instead and paste the path.
5. Click OK to save the changes. If the command prompt is open, restart it for the
following step.
12
The second way is to use the GUI to verify the Python installation. Follow the
steps below to run the Python interpreter or IDLE:
In both cases, the installed Python version shows on the screen, and the editor is
ready for use.
13
Step 5: Verify PIP Was Installed
To verify whether PIP was installed, enter the following command in the command
prompt:
pip --versionCopy
If it was installed successfully, you should see the PIP version number, the
executable path, and the Python version:
PIP has not been installed yet if you get the following output:
The virtualenv package enables making isolated local virtual environments for
Python projects. Virtual environments help avoid package conflicts and enable
choosing specific package versions per project.
14
Python IDLE (Integrated Development and Learning Environment) is an integrated
development environment for Python that comes bundled with the standard Python
distribution.
15
Python IDLE to write code and execute it
This IDLE will act as Interactive Python Interpreter, meaning as soon as you write
certain expression/code after >>> (Tripple forward arrow), you will get the result in
the next line itself. You can evaluate multiple expressions one by one or you could
also write multiple lines of script and evaluate them.
To write multiple lines of code, we need an editor. You can open an editor by
navigating to File menu and select the new file from the drop-down list.
Alternatively, you can use the shortcut command (Crtl+N). This is Python default
editor and we will write our programs in this editor. Image shown below illustrate
the method to create a new file for writing python program.
16
You have noticed that the name of the editor is untitled, which means the name has
not been assigned to this file. We will first give a name and save the file. To do so,
click on the file option of this editor (not the IDLE) and select Save from the drop-
down list. It will ask for the location to save the file, browse the path where you want
to save the file and provide a name with the extension .py with it and click on the
Save button. You will notice the untiled is replaced with the name of your file along
with the location. Now, we are good to go and write the program.
Note:
You can also download and use code editors or integrated development
environments (IDEs) that support Python programming such as Visual Studio
Code, PyCharm, Thonny, Spyder, IDLE, Sublime Text, Atom, or Jupyter
Notebook.
17
Quick Overview of Popular Python Editors & IDEs
18
Key Feachers of Python Programing
Basic Syntax:
print("Hello , world!")
x = 10 # Integer
y = 3.14 # Float
name = "John" # String
3. Comments: You can add comments in your code using the # symbol for
single-line comments, or triple quotes for multi-line comments.
19
5. Control Flow: You can control the flow of your program with conditional
statements (if, elif, else) and loops (for, while). If Statement:
x = 10
if x > 5:
print("x is greater than 5")
elif x == 5:
print("x is equal to 5")
else:
print("x is less than 5")
For Loop:
Exercise:
What will be the result of the following code:
for x in range(10):
print(x)
While Loop: With the while loop we can execute a set of statements as long as
a condition is true.
x=0
while x < 5:
print(x)
x += 1 # Increase x by 1
20
6. Functions: You can define functions in Python using the def keyword.
Python Libraries: Python has many powerful libraries, like numpy for
numerical computations, pandas for data manipulation, matplotlib for plotting,
and requests for web requests. You can install external libraries using pip:
bash
def bark(self) :
return f"{self.name} says woof! "
# creating an object of dog class
dog = dog("Buddy", 3)
print(dog.bark()) # output: Buddy says woof!
21
Python Syntax
Python syntax is designed to be easy to read.
Python Indentation refers to the spaces at the beginning of a code line.
Example:
if 5 > 2:
print("Five is greater than two!") # This is indented
Note: Python will give you an error if you skip the indentation
File "demo_indentation_test.py", line 2
Example: Syntax Error print("Five is greater than two!")
if 5 > 2: ^
print("Five is greater than two!") IndentationError: expected an indented block
22
Homework: Write your first Python program to display your full name and
grade.
Comments
Use # for single-line comments.
For multi-line comments, use triple quotes """ or’‘‘
Using comments: comments are a very useful tool for programmers. They
serve two purposes:
1-adding an explanation of how the program works;
2- Stopping parts of the program from working temporarily so you can run
and test other parts of the program.
Python is case sensitive so it is important that you use the correct case, otherwise
your code will not work.
In this example, comments have been added at the end of the last three lines. They
are shown in red and start with the # symbol.
You can use a semicolon to write multiple statements on one line (not
recommended for readability).
23
Line Continuation
If a statement is too long, you can break it into multiple lines using a backslash or
parentheses ().
Variables in Python
Variables are used to store data. Variable is a label for a location in memory.
Python does not require you to declare the type of a variable explicitly.
The syntax for value assignment to a python variable is:
24
Variable Naming Rules
It may only contain letters (uppercase or lowercase), numbers or the
underscore character () (no spaces!)
They can contain letters, numbers, and underscores.
Variable names are case-sensitive (age, Age and AGE are three different
variables).
Avoid using Python keywords (e.g., if, else, for, while, etc.) as variable names.
It may not start with a number.
Assigning Values:
Use the = operator to assign a value to a variable.
You can assign multiple variables in a single line.
Dynamic Typing:
Python is dynamically typed, meaning you don't need to declare the type of a
variable. The type is determined at runtime.
You can reassign a variable to a different type.
25
26
Global Variables and Local Variables
1-Variables that are created outside of a function (as in all of the examples in the
previous pages) are known as global variables. Can be used by everyone, both inside
of functions and outside.
Example
x = "awesome"
Python is awesome
def myfunc():
print("Python is " + x)
myfunc()
2- Normally, when you create a variable inside a function, that variable is local, and
can only be used inside that function.
Use the type () function to check the type of a variable. Deleting Variables:
Use the del keyword to delete a variable
27
Python Data Types
In programming, data type is an important concept.Variables can store data of
different types, and different types can do different things.Python has the following
data types built-in by default, in these categories:
28
used to store multiple thistuple = ("apple",
items in a single variable.
"banana", "cherry")
Tuples are used to store
multiple items in a single
variable.
my_list = [1, 2, 3]
my_tuple = (1, 2, 3)
29
Getting the Data Type
You can get the data type of any object by using the type() function:
Example
Print the data type of the variable x: <class 'int'>
x = 5
print(type(x))
If you want to specify the data type, you can use the following constructor functions:
30
Programming examples with solutions
x = str("Hello World")
#display x:
Hello World
print(x) <class 'str'>
print(type(x))
x = int(20)
#display x:
20
print(x) <class 'int'>
print(type(x))
x = float(20.5)
#display x:
20.5
print(x) <class 'float'>
print(type(x))
31
x = complex(1j)
#display x:
lj
print(x)
<class 'complex'>
print(type(x))
print(type(x))
print(type(x))
32
Python Operator
Operators are the main building block of any programming language. Operators
allow the programmer to perform different kinds of operations on operands. These
operators can be categorized based upon their different functionality.
Operators are used to perform operations on variables and values. Mostly the
operator finds itself between two operators. In Python expression, operators are “+”
(add) and “=” (equal), and operands are a, b, c. Operands could have either a fixed
value (also known as constant) or a changeable value.
Arithmetic operators
Assignment operators
Comparison operators
Logical operators
Bitwise operators
Arithmetic Operators
33
Operator precedence
Python has a specific and predictable way to determine the order in which it performs
operations. For integer operations, the system will first handle brackets (), then **
then*, // and %, and finally + and-
operators are left- associative, except for **, which is right- associative.
34
35
Assignment Operators
36
Comparison Operators
37
Logical Operators
Logical operators are used to combine conditional statements:
38
Bitwise Operators
39
40
Homework: What are the results of the following operations and explain why:
15 + 20 * 3 = ?
13 // 2 + 3 = ?
31 + 10 // 3 = ?
20 % 7 // 3 = ?
Example 1: write code in python language to add three Numbers and then
print the result?
41
Example 3: write code in python language to find to Convert Celsius to
Fahrenheit?
input(): This function first takes the input from the user and then evaluates the
expression, which means Python automatically identifies whether the user entered a
string or a number or list.
input () function first takes the input from the user and converts it into a string. It
does not evaluate the expression it just returns the complete statement as String. For
example, Python provides a built-in function called input which takes the input from
the user. When the input function is called it stops the program and waits for the
user‟s input. When the user presses enter, the program resumes and returns what the
user typed. Ask for the user's name and print it:
# input() example
name = input("Enter your name:")
print(name)
42
Example 1: Ask for the user’s first name and display the output message Hello
[First Name].
Example 2: Ask the user to enter two numbers. Add them together and
display the answer as the total is [answer].
Example 3: Write a program that will ask for a number of days and then will
show how many hours, minutes and seconds are in that number of days.
Example 4: There are 2,204 pounds in a kilogram. Ask the user to enter a
weight in kilograms and convert it to pounds.
Homework1: Ask for the user’s first name and then ask for their surname and
display the output message Hello [First Name] [Surname].
Homework2: Ask the user to enter three numbers. Add together the first two
numbers and then multiply this total by the third. Display the answer as The
answer is [answer].
43
Chapter 2
Control Structures
44
Conditional statements ( if , else , elif)
In every programming language, we need some structure to make a decision based
on a certain condition. Python if statement helps in making decisions in the program,
this is probably the simplest yet most frequently used in Python for decision making.
Python if else statement works by evaluating a condition and subsequently making
the decision. If a condition is met then execute a certain portion of the code otherwise
execute other portion (which is specified in else or elif sections). In this section, you
will get detailed knowledge on Python if-else statement.
If statements allow your program to make a decision and change the route that is
taken through the program.
An "if statement" is written by using the if keyword, the syntax for a simple if
statement:
The above code will check the condition first, if the condition evaluates to True then
the body part will be executed. The output of the condition section should always be
either True or False.
a = 33
b = 200
if b > a:
print("b is greater than a")
Example1: Write a Python code which prints “Number is bigger than 5” if the
provided number is greater than ( >) 5?
45
Bracket around the condition: If there is only one condition then bracket ( ) is
optional but when there are more than one conditions, the bracket is required. For
example, two conditions are validated with “logical and” operator.
if the condition evaluates to True then the first block will execute but if the
condition is not True (i.e False) then the second block will execute.
Example1: Write a Python code which prints “Number is bigger than 5” if the
provided number is greater than ( >) 5 otherwise print “Number is smaller than
5”?
46
Python Indentation
Always indent the line after the “if (condition):” statement. Indentation means,
a four-space gap or one Tab space from the beginning of the block. Indentation is
necessary otherwise python interpreter will throw an error. This ensures that the code
is inside the if block and it will execute only when the condition is true.
A colon (:) must be placed at the end of if (condition) when writing Python if else
statement.
The elif keyword is Python's way of saying "if the previous conditions were not true,
then try this condition". Let’s modify the scenario a little bit. Now the program
requirement will be, print “Number is bigger than 5” if provided number (in this case
num1) is greater than 5, else “Number is smaller than 5” if the provided number is
less than 5 and add another case to print “Number is equal to 5” if provided number
is equal to 5. Here comes the role of “elif” block
To add more condition apart from if and else, you can use elif.
47
Syntax for Python if-elif-else :
ELIF :The elif keyword is Python's way of saying "if the previous conditions were
not true, then try this condition".
Example1:
a = 33
b = 33
if b > a:
print("b is greater than a")
elif a == b:
print("a and b are equal")
In this example a is equal to b, so the first condition is not true, but the elif
condition is true, so we print to screen that "a and b are equal".
Example2: Write a Python code which prints “Number is bigger than 5” if the
provided number is greater than ( >) 5 otherwise print “Number is smaller than
5”?
48
Example3: Write a program in Python to check a value entered by the user. If
it is between 10 and 20, it prints “Thank you.” Otherwise, it prints something
else.
This uses and to test multiple conditions in the if statement. Both the conditions
must be met to produce the output “Thank you”. Below are examples of the different
comparison and logical operators you can use in the condition line of your if
statement.
49
Below is how the if statement for this flow chart would look in python
ELSE The else keyword catches anything which isn't caught by the preceding
conditions.
Example1 :
a = 200
b = 33
if b > a:
print("b is greater than a")
elif a == b:
print("a and b are equal")
else:
print("a is greater than b")
Notes:
When you are implementing code which contains “if, else and elif” together
then always start with if block, followed by all elif block and finally else
block. There could be one or more elif block possible but it should always
have else at the end.
Do not use “elseif” in-place of “elif” in Python. There is no keyword “elseif”
and Python don’t know what it is.
50
Example1: write code in python language to output student’s grade (A+, A,
B+, B, passed, Failed)?
51
Example2: Ask for two numbers. If the first one is larger than the second,
display the second number first and then the first number, otherwise show the
first number first and then the second.
Example4: Ask the user’s age. If they are 18 or over, display the message “You
can vote”, if they are aged 17, display the message “You can learn to drive”, if
they are 16, display the message “You can buy a lottery ticket”, if they are under
16, display the message “You can go Trick or-Treating”.
52
Homework1: Ask the user to enter a number. If it is under 10, display the
message “Too low”, if their number is between 10 and 20, display “Correct”,
otherwise display “Too high”.
Homework3:
Write a Python program that asks the user to enter the temperature. Then,
print a message indicating the weather condition based on the following
criteria:
If the temperature is 40 or above → "The weather is extremely hot "
If the temperature is between 30 and 39 → "The weather is hot "
If the temperature is between 20 and 29 → "The weather is mild "
If the temperature is below 20 → "The weather is cold "
Python Loops
For Loop
A for loop allows Python to keep repeating code a set number of times. It is
sometimes known as a counting loop because you know the number of times the
loop will run before it starts. With the for loop we can execute a set of statements,
once for each item in a list, tuple, set etc
Python for loop syntax: for loop starts by typing “for” at the beginning followed
by an variable, then after a membership operator in and ends with the range (or
collection). A colon (:) must be present at the end of the line, where “for loop” is
declared, otherwise interpreter will throw an error.
53
The range() Function: To loop through a set of code a specified number of times,
we can use the range() function,The range() function returns a sequence of numbers,
starting from 0 by default, and increments by 1 (by default), and ends at a specified
number.
Example1:
In this example it starts at 1 and will keep repeating the loop (displaying i) until it
reaches 10 and then stops. This is how this loop would look in Python. he outputs
would be 1, 2, 3, 4, 5, 6, 7, 8 and 9. When it gets to 10 the loop would stop so 10
would not be shown in the output.
54
Example2 : Increment the sequence with 3
Note: The for loop does not require an indexing variable to set beforehand .
Example4: Write a Python program that asks the user to enter a positive integer
and print all numbers from 1 to the entered number?
55
Example5: Write a Python program to enter a positive integer,Then calculate
the sum of all even numbers from 1 to that number and display the result ?
Example6: ask the user to enter their name and a number and then display their
name that number of times.
Example7: Set a variable called total to 0. Ask the user to enter five numbers
and after each input ask them if they want that number included. If they do,
then add the number to the total. If they do not want it included, don’t add it
to the total. After they have entered all five numbers, display the total.
Homework1: Ask the user to enter a number between 1 and 12 and then display
the times table for that number.
56
Homework2: Write a Python program that prints only the odd numbers
between 1 and 15.
A while loop
In python executes the code present in the loop’s body as long as the underline
condition remains True. You will want to use while loop in all the situation where
the number of execution is not known in prior. Let’s say you want to keep on printing
the random numbers and loop should break only if the random number is equal to 1.
In this scenario, you can’t use a for loop because you don’t know after how many
iterations the number is going to be 1.
while is the keyword followed by a conditional statement and ends with a colon (:).
Body of the while loop is indented (4 space or 1 tab space), which guarantee that the
indented part falls under the loop execution.
Note: If you don’t provide indentation then Python will throw an error.
57
Example1: A python program to print “valid” until the number is equal to 3.
Start the program with 0
In the above code, while loop will start with a value of 0 and every time
the condition is checked whether the value of i is not equal to 3 or not. If
the value of i is not equal to 3 then the expression evaluates to True and
the body of the loop gets executed. In the body section, a print statement
gets executed first and then i is incremented with 1.
Example2: Ask the user to enter a number. Keep asking until they enter a value
over 5 and then display the message “The last number you entered was a
[number]” and stop the program.
Example3: Ask the user to enter a number between 10 and 20. If they enter a
value under 10, display the message “Too low” and ask them to try again. If
they enter a value above 20, display the message “Too high” and ask them to
try again. Keep repeating this until they enter a value that is between 10 and 20
and then display the message “Thank you”.
58
else statement in while loop
Else statement in while loop is optional and can be used to execute something after
python while loop completes its execution. A typical example of using else statement
in while loop is given below,
Notes:
With the break statement we can stop the loop even if the while condition
is true:
i=1
while i < 6:
1
print(i)
2
if (i == 3): 3
break
i += 1
for x in range(6):
0
1
print(x) 2
3
else: 4
5
print("Finally finished!") Finally finished!
59
Note: The else block will NOT be executed if the loop is stopped by a break
statement.
for i in range(3):
if i == 1:
break
print(i)
else:
Continue Skips the current iteration and moves to the next one.
for i in range(5):
0
if i == 3: 1
2
continue
4
print(i)
Homework: Ask the user to enter a number. Keep asking until they enter a
value over 5 and then display the message “The last number you entered was
a [number]” and stop the program.
60
Chapter 3
Data Structures
61
Data Structures
So far, we have used variables that can store a single item of data in them. When you
used the random.choice([“red”,“blue”,“green”]) line of code you are picking a
random item from a list of possible options. This demonstrates that one item can
hold several pieces of separate data, in this case a collection of colours. There are
several ways that collections of data can be stored as a single item. Three of the
simpler ones are: tuples, lists and dictionaries:
List
Lists are used to store multiple items in a single variable.Lists are one of 4 built-in
data types in Python used to store collections of data, the other 3 are Tuple, Set, and
Dictionary, all with different qualities and usage.Lists are created using square
brackets:
Example1:
int_list = [ 1, 2, 3, 4, 5, 6 ]
float_list = [2.1, 3.45, 6.23, 1.91 ]
list3 = [True, False, False]
List items are ordered, changeable, and allow duplicate values.
Example2:
Create a List:
['apple', 'banana', 'cherry']
thislist = ["apple", "banana", "cherry"]
print(thislist)
2-Write a variable name followed by equal ( = ) sign and then write elements
separated by a comma inside a square bracket.
62
Image shown below is a typical visualization of the list with elements, index and
element value
Note: The data in a list does not all have to be of the same data type. For
example, the same list can store both strings and integers; however, this can
cause problems later and is therefore not recommended.
As we know now that List elements have a unique index (that is why list are known
as an ordered collection). Taking an example and accessing the element by using
the index method in Python.
List elements can be accessed by positive as well as negative index method, Image
below shows how positive and the negative index associated with List.
63
Example1: To get the last element of the list, we can use negative indexing method.
This will display data in positions 1, 2 and 3. In this case 634, 892 and 345.
Remember, Python starts counting from 0 and will stop when it gets to the last
position, without showing the final value.
By leaving out the start value, the range will start at the first item.
Example1: This example returns the items from the beginning to, but NOT
including, "kiwi":
thislist = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]
print(thislist[:4])
You can leaving out the end value, the range will go on to the end of the list:
thislist = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]
print(thislist[2:])
64
Check if Item Exists
List operations
Displays the length of the list (i.e. how many items are in the list).
print(len(x))
Adding element (List Append & List Insert method): To add an element at the
end of a list we can use the append method in Python. Python list Append
method takes only one argument at a time which means we can add only one
element at a time. However, we can add more than one element to a python
list by passing a list itself as argument.
65
Example1
Example2
Add a list to a list:
Using the insert method we can add an element at any specific index location.
Example3
Insert the value "orange" as the second element of the fruit list:
Inserts the number 55 into position 2 and pushes everything else along to make
space. This will change the index numbers of the items in the list
Removing element (List Pop & List Remove method): To remove an element
from a list we have two predominant methods which are pop and remove. To
remove one element from the end of a list we use pop method while to remove
a specific element by its value we use remove method. We can also pass an
argument to pop method to remove an element by its index.
66
Example1
Remove the second element of the fruit list:
fruits = ['apple', 'banana', 'cherry']
['apple', 'cherry']
fruits.pop(1)
Note: If you do not specify the index, the pop() method removes the last item.
Example2
Remove the last element of the fruit list:
fruits = ['apple', 'banana', 'cherry']
['apple', 'banana']
fruits.pop()
Example3
Remove "banana":
Note: If there are more than one item with the specified value,
the remove() method removes the first occurrence:
Example4
Remove the first occurrence of "banana":
67
Dictionaries
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
very key is connected to its value by a colon, and individual key value pairs are
separated by commas. You can store as many key value pairs as you want in a
dictionary.
Note: A dictionary is a collection which is unordered, changeable and do not
allow duplicates.
Example
thisdict = {
"brand": "Ford", {'brand': 'Ford', 'electric': False, 'year': 1964, 'colors':
"electric": False, ['red', 'white', 'blue']}
"year": 1964,
"colors": ["red", "white", "blue"]
}
68
2- Using dict () method
Dictionary can also be created using python dict method as shown below:
dict2 = dict()
print(dict3)
Example1
Print the "brand" value of the dictionary:
thisdict = {
"brand": "Ford", "model": "Mustang", "year": 1964 Ford
}
print(thisdict["brand"])
Example2
Get the value of the "model" key
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964 Mustang
}
x = thisdict["model"]
print(x)
69
Note: Dictionaries can still use integer values as keys, just like lists use integers
for indexes, but they do not have to start at 0 and can be any number
Example3: Ask the user to enter four of their favourite foods and store them
in a dictionary so that they are indexed with numbers starting from 1. Display
the dictionary in full, showing the index number and the item. Ask them
which they want to get rid of and remove it from the list. Sort the remaining
data and display the dictionary.
2- get():There is also a method called get() that will give you the same result:
Example: Get the value of the "model" key:
x = thisdict.get("model")
If the key is not present then we can pass additional (it is optional) argument.
Fortunately, dictionaries have a get() method that takes two arguments: the key of
the value to retrieve and a fallback value to return if that key does not exist.
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
print(thisdict.get('color ',0))
70
3- dictionary methods: There are three dictionary methods that will return list-like
values of thedictionary’s keys, values, or both keys and values: keys(), values(), and
items().The values returned by these methods are not true lists: they cannot be
modified and do not have an append() method. But these data types (dict_keys,
dict_values,and dict_items, respectively) can be used in for loops.
thisdict = {
"brand": "Ford",
2: "Mustang",
"year": 1964 dict_keys(['brand', 2, 'year'])
}
print(thisdict.keys())
values() method: A values () method is used to get all the values of a dictionary.
Let’s understand it via an example.
thisdict = {
"brand": "Ford",
2: "Mustang",
"year": 1964 dict_values(['Ford', 'Mustang',
} 1964])
print(thisdict.values())
items() method: A items () method in is used to get all the key-values pair of
a dictionary. Let’s understand it via an example.
thisdict = {
"brand": "Ford",
2: "Mustang", dict_items([('brand', 'Ford'), (2, 'Mustang'),
"year": 1964 ('year', 1964)])
}
print(thisdict.items())
71
Notes:
1- To determine how many items a dictionary has, use the len() function:
thisdict = {
"brand": "Ford",
2: "Mustang", 3
"year": 1964
}
print(len(thisdict))
2- Adding an item to the dictionary is done by using a new index key and
assigning a value to it:
thisdict = {
"brand": "Ford",
2: "Mustang", {'brand': 'Ford', 2: 'Mustang', 'year': 1964,
"year": 1964 'color': 'red'}
}
thisdict["color"] = "red"
print(thisdict)
The data types (dict_keys, dict_values, and dict_items, respectively) can be used in
for loops.
72
Example1:
Example:
Syntax
dictionary.setdefault(keyname, value)
73
In this example, the key “AI” is present. The setdefault method will output the actual
value (which is 1, in this case).
In this example, the key “DS” is NOT present. The setdefault method will output a
None value as well as it will also insert the new key-value pair in the dictionary, as
shown below.
In this example, the key “DS” is present. The setdefault method should output None
value BUT since the number 4 is passed with the setdefault method, so it will return
4 as the output. Additionally, the new value will be assigned to the key in the
dictionary, as shown below.
Tuples
A tuple in Python is an immutable data type, meaning once it is created, its elements
cannot be modified, added, or removed. Tuple are used to store multiple items in a
single variable. Tuple is one of 4 built-in data types in Python used to store
collections of data, the other 3 are List, Set, and Dictionary, all with different
qualities and usage. A tuple is a collection which is ordered and unchangeable.
74
Tuples are written with round brackets. Example: Create a Tuple: thistuple =
("apple", "banana", "cherry") print(thistuple)
Tuple Items Tuple items are ordered, unchangeable, and allow duplicate
values.Tuple items are indexed, the first item has index [0], the second item has
index [1] etc.
Characteristics:
•Tuples can store elements of different data types.
•Elements are accessed using indexing.
•Tuples allow duplicate values (repeated elements).
•Once created, tuples are immutable (cannot be changed).
Example1
Creating a Tuple:
Example1
Accessing Tuple Elements:
# Output: 1
•Tuples are used when you need to store data that should not change.
•They are commonly used for returning multiple values from functions.
Difference between Tuples and Lists :
•Tuples are immutable (cannot be changed), while lists are mutable (can be
Modified)
•Lists are used when data may need to change, whereas tuples are used when you
want fixed data.
75
Example1: Create a tuple containing the names of five countries and display
the whole tuple. Ask the user to enter one of the countries that have been
shown to them and then display the index number (i.e. position in the list) of
that item in the tuple.
Example2: Add to program in example1 to ask the user to enter a number and
display the country in that position.
Homework1:
Create a tuple of 6 animals.
Display the third and fifth animals using indexing.
Homework2:
Create a tuple named months containing the names of the first six months of
the year.
Display the second and the last month in the tuple.
76
Sets
Characteristics:
•Sets do not maintain order, so you cannot access elements by index.
•They do not allow duplicate elements.
•You can add and remove elements from a set.
Creating a Set:
77
Basic Set Operations:
78
Chapter 4
Functions
79
Python Functions
A function is a block of code designed to perform a specific task. It runs only when
called. You can pass data, known as parameters, into a function, and it can return a
result. Functions help break down complex problems into smaller, more manageable
parts, making programs easier to understand and reuse.
Creating a Function
In Python a function is defined using the def keyword:
def greet():
print("Hello world")
Calling a Function
In the above example, we have declared a function named greet().If we run the above
code, we won't get an output. It's because creating a function doesn't mean we are
executing the code inside it. It means the code is there for us to use if we want to.
To use this function, we need to call the function.
To call a function, use the function name followed by parenthesis:
80
Example1: Python Function Call
In the above example, we have created a function named greet(). Here's how the
control of the program flows:
Function Arguments
Arguments are inputs given to the function. Arguments are specified after the
function name, inside the parentheses. You can add as many arguments as you want,
just separate them with a comma.
The following example has a function with one argument (fname). When the
function is called, we pass along a first name, which is used inside the function to
print the full name:
81
Example1:
def my_function(fname):
print(fname + " Refsnes") Output:
82
Arguments
Arguments are the actual values that we pass to the function when we call it.
Arguments replace the parameters when the function executes.
print_age(25) # 25 is an argument
Here, during the function call, the argument 25 is passed to the function.
Note: The return statement also denotes that the function has ended. Any code
after return is not executed.
Return Values: To let a function return a value, use the return statement:
Example2:
def my_function(x):
return 5 * x Output:
15
print(my_function(3)) 25
print(my_function(5)) 45
print(my_function(9))
83
The pass Statement
The pass statement serves as a placeholder for future code, preventing errors from
empty code blocks. It's typically used where code is planned but has yet to be written.
Homework:
Write Python program that uses functions to create a basic calculator for
addition, subtraction, multiplication, and division.
Here, the sum variable is created inside the function, so it can only be accessed
within it.
Based on the scope, we can classify Python variables into three types:
1. Local Variables
2. Global Variables
3. Nonlocal Variables
When we declare variables inside a function, these variables will have a local
scope (within the function). We cannot access them outside the function.
These types of variables are called local variables. For example:
84
Local Scope: A variable created inside a function belongs to the local scope of that
function, and can only be used inside that function.
Example1
A variable created inside a function is available inside that function:
def myfunc():
x = 300
print(x) Output : 300
myfunc()
Function Inside Function: As explained in the example above, the variable x is not
available outside the function, but it is available for any function inside the function:
Example2
The local variable can be accessed from a function within the function:
def myfunc():
x = 300
def myinnerfunc():
print(x) Output : 300
myinnerfunc()
myfunc()
85
In Python, a variable declared outside of the function or in global scope is known
as a global variable. This means that a global variable can be accessed inside or
outside of the function.
Let's see an example of how a global variable is created in Python.
Note: If you operate with the same variable name inside and outside of a
function Python will treat them as two separate variables, one available in the
global scope (outside the function) and one available in the local scope (inside
the function):
Example1:
The function will print the local x, and then the code will print the global x:
A variable created outside of a function is global and can be used by anyone:
x = 300
GLOBAL KEYWORD
If you need to create a global variable, but are stuck in the local scope, you can use
the global keyword. The global keyword makes the variable global.
86
Example2
If you use the global keyword, the variable belongs to the global scope:
def myfunc():
global x
x = 300 Output: 300
myfunc()
print(x)
Also, use the global keyword if you want to make a change to a global variable
inside a function.
Example3
To change the value of a global variable inside a function, refer to the variable
by using the global keyword:
x = 300
def myfunc():
global x
Output: 200
x = 200
myfunc()
print(x)
87
In the above example, there is a nested inner() function. The inner() function is
defined in the scope of another function outer().
We have used the nonlocal keyword to modify the message variable from the outer
function within the nested function.
Note: If we change the value of a nonlocal variable, the changes appear in the
local variable.
88
Chapter 5
Working with files
89
Working with files
An incredible amount of data is available in text files. Text files can contain
weather data, traffic data, socioeconomic data, literary works, and more. Reading
from a file is particularly useful in data analysis applications, but it’s also
applicable to any situation in which you want to analyze or modify information
stored in a file. Python provides various functions to perform different file
operations, a process known as File Handling.
In Python, we need to open a file first to perform any operations on it—we use the
open() function to do so. The open() function takes two parameters: filename, and
mode.
There are four different methods (modes) for opening a file:
"r" - Read - Default value. Opens a file for reading, error if the file does not
exist
"a" - Append - Opens a file for appending, creates the file if it does not exist
"w" - Write - Opens a file for writing, creates the file if it does not exist
"x" - Create - Creates the specified file, returns an error if the file exists
"t" - Text - Default value. Text mode
"b" - Binary - Binary mode (e.g. images)
"+" - Open a file in both read and write mode
Syntax
f = open("demofile.txt")
or
f = open("demofile.txt", "rt")
Because "r" for read, and "t" for text are the default values, you do not need to
specify them.
Note: Make sure the file exists, or else you will get an error.
After we open a file, we use the read() method to read its content. For example:
Suppose we have a file named file1.txt.
91
Read Only Parts of the File
By default the read() method returns the whole text, but you can also specify many
parts you want to return:
Read characters: specify how many characters you want to return, for example:
f = open("file1.txt", "r" )
print(f.read(5))
Read Line: You can return one line by using the readline() method,for example
Read one line of the file:
f = open("file1.txt", "r" )
print(f.readline())
By calling readline() two times, you can read the two first lines:
By looping through the lines of the file, you can read the whole file, line by line:
f = open("file1.txt", “r”)
for x in f:
print(x)
92
Note: The readlines() method: This function reads all of the lines and returns
them as string elements in a list.
When we run the above code, we will see the specified content inside the file.
If we try to perform the write operation to a file that already has some content, the
new content will replace the existing ones. For example:
93
When we run the above code, the new content will replace any existing content in
file2.txt.
Note: If we try to open a file that doesn't exist, a new file is created, and the
write() method will add the content to the file.
Example2:
Write a new file called “Numbers.txt”. Add five numbers to the document
which are stored on the same line and only separated by a comma. Once you
have run the program, look in the location where your program is stored and
you should see that the file has been created. The easiest way to view the
contents of the new text file on a Windows system is to read it using Notepad.
file = open("Countries.txt","w")
file.write("Italy\n")
file.write("Germany\n")
file.write("Spain\n")
file.close()
Creates a file called “Countries.txt”. If one already exists then it will be overwritten
with a new blank file. It will add three lines of data to the file (the \n forces a new
line after each entry). It will then close the file, allowing the changes to the text file
to be saved.
94
Example3: Write a new file called “Numbers.txt”. Add five numbers to the
document which are stored on the same line and only separated by a comma.
Once you have run the program, look in the location where your program is
stored and you should see that the file has been created. The easiest way to view
the contents of the new text file on a Windows system is to read it using Notepad.
Example4: Open the Names.txt file. Ask the user to input a new name. Add this
to the end of the file and display the entire file.
Example5: Open the Names.txt file and display the data in Python.
95
Chapter 6
Modules and Libraries
96
Modules
What is a module?
Module is a file that contains code to perform a specific task.
A module may contain variables, functions, classes etc. Consider a module to be the
same as a code library.
Create a Module
To create a module just save the code you want in a file with the file extension .py.
Let us create a module and save it as example.py.
97
Example1
Import the module named mymodule, and call the greeting function:
import mymodule
mymodule.greeting("Jonathan")
syntax: module_name.function_name.
Also variables of all types (arrays, dictionaries, objects etc) can access by Import the
module named for example access the person1 dictionary:
Save this code in the file mymodule.py
Import the module named mymodule, and access the person1 dictionary:
Renaming a Module
In Python, we can also import a module by renaming it, by using the as keyword:
For example:
Create an alias for mymodule called mx :
98
Built-in Modules
The Python standard library contains well over 200 modules. We can import a
module according to our needs. Suppose we want to get the value of pi, first we
import the math module and use math.pi. For example:
Note: The dir() function can be used on all modules, also the ones you create
yourself.
99
Python libraries (NumPy and pandas)
1. NumPY
NumPy is a Python library used for working with arrays.
It also has functions for working in domain of linear algebra, fourier transform, and
matrices.
NumPy was created in 2005 by Travis Oliphant. It is an open source project and
you can use it freely. NumPy stands for Numerical Python.
Installation of NumPy
If you have Python and PIP already installed on a system, then installation of
NumPy is very easy.
Install it using this command:
C:\Users\Your Name>pip install numpy
If this command fails, then use a python distribution that already has NumPy
installed like, Anaconda, Spyder etc.
100
Import NumPy
Once NumPy is installed, import it in your applications by adding the import
keyword:
import numpy
Now NumPy is imported and ready to use.
import numpy
arr = numpy.array([1, 2, 3, 4, 5])
print(arr)
NumPy is usually imported under the np alias. Create an alias with the as keyword
while importing:
import numpy as np
Example
import numpy as np
arr = np.array([1, 2, 3, 4, 5])
print(arr)
Result: [1 2 3 4 5]
1.NumPy is used to work with arrays. The array object in NumPy is called ndarray.
We can create a NumPy ndarray object by using the array() function.
Example:
import numpy as np
arr = np.array([1, 2, 3, 4, 5])
print(arr)
print(type(arr))
Result: [1 2 3 4 5]
<class 'numpy.ndarray'>
101
2. Pandas
Pandas is a Python library used for working with data sets.It has functions for
analyzing, cleaning, exploring, and manipulating data.The name "Pandas" has a
reference to both "Panel Data", and "Python Data Analysis" and was created by Wes
McKinney in 2008.
Pandas are also able to delete rows that are not relevant, or contains wrong values,
like empty or NULL values. This is called cleaning the data.
Installation of Pandas
If you have Python and PIP already installed on a system, then installation of Pandas
is very easy.
Install it using this command:
If this command fails, then use a python distribution that already has Pandas installed
like, Anaconda, Spyder etc.
Import Pandas
Once Pandas is installed, import it in your applications by adding the import
keyword:
import pandas
102
Now Pandas is imported and ready to use.
103
Chapter 7
Data Analysis in Python
104
Introduction to Data Analysis in Python
Data analysis is the process of inspecting, cleaning, transforming, and modeling
data to discover useful information.
Python has become one of the most popular languages for data analysis because it is
simple, powerful, and has many useful libraries.
Pandas is a Python library that provides flexible data structures for handling
structured data.
Result:
105
Example: Creating a DataFrame
import pandas as pd
d = {'col1': [1, 2, 3, 4, 7], 'col2': [4, 5, 6, 9, 5], 'col3 ]11 ,1 ,12 ,8 ,7[ :'}
df = pd.DataFrame(data=d)
print(df)
Example Explained
Note: We write pd. in front of DataFrame() to let Python know that we want to activate
the DataFrame() function from the Pandas library.
106
We see that "col1", "col2" and "col3" are the names of the columns.
Do not be confused about the vertical numbers ranging from 0-4. They tell us the
information about the position of the rows.
Example
Count the number of columns:
import pandas as pd
d = {'col1': [1, 2, 3, 4, 7], 'col2': [4, 5, 6, 9, 5], 'col3 ]11 ,1 ,12 ,8 ,7[ :'}
df = pd.DataFrame(data=d)
count_column = df.shape]1[
print("Number of columns:")
print(count_column)
Result:
107
Example
Count the number of rows:
import pandas as pd
d = {'col1': [1, 2, 3, 4, 7], 'col2': [4, 5, 6, 9, 5], 'col3': [7, 8, 12, 1, 11]}
df = pd.DataFrame(data=d)
count_row = df.shape[0]
print("Number of rows:")
print(count_row)
Result:
What is Matplotlib?
108
Installation of Matplotlib
If you have Python and PIP already installed on a system, then installation of
Matplotlib is very easy.
If this command fails, then use a python distribution that already has Matplotlib
installed, like Anaconda, Spyder etc.
Import Matplotlib
import matplotlib
Example
import matplotlib
print(matplotlib.__version__)
Result: 2.0.0
Matplotlib Pyplot
Most of the Matplotlib utilities lies under the pyplot submodule, and are usually
imported under the plt alias:
109
Example:
Draw a line in a diagram from position (0,0) to position (6,250):
import sys
import matplotlib
matplotlib.use('Agg')
import numpy as np
plt.plot(xpoints, ypoints)
plt.show()
plt.savefig(sys.stdout.buffer)
sys.stdout.flush()
Result:
110
Seaborn
Install Seaborn.
Displots
Displot stands for distribution plot, it takes as input an array and plots a curve
corresponding to the distribution of points in the array.
Import Matplotlib
Import the pyplot object of the Matplotlib module in your code using the following
statement:
Import Seaborn
Import the Seaborn module in your code using the following statement:
111
Plotting a Displot
Example
Result:
Result:
112
Resources:
1. W3Schools Tutorials
🔗 https://www.w3schools.com/python/default.asp
113
Resources to Help You Learn Code:
"Boost your coding skills! Explore these resources, practice regularly, and
enjoy your journey to becoming a confident programmer"
1. https://pandas.pydata.org/docs/
2. https://matplotlib.org/stable/contents.html
3. https://seaborn.pydata.org/
4. https://www.kaggle.com/learn
5. https://realpython.com/
6. https://www.codecademy.com/learn/learn-python-3
7.
8. https://www.coursera.org?utm_source=chatgpt.com
9.
10.
11.
12.
114