0% found this document useful (0 votes)
10 views114 pages

Python Book

Uploaded by

ameenayad2010
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)
10 views114 pages

Python Book

Uploaded by

ameenayad2010
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

‫‪Prepared by‬‬

‫م‪.‬م‪ .‬وسن محمد جعفر‬ ‫م‪ .‬رشا قاسم حمادي‬

‫زهراء راجي حمزة‬ ‫هبة قيس عبدالجليل‬

‫‪1‬‬

‫‪2025 - 2026‬‬
Table of Contents

Chapter1 Introduction to Python


 Python overview and installation
 Understanding Python syntax
 Variables, data types, and basic operations
Chapter2 Control Structures
 Conditional statements (if, else, elif)
 Loops (for, while)
Chapter3 Data Structures
 Lists and list operations
 Dictionaries and their applications
 Tuples and sets
Chapter4 Functions
 Defining and calling functions
 Function arguments and return values
 Scope and lifetime of variables
Chapter5 Working with Files
 Reading and writing files
Chapter6 Modules and Libraries
 Importing modules
 Utilizing popular Python libraries (e.g., NumPy, pandas)
 Creating custom modules
Chapter7 Data Analysis with Python
 Introduction to data analysis
 Data manipulation using pandas
 Visualization with Matplotlib and Seaborn

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:

 Web development (server-side).


 Software development.
 Mathematics.
 System scripting.

History of python:

4
What can Python do?

 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?

 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.

Who Uses Python?

Google NASA Cisco Dropbox Yahoo Netflix


(Youtube)
IBM Quora Mozilla Git Hub Instagram and many
more

5
Python installation

Step 1: Download the installer:


 Go to the official Python website: python.org/downloads/.

 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.

The installation window shows two checkboxes:

 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.

 In the installer, choose "Install Now" or "Customize Installation".


 Important: Check the box that says "Add Python to PATH" to make Python
accessible from the command line.

The default installation installs Python to


C:\Users\[user]\AppData\Local\Programs\Python\Python[version]
for the current user.

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

Customizing the installation allows changing these installation options and


parameters.

 Choose the optional installation features. Python works without these


features, but adding them improves the program's usability.

Click Next to proceed to the Advanced Options screen.

 The second part of customizing the installation includes advanced options.

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

To add Python to PATH, do the following:

1. In the Start menu, search for Environment Variables and press Enter.

10
2.Click Environment Variables to open the overview screen.

3. Double-click Path on the list to edit it.

Alternatively, select the variable and click the Edit button.

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.

Step 4: Verify Python Was Installed on Windows


The first way to verify that Python was installed successfully is through the
command line. Open the command prompt and run the following command:

python – version Copy

The output shows the installed Python version

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:

1. Navigate to the directory where Python was installed on the system.


2.Double-click python.exe (the Python interpreter) or IDLE.
3. The interpreter opens the command prompt and shows the following window:

Running IDLE opens Python's built-in IDE:

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:

'pip' is not recognized as an internal or external command,


Operable program or batch file. Copy

If an older version of Python is installed or the PIP installation option is disabled


during installation, PIP will not be available. To install PIP, see our article How to
Install PIP on Windows.

Step 6: Install virtualenv (Optional)


Python software packages install system-wide by default. Consequently, whenever
a single project-specific package is changed, it changes for all your Python projects.

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.

To install virtualenv, run the following command in the command prompt:

pip install virtualenv

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

code editors Description


Visual Studio Code A free, lightweight, and highly
https://code.visualstudio.com/download customizable code editor with Python
support through extensions
PyCharm A full-featured IDE by JetBrains; the
https://www.jetbrains.com/pycharm/ Community version is free, while the
Professional version includes advanced
tools
|Thonny A beginner-friendly Python IDE with a
simple interface and step-by-step
debugging tools
Spyder An open-source IDE geared toward
scientific programming and data
science; integrates with libraries like
NumPy, Pandas, and Matplotlib
IDLE The default Python editor that comes
with the installation, ideal for simple
scripting
Sublime Text A sleek, fast code editor, highly
customizable but requires a license for
full use
Atom An open-source, extensible editor built
by GitHub, supports Python via plugins
Jupyter Notebook A web-based interactive environment
that combines code, text, and visuals
perfect for data analysis and teaching

