Python Programming Language
To verify that Python was installed successfully, open the terminal or command
prompt and type python --version .
Certiport Method. […] type py .
A Python File should have the extension: .py
Use only letters, numbers, and underscores.
Start only with a letter or an underscore.
Do not use spaces.
End with .py
In Python, a data type defines what kind of value a variable can hold and what
operations can be performed on it.
String (str)
Integer (int)
Float (float)
Boolean (bool)
A string included in “ “ is the same as a string included in ‘ ‘.
Int – whole numbers; Float – decimal numbers; Bool – True or
False.
A variable is a name that stores a value.
Var. names must begin with a letter or an underscore.
Var. names may only contain letters, digits, and underscores.
Var. such as Name, name, NAME are treated as distinct identifiers.
Reserved keywords may not be used as var. names.
An operator is a special symbol that performs a specific action on one or more
values.
The assignment operator var_name = value
Concatenation means joining two or more strings together into one ( + ).
To write a comment in Python, start the line with the # symbol.
For block comments, even though Python does not have a special symbol, we
can use “”” or ‘’’, which is a string that is just ignored in the program.
The type() function is used to determine the data type of a given variable or
value.
print(type([Link])
The str() function is used to convert other data types into strings.
The int() function converts a value to an integer, removing any decimal part.
The float() function converts a value into a floating-point number.
The bool() function converts a value into a Boolean.
bool(1) – True
bool(0) – False
bool(“Text”) – True
bool(“”) – False
Math operators:
- // whole division (drops the decimal)
- % remainder (what is left after division)
- ** power (repeats a number as a power)
Use index to get a specific character from the string.
word = “Hello”
print(word[0]) #H
Use the len() function to find out how many characters are in a string.
Use slicing to get a part of a string. [0 : nr] or [ : nr] or [nr : ] or [ : ]
A method is a built-in action used on a specific type of data.
.upper() converts all letters to uppercase
.lower() converts all letters to lowercase
.capitalize() converts only the first letter to uppercase
.count(“x”) counts how many times a letter or word appears
.replace(“x”, “y”) replaces one character or word with another
A list is a data structure that can store multiple values.
.append(x) adds an item to the end of the list
.remove(x) removes an item from the list
.insert(position, value) adds an item at a specific place
Tuples are orders, immutable collections of items, that cannot be modified after
creation unlike lists.
Dictionaries are unordered, mutable collections that store data in key-value pairs.
If you try to access a key that does not exist, Python gives a KeyError. To avoid
that, use .get().
.update({key: value}) updates the value of an existing key or adds a
new pair
.pop(key) removes the pair with the specified key
.keys() returns a view object of all keys in the dictionary
.values() returns a view object of all values in the dictionary
.items() return a view object of all the pairs as tuples
Sets are unordered, mutable collections of unique elements. Sets do not allow
duplicate values.
To create an empty set, use set() .
.add() adds an element to the set
.remove() removes a value. Raises an error if not found.
.discard() removes a value if it exists. Does nothing if not found.
[Link](other_set) returns a new set with all elements from both
sets
[Link](other_set) returns elements common to both sets
[Link](other_set) returns elements in the first set but not in the second
Assignment operators are used to assign values to variables.
= += -= *= /= //= %= **=
Comparison operators are used to compare values. The result is a Boolean.
== != > < >= <=
Logical operators are used to combine multiple conditions. The result is a
Boolean.
and or not
- and returns True only if both sides are True
- or returns True if at least one side is True
- not turns True into False and False into True
Identity operators are used to compare whether two variables refer to the same
object in memory, not just whether their values are equal.
is is not
- Is return True if both refer to the same object
- Is not returns True if variables refer to different objects
Membership operators are used to test whether a value is present in a sequence
or collection, such as a string, list, tuple, set, or dictionary.
in not in
- in returns True if the value exists
- not int returns True if the value does not exist
In Python, elif is a keyword that stands for “else if”, that is used to check for
multiple conditions sequencially after an initial if statement.
A nested conditional is an if statement placed inside another if or else.
In Python, the match-case statement is used to compare one variable against
many fixed values, like a menu of options.
A loop is a way to make the computer repeat actions. There are two main types
of loops:
- for loops - used when you know how many times to repeat something
for i in range()
print(i)
- while loops - used when you want to repeat something until a condition is no
longer true.
while x<… :
print(x)
An iterable is anything you can go through one item at a time (such as strings,
lists, dictionaries, tuples, sets).
Both break and continue are control flow tools. They change how a loop behaves
from inside the loop body.
- break statement stops the loop immediately
- continue statement skips the current step
- pass is a placeholder statement used when a block of code is syntactically
required but no action is needed at that moment.
A nested loop means a loop inside another loop.
A function is a reusable block of code designed to perform a specific task. They
can receive information, which is called parameters, that allow them to perform
tasks using different values each time they are called.
Local variables are defined inside a function and exist only during that function’s
execution.
Global variables are defined outside any function and are accessible throughout
the program.
Many basic io functions work without manually importing the io module.
Working with files begins with opening them using the built-in open() function,
and at the end it is important to close the file using the .close() method.
The with statement is used in Python to manage external resources such as files.
It ensures that the file is properly closed after its suite finishes execution, even if
an exception occurs.
Before writing to or reading from a file, it is often useful to first verify whether the
file already exists. Python provides a function called .exists() in the [Link]
module, which returns True if the file exists, and False if it does not.
When a file is no longer needed, it is good practice to remove it from the system.
Attempting to delete a file that does not exist will result in an error. To prevent
this, it is important to first verify whether the file is present using
[Link](), and then to remove it with [Link](file_name).
[Link](path) checks if the path points to a file (not a folder). Returns True if
the false exists and it’s a file, not a directory.
[Link](path) checks if the path points to a directory (not a file). Returns
True if the folder exists and it’s a folder, not a file.
[Link](path) creates one new directory (folder). If the folder already exists it
raises a FileExistsError.
[Link](path) creates a folder and all parent folders if needed.
[Link]() returns the current working directory (the folder where your Python
script is running).
[Link](path) changes the current working directory.
An exception is an error that occurs while the program is running. To prevent the
program from stopping immediately, there is used a structure called try and
except.
Syntax errors occur when the rules of the programming language are broken.
These are detected before the program runs (missing colons, incorrect
indentation, misspelled keywords).
Logic errors occur when the program runs without crashing, but produces
incorrect results, the code being syntactically correct, but not doing what it was
intended to (wrong formula, repeating the wrong loop, comparing two wrong
variables).
Runtime errors occur while the program is running, and they are unexpected
problems that stop the program if they are not handled (dividing by zero,
accesing a variable that doesn’t exist, converting an invalid string to a number).
ZeroDivisionError occurs when a number is divided by zero, which is not allowed
nor in maths, nor in programming.
ValueError occurs when a function receives the right type of argument but with
an invalid value (trying to convert a non-number string into an integer).
NameError occurs when a code refers to a variable or a function that does not
exist or has not been defined.
TypeError occurs when an operation is used on a data type that does not support
it (adding a number and a string together).
IndexError occurs when trying to access an index that does not exist in a list or
string.
KeyError occurs when trying to access a key that does not exist in a dictionary.
AttributeError occurs when trying to use a method or attribute that does not exist
for the object.
A finally block cand also be added. This block runs no matter what, whether there
was an error or not.
The raise statement is used to manually create an error in Python. This allows a
program to stop execution when something goes wrong, even if Python itself
wouldn’t automatically raise an error in that situation.
Object-Oriented Programming (OOP) is a programming approach based on the
use of “objects” that hold both data and code. It enables developers to create
modular and well-organised software.
A class is a user-defined blueprint or template for creating objects.
An object is an individual instance of a class.
An attribute is a variable that belongs to an object. It is used to store information
about the object’s state or properties. They are usually set using the self keyword
inside the __init__ method.
The __str__ method is a special method used to define what should be shown
when you print an object. With this you can control the output and return a
readable string that describes the object.
A method is a function that is defined inside a class and works with the object’s
data.
The del keyword is used to delete objects, attributes, or variables from memory.
In classes, you can delete an entire object or a specific attribute from an object.
The hasattr() checks whether an object has a specific attribute, and return True
or False.
The getattr() retrieves the value of an attribute from an object. If it doesn’t exist,
it raises an AttributeError.
The setattr() adds a new attribute to an object or updates the value of an
existing one.
vars() returns a dictionary containing all the attributes of the object and their
current values.
Inheritance allows a class to reuse the code from another class. The child class
inherits all attributes and methods from the parent class, and can also add new
ones or override existing ones. Class ChildClass(ParentClass):
Use the pass keyword when you want to define a class but you’re not ready to
write its content yet.
Overriding means redefining a method in a child class that already exists in the
parent class.
The super() function allows the child class to call a method from the parent class,
without duplicating it as with __init__().
In Python, polymorphism allows different classes to have methods with the same
name, but with different behaviour.
A module is simply a file with the .py extension that contains a Python code. The
primary purpose of a module is to enable code reuse and logical separation or
functionalities. In essence, whenever a Python file is saved, it can act as a
module and be imported using the import statement in another script. By doing
this, it will reflect a good software design: one file defining what to do, and the
other when and how to do it.
The math module is used to access mathematical functions that go beyond the
basic +, -, *, and /. It includes square roots, powers, rounding methods, and
constants like pi or e.
import math
[Link]() returns the non-negative square root of a numeric expression x.
[Link]() computes the integer square root of a non-negative integer x.
(n2<=x)
[Link](x, y) returns the result of raising x to the power of y.
There are two key functions for controlling the direction of rounding:
- [Link]() returns the largest integer less than or equal to x.
- [Link]() returns the smallest integer greater than or equal to x.
[Link] represents the value of pi, and math.e represents the value of the Euler’s
number.
[Link]() returns the absolute value of a number x, always as a float,
regardless of whether the input is an integer or a float.
abs() returns int if the input is int.
[Link]() computes n! . If a negative or non-integer value is passed,
Python raises a ValueError.
[Link]() returns the integer part of the number x by removing the fractional
part, regardless of whether the number is positive or negative.
[Link]() returns the value of the mathematical expression: e x.
The logarithm of a number is used in different ways in Python:
- [Link](x) is the natural log of x
- [Link](x, base)
- math.log10(x)
- math.log2(x)
Python provides built-in support for handling dates and times through the
datetime module. import datetime
The current local date and time can be retrieved using the .[Link]()
function.
If only the current date is needed without the time component, the .[Link]()
function should be used.
From both datetime and date objects, individual components such as year,
month, and day can be accessed using attributes.
To display dates in a specific string format, the strftime() method is used.
Conversely, a date represented as a string can be converted into a datetime
object using strptime() .
The date string must exactly match the structure given in the format string.
( “2025/07/30” won’t work with “%Y-%m-%d”).
The timedelta class from Python’s datetime module is used to represent a
duration of time-such as a number of days, hours, or minutes.
[Link]()
The random module in Python is part of the standard library and is used to
perform operations that involve randomisation. import random
The [Link]() function returns a random floating-point number between
0.0 and 1.0 .
The [Link](a, b) function returns a random integer N such that
a<=N<=b. Both end values are inclusive.
The [Link](sequence) function returns a single random element from a
non-empty sequence, such as a list, tuple, or string. If the sequence is empty,
choice() raises an IndexError.
The [Link](sequence) function randomly reorders the items of a mutable
sequence (such as a list) in place. This function modifies the original list and does
not return a new one. Attempting to shuffle an immutable sequence such as a
tuple or string will result in a TypeError.
The [Link](population, k) function returns a new list of k unique
elements selected randomly from the given population (e.g. list, tuple, or string).
This function does not modify the original sequence, and all selected elements
are distinct. If k is greater than the size of population, a ValueError is raised.
The [Link](value) function allows you to set the starting point of the
random number generator.
The assert statement is used in Python as a tool for internal self-testing. It allows
to verify that certain conditions hold True during execution. If the condition is
False, an AssertionError is raised, halting the program. assert condition
While assert can be used inside functions to check internal assumptions, it can
also be used outside functions to create simple test cases. These are useful for
verifying that functions produce correct output when given expected inputs.
unittest is the built-in testing framework in Python. It allows to organise tests into
structured classes and methods, making it easier to write, run , and maintain
automated tests.
The assertEqual method verifies that two values are equal. It is typically used to
confirm that the actual output of a function matches the expected result.
The assertIn method checks whether a value is contained inside a sequence such
as a list, tuple, set, or string. It is useful when testing membership conditions, for
example to confirm that a returned item is present in the expected collection.
The assertIs method verifies that two variables refer to the same object in
memory. It is particularly useful when testing object identity, ensuring that no
duplicate or unintended copies of an object were created.
The assertIsInstance method verifies that an object is an instance of a specified
class or one of its subclasses.
The assertTrue method verifies that a condition or expression evaluates to True.