Python Mid Term Notes
Python Mid Term Notes
Programming
Python Introduction:
Definition: Python is a high-level,
interpreted programming language
known for its simplicity and
readability. Created by Guido van
Rossum and first released in 1991,
Python emphasizes code readability
and allows programmers to express
concepts in fewer lines of code
compared to languages like C++ or
Java.
Key Features:
oInterpreted: Python code is
executed line-by-line, making
debugging easier.
oHigh-level: Python abstracts
away many of the complex
details of the computer's
hardware.
o Dynamically Typed: Variable
types are determined at runtime,
not in advance.
o Portable: Python code can run
on various platforms without
modification.
Installing and Setting Python
Environment in Windows and Linux:
Windows:
1. Download the Python installer
from the official Python website.
2. Run the installer and ensure
you check the "Add Python to
PATH" option.
3. Verify installation by running
python --version in the
command prompt.
Linux:
1. Use the package manager of
your distribution (apt-get,
yum, etc.).
2. Example for Debian-based
systems: sudo apt-get
install python3.
3. Verify installation by running
python3 --version in the
terminal.
Basics of Python Interpreter:
Definition: The Python interpreter is
a program that reads and executes
Python code. It translates high-level
Python instructions into machine
language.
Modes:
oInteractive Mode: Run Python
directly in the terminal using
python (or python3).
oScript Mode: Write Python code
in a file with a .py extension
and run it using python
script.py.
Execution of Python Program:
Writing a Python Script: Use a
text editor or an IDE to write Python
code in a file with a .py extension.
Running the Script:
python
# script.py
print("Hello, World!")
Execute in terminal:
sh
python script.py
Editor for Python Code:
IDEs and Editors:
oIDLE: The default Python
Integrated Development and
Learning Environment.
oPyCharm: Feature-rich IDE with
powerful debugging tools.
VS Code: Lightweight and
o
python
# This is a comment
print("Hello, World!")
Variables:
Definition: Named locations
o
python
x = 10 # int
y = 3.14 # float
name = "Alice" # str
Types:
Common Types: int, float,
o
Lists
Definition:
A list is a collection of items that are
ordered and changeable (mutable).
Lists allow duplicate elements and
are defined using square brackets
[].
Creating a List:
To create a list, you place elements
inside square brackets, separated by
commas.
python
my_list = [1, 2, 3,
'hello', 4.5]
Here, my_list contains integers, a
string, and a float.
Accessing Elements:
You can access elements in a list
using their index (position in the
list). Indexing starts at 0.
python
first_item = my_list[0]
# 1
last_item = my_list[-1]
# 4.5
Adding Elements:
append() Method: Adds an
element to the end of the list.
python
my_list.append(6) # [1,
2, 3, 'hello', 4.5, 6]
insert() Method: Adds an
element at a specified position.
python
my_list.insert(1,
'world') # [1, 'world',
2, 3, 'hello', 4.5, 6]
Removing Elements:
remove() Method: Removes the
first occurrence of a specified
element.
python
my_list.remove('hello')
# [1, 'world', 2, 3,
4.5, 6]
pop() Method: Removes and
returns the element at a specified
position. If no index is specified, it
removes the last item.
python
my_list.pop(2) #
Removes 2, resulting in
[1, 'world', 3, 4.5, 6]
clear() Method: Removes all
elements from the list.
python
my_list.clear() # []
Modifying Elements:
You can change the value of an
existing element using its index.
python
my_list[1] = 'Python' #
['Python', 'world', 3,
4.5, 6]
Iteration:
Loop through elements in a list
using a for loop.
python
for item in my_list:
print(item)
List Comprehension:
A concise way to create lists. It
consists of brackets containing an
expression followed by a for
clause.
python
squares = [x**2 for x in
range(10)] # [0, 1, 4,
9, 16, 25, 36, 49, 64,
81]
Nested Lists (Matrices):
Lists can contain other lists, making
it possible to create matrices (2D
lists).
python
matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
print(matrix[0][1]) # 2
Dictionaries
Definition:
A dictionary is a collection of key-
value pairs. Each key is unique and
maps to a value. Dictionaries are
mutable and defined using curly
braces {}.
Creating a Dictionary:
To create a dictionary, place key-
value pairs inside curly braces,
separated by commas. Each key is
followed by a colon and its
corresponding value.
python
my_dict = {"name":
"Alice", "age": 25,
"email":
"[email protected]"}
Accessing Elements:
You can access the value associated
with a key using square brackets.
python
name = my_dict["name"]
# Alice
Adding/Updating Elements:
Add a new key-value pair or update
an existing one by assigning a value
to the key.
python
my_dict["phone"] = "123-
456-7890"
my_dict["age"] = 26 #
Updates the value of
"age"
Removing Elements:
del Statement: Removes a key-
value pair.
python
del my_dict["email"]
pop() Method: Removes and
returns the value associated with a
specified key.
python
phone =
my_dict.pop("phone") #
Returns "123-456-7890"
Iteration:
Loop through keys, values, or key-
value pairs in a dictionary.
python
for key in my_dict:
print(key,
my_dict[key])
Use items() to get key-value
pairs.
python
for key, value in
my_dict.items():
print(key, value)
Tuples
Definition:
A tuple is an immutable, ordered
collection of items. Tuples are
defined using parentheses ().
Creating a Tuple:
To create a tuple, place items inside
parentheses, separated by commas.
python
my_tuple = (1, 2, 3,
'hello', 4.5)
Accessing Elements:
You can access elements in a tuple
using their index.
python
first_item = my_tuple[0]
# 1
last_item = my_tuple[-1]
# 4.5
Immutability:
Once a tuple is created, you cannot
change its elements. This makes
tuples useful for fixed collections of
items.
python
# Attempting to modify a
tuple will result in an
error
my_tuple[1] = 'Python'
# TypeError: 'tuple'
object does not support
item assignment
Advantages of Tuples:
Since tuples are immutable, they can
be used as keys in dictionaries (lists
cannot).
Tuples generally use less memory
than lists.
Comparison with Lists:
Mutability:
Lists are mutable (can change).
o
oTuples are immutable (cannot
change).
Usage:
oUse lists when you need a
collection of items that can
change.
oUse tuples when you need a
collection of items that should
remain constant.
Sets
Definition:
A set is a mutable, unordered
collection of unique items. Sets are
defined using curly braces {}.
Creating a Set:
To create a set, place items inside
curly braces, separated by commas.
python
my_set = {1, 2, 3, 4, 5}
Adding Elements:
Use add() to add an element to the
set.
python
my_set.add(6)
Removing Elements:
Use remove() to remove an
element from the set.
python
my_set.remove(3)
discard() Method: Similar to
remove(), but does not raise an
error if the element is not found.
python
my_set.discard(10) #
Does nothing since 10 is
not in the set
Set Operations:
Union: Combines elements from
both sets.
python
set1 = {1, 2, 3}
set2 = {3, 4, 5}
union_set = set1 | set2
# {1, 2, 3, 4, 5}
Intersection: Returns common
elements from both sets.
python
intersection_set = set1
& set2 # {3}
Difference: Returns elements in the
first set but not in the second.
python
difference_set = set1 -
set2 # {1, 2}
Symmetric Difference: Returns
elements in either set, but not in
both.
python
symmetric_difference_set
= set1 ^ set2 # {1, 2,
4, 5}
Iteration:
Loop through elements in a set using
a for loop.
python
for item in my_set:
print(item)
Summary Comparison
Featu Dictiona
Lists Tuples Sets
re ries
def outer():
x = "enclosing"
def inner():
x = "local"
print(x) #
Output: local
inner()
print(x) # Output:
enclosing
outer()
print(x) # Output: global
Modules
Module Coding Basics:
A module is a file containing Python
definitions and statements. The file
name is the module name with the
suffix .py.
Example: mymodule.py
python
# mymodule.py
def add(a, b):
return a + b
def subtract(a, b):
return a - b
Importing Programs as Modules:
Use the import statement to
include the module in your code.
python
import mymodule
print(mymodule.add(5,
3)) # Output: 8
From Import Statement: Import
specific functions or variables from
a module.
python
from mymodule import add
print(add(5, 3)) #
Output: 8
Executing Modules as Scripts:
Use the special variable __name__
to determine if the module is being
run on its own or being imported
somewhere else.
python
# mymodule.py
def main():
print("This is a
script")
if __name__ ==
"__main__":
main()
Compiled Python Files (.pyc):
When a Python script is run, the
Python interpreter compiles the code
to bytecode, which is stored in
.pyc files in the __pycache__
directory. This makes the program
start faster on subsequent runs.
Standard Modules:
Python comes with a standard
library of modules. Some useful
standard modules include:
o os Module: Provides a way to
interact with the operating
system.
python
import os
print(os.getcwd()) #
Output: Current
working directory
o sys Module: Provides access to
some variables used or
maintained by the interpreter and
to functions that interact with the
interpreter.
python
import sys
print(sys.version) #
Output: Python version
The dir() Function:
The dir() function is used to list
the names in the current local scope
or the attributes of a given object.
python
import mymodule
print(dir(mymodule)) #
Output: List of
attributes and functions
in mymodule
Packages:
A package is a way of structuring
Python’s module namespace by
using “dotted module names”. A
package is a collection of modules.
Creating a Package: Create a
directory and add an
__init__.py file to it, which
indicates that the directory is a
package.
o Directory Structure:
o mypackage/
o __init__.py
o module1.py
o module2.py
o Importing from a Package:
python
from mypackage import
module1
from mypackage.module2
import function
Summary Comparison
Topi Descrip
Example Code
c tion
Func Reusabl def greet(name):
tions e print(f"Hello,
blocks {name}!")<br>greet
of code ("Alice")
Topi Descrip
Example Code
c tion
that
perform
a
specific
task
Executi
Func ng a
tion functio greet("Alice")
Call n by its
name
Values def greet(name,
Argu passed greeting="Hello")
ment to a
:<br>greet("Alice"
s functio
, greeting="Hi")
n
Scop Variabl x =
e e "global"<br>def
Rules visibilit outer(): x =
y "enclosing" def
Topi Descrip
Example Code
c tion
governe
d by inner(): x =
LEGB "local" print(x)
rule
Files import
containi
Mod mymodule<br>print(
ng
ules mymodule.add(5,
Python
3))
code
Includi from mymodule
Impo
ng a import
rting
module
Mod add<br>print(add(5
in your
ules , 3))
code
Exec Runnin if __name__ ==
uting g a "__main__":
as module main()
Scrip as the
t main
Topi Descrip
Example Code
c tion
progra
m
.pyc
files
Com
created The .pyc files in the
piled
to
Pyth __pycache__
improv
on directory
e
Files
perform
ance
Pre-
installe import
Stan d os<br>print(os.get
dard module
cwd())<br>import
Mod s such
sys<br>print(sys.v
ules as os
ersion)
and
sys
dir( Lists import
Topi Descrip
Example Code
c tion
names
in the
current
local
)
scope mymodule<br>print(
Func
or dir(mymodule))
tion
attribut
es of a
given
object
Pack Collecti from mypackage
ages on of import
module module1<br>from
s mypackage.module2
structur import function
ed with
director
ies and
__ini
Topi Descrip
Example Code
c tion
t__.p
y files