18
Key Feachers of Python Programing
Basic Syntax:

1. Hello World: A typical starting point in any programming language is


printing "Hello, World!" to the console.

print("Hello , world!")

2. Variables: In Python, you don't need to declare variable types explicitly.


Python automatically determines the type based on the assigned value.

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.

# This is a single-line comment


"""
this is a multi-line comment
or docstring.
"""

4. Data Types: Python has several built-in data types:

• Numbers: int, float


• Strings: Sequences of characters, enclosed in either single or double quotes.

• Booleans: True or False


• Lists: Ordered collection of items.

• Tuples: Immutable ordered collection of items.


• Dictionaries: Key-value pairs.

• Sets: Unordered collection of unique items.

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:

for i in range(5): # Integers over the numbers 0-4


print(i)

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

Note: remember to increment i, or else the loop will continue forever.

20
6. Functions: You can define functions in Python using the def keyword.

def greet (name) :


return f"Hello, {name}!"
message = greet("Alice")
print(message)

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

pip install library_name

Example using math libraries


import math

print(math.sqrt(16)) #prints 4.0


print(math.pi) #prints 3.141592653589793

Object-Oriented Programming (OOP): Python supports OOP. You can


define classes and create objects.
class Dog :
def __init__(self , name , age) :
self.name = name
self.age = age

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

 Python uses indentation (spaces or tabs) to define blocks of code instead of


braces.}{
 Standard practice is to use 4 spaces per indentation level
 Python syntax can be executed by writing directly in the Command Line:
>>> print("Hello, World!")
Hello, World!

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

Homework: is indentation in Python used for readability only? (True or False)

Running Your Program


You can run the program by selecting the Run menu and selecting Run Module.
Alternatively, you can press the [F5] key. If this is the first time the program is saved,
Python will prompt you to name and save the file before it will allow the program to
run.

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

Create a variable outside of a function, and use it inside the function:

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.

Checking Variable Type:

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

Data types Description Examples


Text (str) Designed to handle x = "Hello World"
strings, texts, characters
Strings (str) and words. They are
mostly used to hold the
string and to display the
information using some name = "Alice."
function such as print
statement. Strings are
always defined and
displayed under the single
quotation (‘ ‘) or the
double quotation (“ ”).
Numeric To deal with numeric X=2023
(int ,float,complex) (both Negative and
z = -3255522
Positive number
including zero) value in X=343.432
python. An integer
z = -35.59
constant is written as an
integer—0, –11, +33, Complex=1j
123456—and has
x = 3+5j y = 5j
unlimited range. A float
can be written with
adecimal point, can be
scientific numbers with
an "e" to indicate the
power of 10.
complex numbers are
written with a "j" as the
imaginary part
Sequence Operating on the thislist = ["apple",
(list, tuple ) collection of more than
"banana", "cherry"]
one number. Lists are

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)

Set (set) Sets are used to store thisset = {"apple",


multiple items in a single "banana", "cherry"}
variable.
A set is a collection my_set = {1, 2, 3}
which is unordered,
unchangeable*, and
unindexed.
Mapping(dict) Dictionaries are used to x = {"name" : "John",
store data values in key: "age" : 36}
value pairs.
Dictionaries (dict) This is a very powerful my_dict={"key":
datatype to hold a lot of "value"}
related information t
associated through keys.
The main operation of a
dictionary is to extract a
value based on the key
name.
Unlike lists, wh numbers
are used, dictionaries
allow the use of a key to
access its members.
Dictionaries can also be
used to sort, iterate and
compare data.
Dictionaries are created
by using braces ({}) with
pairs separated by a
comma (.) and the key
values associated with a
colon(:).

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

Setting the Specific Data Type

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'>

#display the data type of x:

print(type(x))

x = int(20)

#display x:
20
print(x) <class 'int'>

#display the data type of x:

print(type(x))

x = float(20.5)

#display x:
20.5
print(x) <class 'float'>

#display the data type of x:

print(type(x))

31
x = complex(1j)

#display x:
lj
print(x)
<class 'complex'>

#display the data type of x:

print(type(x))

x = list(("apple", "banana", "cherry"))

#display x: ['apple', 'banana', 'cherry']


print(x) <class 'list'>

#display the data type of x:

print(type(x))

x = tuple(("apple", "banana", "cherry"))

#display x: ('apple', 'banana', 'cherry')


<class 'tuple'>
print(x)

#display the data type of 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.

Python divides the operators in the following groups:

 Arithmetic operators
 Assignment operators
 Comparison operators
 Logical operators
 Bitwise operators

 Arithmetic Operators

Arithmetic operators are used with numeric values to perform common


mathematical operations:

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-

If an expression contains multiple operations which are at the same level of


precedence, like*, and %, they will be performed in order, either from left to right
(for left- associative operators) or from right to left (for right-associative operators).
All these arithmetic

operators are left- associative, except for **, which is right- associative.

34
35
Assignment Operators

Assignment operators are used to assign values to variables:

36
Comparison Operators

Comparison operators are used to compare two values:

37
Logical Operators
Logical operators are used to combine conditional statements:

38
Bitwise Operators

Bitwise operators are used to compare (binary) numbers:

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?

Example 2: write code in python language to find area of circle?

41
Example 3: write code in python language to find to Convert Celsius to
Fahrenheit?

Basics of data Input

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

"Learning is a journey—enjoy every step!"

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.

Python’s simple if 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.

else statement in Python


In the above program, when you provide any number greater than (>) 5, you will
get the result as “Number is bigger than 5” but what will happen if “num1” is less
than 5.
Here comes the role of else block.

The syntax for a Python if else statement:

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

Python uses indentation to highlight the blocks of code.


Whitespace is used for indentation in Python. All statements with the same distance
to the right belong to the same block of code. If a block has to be more deeply nested,
it is simply indented further to the right. You can understand it better by looking at
the following lines of code.

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.

elif statement in python

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.

Example3:Ask the user to enter a number between 10 and 20 (inclusive). If they


enter a number within this range, display the message “Thank you”, otherwise
display the message “Incorrect answer”.

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”.

Homework2: Ask the user to enter 1, 2 or 3. If they enter a 1, display the


message “Thank you”, if they enter a 2, display “Well done”, if they enter a 3,
display “Correct”. If they enter anything else, display “Error message”.

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

Python has two primitive loop commands:


for loop
while loop

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:

for i in range(1, 10):


print(i)

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.

The range() function defaults to increment the sequence by 1, however it is possible


to specify the increment value by adding a third parameter: range(2, 30, 3):

54
Example2 : Increment the sequence with 3

for x in range(2, 30, 3):


print(x)

Homework: Write a Python program that uses a for loop to print a


descending sequence starting from 50 down to 25, decreasing by 3 each time.

👉 also, write the expected output of your program.

Note: The for loop does not require an indexing variable to set beforehand .

Example3: Write a program in Python to print counting Number 50 to 80?

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.

👉 also, write the expected output.

Homework3: Write a Python program that prints the sequence of cubes of


numbers from 1 to 5.

👉 also, write the expected output.

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.

A while loop allows code to be repeated an unknown number of times as long as a


condition is being met. This may be 100 times, just the once or even never. In a while
loop the condition is checked before the code is run, which means it could skip the
loop altogether if the condition is not being.

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

 The else keyword in a for loop specifies a block of code to be executed


when the loop is finished:

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:

print("This line will not be executed")

 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

"Code, break, fix, repeat… that’s how you grow!"

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)

Method to create a List in Python


1- We can create an empty list (list without any element) in python. This means an
instance of a list is created but there is no element in it.

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.

Accessing elements of the list

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.

Slicing List elements with the index method


Slicing, in general, means getting a part of anything. List slicing means getting a
portion of the list such as the first four elements of the list or last three elements of
the list. We can also use the index method to slice elements between any two indexes
etc. Always remember, in python, the list index starts from zero (0).
Syntax: list_name [start index : stop index ]

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

To determine if a specified item is present in a list use the in keyword.

Example2: Check if "apple" is present in the list:

thislist = ["apple", "banana", "cherry"]


if "apple" in thislist: Yes, 'apple' is in the fruits list
print("Yes, 'apple' is in the fruits list")

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

Add an element to the fruits list:

fruits = ['apple', 'banana', 'cherry']


['apple', 'banana', 'cherry', 'orange']
fruits.append("orange")

Example2
Add a list to a list:

a = ["apple", "banana", "cherry"]


b = ["Ford", "BMW"]
['apple', 'banana', 'cherry', ["Ford", "BMW"]]
a.append(b)

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:

fruits = ['apple', 'banana', 'cherry']


fruits.insert(1, "orange") ['apple', 'orange', 'banana', 'cherry']

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

thislist = ["apple", "banana", "cherry"]


thislist.remove("banana") ['apple', 'cherry']
print(thislist)

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

thislist = ["apple", "banana", "cherry", "banana", "kiwi"]


thislist.remove("banana")
['apple', 'cherry', 'banana', 'kiwi']
print(thislist)

67
Dictionaries

A dictionary in Python is a collection of key-value pairs. Each key is connected to


a value, and you can use a key to access the value associated with that key.A key’s
value can be a number, a string, a list, or even another dictionary.In fact, you can use
any object that you can create in Python as a value in adictionary .In Python, a
dictionary is wrapped in braces, { }, with a series of key value pairs inside the braces,
as shown in the example:

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.

How to create Python dictionary


1- Using curly braces

dict1 = { } # to create an empty dictionary


print (dict1)

Example

String, int, boolean, and list data types:

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

dict3 = dict({'John' : 1 , 'feb' : 2}) {'John': 1, 'feb': 2}

print(dict3)

Accessing dictionary elements


As you know, a dictionary consists of one or more key-value pairs. There are built-
in methods to get the individual element from a dictionary.
1- key name :You can access the items of a dictionary by referring to its key name,
inside square brackets: Dictionary Items Dictionary items are ordered, changeable,
and do not allow duplicates. Dictionary items are presented in key:value pairs, and
can be referred to by using the key name.

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.

 keys() method: A keys () method in is used to get all the keys of a


dictionary. Let’s understand it via an example.

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)

For loop iterate through dictionary python


A for loop can also be used to iterate through the keys of the dictionary and will
return you current key and the corresponding value. A typical example to use for
loop over dictionary is shown below:

The data types (dict_keys, dict_values, and dict_items, respectively) can be used in
for loops.

72
Example1:

Checking Whether a Key or Value Exists in a Dictionary


You can use in and not in operators to see whether a certain key or value exists in a
dictionary.

Example:

Python Dictionary method

 setdefault ( ) method: The setdefault() method returns the value of a key if


the key is present in the dictionary. If the key is not present, we can choose to
set a default value for that key. In the absence of default value, it would return
None.

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:

my_tuple = (1, 2, 3 , "Hello")


print(my_tuple)

# output : (1, 2, 3, 'Hello')

Example1
Accessing Tuple Elements:

my_tuple = (1, 2, 3 , "Hello")


print(my_tuple[0])

# Output: 1

Tuple Use Cases :

•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

A set is an unordered collection of unique elements. It is used when you.need to store


a collection of distinct items, without worrying about the order.

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.

Set Use Cases:


• Sets are ideal for operations that involve uniqueness or membership checking.
• They are used when you need to eliminate duplicates or perform mathematical
set operations like union, intersection, and difference

Creating a Set:

thisset = {"apple", "banana", "cherry"}


print(thisset)
# Note: the set list is unordered, meaning: the items will appear in a random
order.
#output: {'banana', 'cherry', 'apple'}
# Refresh this page to see the change in the result.
#output: {'banana', 'apple', 'cherry'}

Accessing Set Elements


You cannot access set elements using indexes. Instead, you can iterate through the
set or use set operations.

77
Basic Set Operations:

78
Chapter 4
Functions

"Your keyboard is your tool, your imagination is the limit."

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

Here are the different parts of the program:

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:

my_function("Emil") Emil Refsnes


Tobias Refsnes
my_function("Tobias")
Linus Refsnes
my_function("Linus")

Example2: Function to Add Two Numbers?

In the above example, we have created a function named add_numbers() with


arguments: num1 and num2.

Parameters and Arguments


Parameters
Parameters are the variables listed inside the parentheses in the function definition.
They act like placeholders for the data the function can accept when we call them.
Think of parameters as the schema that outlines what kind of information the
function expects to receive.

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.

The return Statement

We return a value from the function using the return statement.


Example1: The function accepts a number and returns the square of the number.

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.

Python Variable Scope


A variable is only available from inside the region it is created. This is called scope.
A variable scope specifies the region where we can access a variable. For example:

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

1. Python Local 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()

2. Python Global Variables


Global Scope: A variable created in the main body of the Python code is a global
variable and belongs to the global scope.Global variables are available from within
any scope, global and local.

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

def myfunc(): Output:


x = 200
print(x) 200
300
myfunc()
print(x)

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)

3. Python Nonlocal Variables


In Python, the nonlocal keyword is used within nested functions to indicate that a
variable is not local to the inner function, but rather belongs to an enclosing
function’s scope.
This allows you to modify a variable from the outer function within the nested
function, while still keeping it distinct from global variables.

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

"Don’t be afraid to make mistakes—they are your stepping stones."

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.

Opening Files in Python

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.

Opening a file using its full path


90
We can also open a file using its full path.

Note: Make sure the file exists, or else you will get an error.

Here are a few examples of opening a file in different mode:

Reading Files in Python

After we open a file, we use the read() method to read its content. For example:
Suppose we have a file named file1.txt.

Now, let's read the content of the file.

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:

Return the 5 first characters of the file:

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:

Read two lines of the file:


f = open("file1.txt", “r”)
print(f.readline())
print(f.readline())

By looping through the lines of the file, you can read the whole file, line by line:

Loop through the 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.

Closing Files in Python


When we are done performing operations on the file, we need to close the file
properly. We use the close() function to close a file in Python. For example:

Writing to files in python


To write to an existing file, you must add a parameter to the open() function:-
using the " w " parameter
Example1
Suppose we have a file named file2.txt. Let's write to this file.

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.

using the "a" parameter


Append - will append to the end of the file, for example:
Open the file "file2.txt" and append 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.

Create a New File


To create a new file in Python, use the open() method, with one of the following
parameters:
"x" - Create - will create a file, returns an error if the file exists
"a" - Append - will create a file if the specified file does not exists
"w" - Write - will create a file if the specified file does not exists

Example: Create a file called "myfile.txt":


f = open("myfile.txt", "x")

Result: a new empty file is created.

95
Chapter 6
Modules and Libraries

"Small steps every day lead to big achievements."

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.

Here, we have defined a function add() inside a module named example.


The function takes in two numbers and returns their sum.

Import modules in Python


We can import the definitions inside a module to another module or the interactive
interpreter in Python.
We use the import keyword to do this. To import our previously defined module
example, we type the following in the Python prompt. import example
This does not import the names of the functions defined in example directly in the
current symbol table. It only imports the module name example there.
Using the module name we can access the function using the dot . operator. For
example:

97
Example1
Import the module named mymodule, and call the greeting function:

import mymodule

mymodule.greeting("Jonathan")

Note: When using a function from a module, use the

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:

Statement from...import Python


We can import specific names from a module without importing the module as a
whole. For example:

Here, we imported only the pi attribute from the math module .

The dir() built-in function


In Python, we can use the dir() function to list all the function names in a module.
Example : List all the defined names belonging to the platform module:

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.

Why Use NumPy?


In Python we have lists that serve the purpose of arrays, but they are slow to
process.
NumPy aims to provide an array object that is up to 50x faster than traditional
Python lists.
The array object in NumPy is called ndarray, it provides a lot of supporting
functions that make working with ndarray very easy.

Homework: Why is NumPy Faster Than Lists?

Which Language is NumPy written in?


NumPy is a Python library and is written partially in Python, but most of the parts
that require fast computation are written in C or C++.

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]

Create a NumPy ndarray Object

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.

What Can Pandas Do?


Pandas gives you answers about the data. Like:
Is there a correlation between two or more columns?
What is average value?
Max value?
Min value?

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:

C:\Users\Your Name>pip install pandas

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

"The more you code, the more you learn—keep going!"

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.

Popular Python libraries for data analysis:


NumPy → Numerical computations
Pandas → Data manipulation and analysis
Matplotlib & Seaborn → Data visualization

Data Manipulation using Pandas


What is Pandas?

Pandas is a Python library that provides flexible data structures for handling
structured data.

The two main objects in Pandas are:

Series → One-dimensional data (like a single column).


DataFrame → Two-dimensional data (like an Excel table).

Example: Creating a Series


import pandas as pd
# Creating a Series
data = ]50 ,40 ,30 ,20 ,10[
s = pd.Series(data)
print(s)

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

 Import the Pandas library as pd.

 Define data with column and rows in a variable named d.

 Create a data frame using the function pd.DataFrame().

 The data frame contains 3 columns and 5 rows.

 Print the data frame output with the print() function.

Note: We write pd. in front of DataFrame() to let Python know that we want to activate
the DataFrame() function from the Pandas library.

Be aware of the capital D and F in DataFrame!

Interpreting the Output


this is the output:

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.

In Python, the numbering of rows starts with zero.

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:

We can use df.shape[0] to find the number of rows:

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:

Visualization with Matplotlib and Seaborn

What is Matplotlib?

Matplotlib is a low level graph plotting library


in python that serves as a visualization utility.

Matplotlib was created by John D. Hunter.

Matplotlib is open source and we can use it freely.

Matplotlib is mostly written in python, a few


segments are written in C, Objective-C and Javascript for Platform compatibility.

Where is the Matplotlib Codebase?

The source code for Matplotlib is located at this github repository


https://github.com/matplotlib/matplotlib

108
Installation of Matplotlib

If you have Python and PIP already installed on a system, then installation of
Matplotlib is very easy.

Install it using this command:

C:\Users\Your Name>pip install matplotlib

If this command fails, then use a python distribution that already has Matplotlib
installed, like Anaconda, Spyder etc.

Import Matplotlib

Once Matplotlib is installed, import it in your applications by adding


the import module statement:

import matplotlib

Now Matplotlib is imported and ready to use:

Checking Matplotlib Version

The version string is stored under __version__ attribute.

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:

import matplotlib.pyplot as plt

109
Example:
Draw a line in a diagram from position (0,0) to position (6,250):

#Three lines to make our compiler able to draw:

import sys

import matplotlib

matplotlib.use('Agg')

import matplotlib.pyplot as plt

import numpy as np

xpoints = np.array([0, 6])

ypoints = np.array([0, 250])

plt.plot(xpoints, ypoints)

plt.show()

#Two lines to make our compiler able to draw:

plt.savefig(sys.stdout.buffer)

sys.stdout.flush()

Result:

110
Seaborn

Visualize Distributions with Seaborn

Seaborn is a library that uses Matplotlib


underneath to plot graphs. It will be used
to visualize random distributions.

Install Seaborn.

If you have Python and PIP already installed


on a system, install it using this command:

C:\Users\Your Name>pip install seaborn

If you use Jupyter, install Seaborn using this command:

C:\Users\Your Name>!pip 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 matplotlib.pyplot as plt

Import Seaborn
Import the Seaborn module in your code using the following statement:

import seaborn as sns

111
Plotting a Displot
Example

import matplotlib.pyplot as plt


import seaborn as sns
sns.displot([0, 1, 2, 3, 4, 5])
plt.show()

Result:

Plotting a Displot without the Histogram


Example
import matplotlib.pyplot as plt
import seaborn as sns
sns.displot([0, 1, 2, 3, 4, 5], kind="kde")
plt.show()

Result:

Note: We will be using:


sns.displot(arr, kind="kde")
to visualize random
distributions in this

112
Resources:

1. W3Schools Tutorials

🔗 https://www.w3schools.com/python/default.asp

2. "Automate the Boring Stuff with Python" by Al Sweigart


3. "Python Crash Course" by Eric Matthes
4. "Python by example" by Nichola Lacey

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

You might also like