Python Programming.
Python Programming.
PROGRAMMING
BEGINNERS
In This Book You Will Learn Explanation with Diagram and
Readymade Solution With Step By Step Explanation
AMIT K
Contents
Beginners Guide to Learn Python Programming Step by Step
Introduction
Chapter 1 : Basics
1 Python Introduction
2 Python Variables
Chapter 2 : Data Types
1 Python boolean
2 Python String
3 Python Number
4 Python List
5 Python Tuple
6 Python Dictionary
Chapter 3 : Operators
1 Python Arithmetic Operators
2 Python Bitwise Operators
3 Python Comparison Operators
4 Python Logical Operators
5 Python Ternary Operators
Chapter 4 : Statements
1 Python if
2 Python while
3 Python for loop
4 Python pass
5 Python break
6 Python continue
Chapter 5 : Functions
1 Python function
2 Python Function Recursion
Chapter 6 : Object Oriented
1 Python Modules
2 Python class
3 Python class Inheritance
4 Python Abstract Base Classes
5 Python Operator Overloading
Chapter 7 : Advanced
1 Python File
2 Python Text File
3 Python Exceptions
4 Python Testing
Introduction
Learning Python Programming step by step.
Python's popularity stems from its simplicity, versatility, and robustness.
Here are some of its main features:
Chapter 1 :
Python Introduction
1 Introduction
Python's popularity stems from its simplicity, versatility, and robustness.
Here are some of its main features:
Compiler Install
Python is an interpreted language, so it doesn't require compilation in the
traditional sense. However, you do need to install the Python interpreter on
your system to run Python code. Here's how you can download and install
Python:
Hello world
Writing "Hello, World!" to the console in Python is straightforward. Here's
the code:
print("Hello, World!")
Comments
In Python, you can write comments to document your code or provide
explanations. Comments are ignored by the Python interpreter and are
meant for human readers. Here's how you can write comments in Python:
Single-line comments:
# This is a single-line comment
print("Hello, World!") # This is also a single-line comment
Alternatively, you can use the # character to comment out multiple lines:
# This is a comment
# This is another comment
print("Hello, World!")
2 Python Variables
Introduction
In Python, variables are used to store data values. A variable is a name that
refers to a value stored in memory. Unlike some other programming
languages, Python is dynamically typed, meaning you don't need to declare
the type of a variable before assigning a value to it. Here's how you can use
variables in Python:
1 Variable Assignment: You can assign a value to a variable using the =
operator.
x = 10
name = "Alice"
3 Data Types: Python variables can hold values of different data types,
including:
5 Variable Scope: Variables have a scope, which defines where they can
be accessed from. Variables declared inside a function have local scope,
meaning they are only accessible within that function. Variables declared
outside of any function have global scope and can be accessed from
anywhere in the code.
x = 10 # global variable
def my_function():
y = 20 # local variable
print(x) # x can be accessed here
print(y) # y can be accessed here
my_function()
print(x) # x can be accessed here
print(y) # Error: y is not defined
Variables are fundamental to programming in Python, as they allow you to
store and manipulate data within your programs.
Constants
In Python, constants are typically created by defining variables with
uppercase names and treating them as if they were constant, although
Python does not have built-in support for constant variables like some other
programming languages. Here's how you can create constants in Python:
MY_CONSTANT = 10
ANOTHER_CONSTANT = "Hello"
@readonly
class Constants:
MY_CONSTANT = 10
ANOTHER_CONSTANT = "Hello"
# Now you cannot modify the values of these constants:
# Constants.MY_CONSTANT = 20 # This will raise an AttributeError
Chapter 2 :
Python Data Types
1 Python boolean
Introduction
Boolean values are a data type in Python that represent truth values. They
can only have one of two values: True or False. Boolean values are
commonly used in conditional statements, loops, and logical operations to
control the flow of the program or to represent the result of a comparison.
Here's how you can use Boolean values in Python:
1 Boolean Variables: You can assign Boolean values to
variables like any other data type.
is_student = True
has_passed_exam = False
boolean to int
In Python, you can convert a Boolean value to an integer using the int()
function. When you convert a Boolean value to an integer, True is
represented as 1 and False is represented as 0. Here's how you can do it:
# Convert True to integer
boolean_value = True
integer_value = int(boolean_value)
print(integer_value) # Output: 1
boolean to string
In Python, you can convert a boolean value to a string using either the str()
function or by using string formatting methods. Here are a example:
Using str() function:
# Convert True to string
boolean_value = True
string_value = str(boolean_value)
print(string_value) # Output: "True"
True False
In Python, True and False are the two boolean values that represent the truth
values. They are used to control the flow of the program, make decisions,
and perform logical operations. Here are some important notes on True and
False and how to use them in Python:
1 True and False Values:
2 Boolean Operations:
3 Comparison Operators:
Comparison operators (==, !=, <, <=, >, >=) return boolean
values (True or False) based on the comparison result.
For example, x == y returns True if x is equal to y, otherwise
it returns False.
4 Control Structures:
6 Return Values:
2 Python String
Introduction
Creating a variable and assigning a string value to it in Python is
straightforward. Here's how you can do it:
# Create a variable named 'my_string' and assign a string value to it
my_string = "Hello, World!"
Variables in String
In Python, you can use variables inside strings using string formatting
techniques. There are several ways to achieve this, including using the %
operator, the str.format() method, and f-strings (formatted string literals).
Here's how you can use variables inside strings using each method:
1 Using % Operator: You can use the % operator to insert
variables into strings. This method is older and less
recommended compared to newer methods like f-strings
and str.format().
name = "Alice"
age = 30
greeting = "Hello, %s! You are %d years old." % (name, age)
print(greeting)
All three methods achieve the same result, but f-strings are generally
preferred due to their simplicity and readability. They were introduced in
Python 3.6 and offer a more intuitive way to format strings with variables.
Escape
Escape sequences in Python strings are special characters that are preceded
by a backslash \. These sequences allow you to include characters in strings
that are difficult or impossible to type directly in source code. Here are
some commonly used escape sequences in Python:
Output:
Line 1
Line 2
Output:
Column 1 Column 2
Output:
World
Output:
This is a backslash:
\
Quote
To include single quotes (') or double quotes (") inside a Python string, you
can use the opposite type of quote to delimit the string, or you can escape
the quote character using a backslash (\). Here's how you can do it:
# Using single quotes to delimit the string with double quotes inside
string_with_double_quotes = 'She said, "Hi"'
print(string_with_double_quotes)
Output:
He said,
'Hello'
She said, "Hi"
Output:
I'm fine
She said, "It's raining"
Both of these methods allow you to include single quotes or double quotes
inside a Python string without causing syntax errors. Choose the method
that best fits your code style and readability preferences.
3 Python Number
Introduction
Python supports several numerical data types, each with its own
characteristics and use cases. Here are the main numerical data types that
Python can handle:
1 Integer (int):
Integers represent whole numbers without any decimal
point.
Example: 5, -10, 1000.
2 Floating-Point (float):
3 Complex (complex):
4 Decimal (decimal.Decimal):
5 Fraction (fractions.Fraction):
6 Boolean (bool):
7 Rational (sympy.Rational):
Integer
Creating integer numbers and performing simple calculations in Python is
straightforward. You can define integer variables and use mathematical
operators to perform calculations. Here's an example:
# Create integer variables
x=5
y=3
In this example:
Floats
Creating floating-point numbers and performing simple calculations in
Python is similar to working with integer numbers. Here's an example of
creating floating-point variables and performing arithmetic operations:
# Create floating-point variables
x = 3.5
y = 2.0
You can use the same arithmetic operators (+, -, *, /, //, %) as with integer
numbers to perform calculations with floating-point numbers. However, it's
important to note that when performing division (/), Python will always
return a floating-point result, even if the operands are integers.
# Print the results
print("Sum:", sum_result)
print("Difference:", difference_result)
print("Product:", product_result)
print("Quotient:", quotient_result)
In this example:
Output:
Sum: 5.5
Difference: 1.5
Product: 7.0
Quotient: 1.75
Multiple Assignment
Multiple assignment in Python allows you to assign multiple variables in a
single line, each with its corresponding value. This can be done using tuple
unpacking or list unpacking. Here's how you can do multiple assignment:
1 Tuple Unpacking: You can use a tuple on the right-hand side
of the assignment operator to assign values to multiple
variables.
# Tuple unpacking
x, y, z = 10, 20, 30
print("x:", x) # Output: 10
print("y:", y) # Output: 20
print("z:", z) # Output: 30
print("a:", a) # Output: 10
print("b:", b) # Output: 20
print("c:", c) # Output: 30
x, y = y, x
print("x:", x) # Output: 20
print("y:", y) # Output: 10
Int to string
To convert an integer to a string in Python, you can use the str() function.
Here's how you can do it:
# Convert an integer to a string
number = 123
string_number = str(number)
Output:
12
3
In this example, the str() function is used to convert the integer 123 to a
string representation "123". The resulting string can then be used in string
operations, printed, or stored in a variable for further processing.
In this example, the int() function is used to convert the string "123" to an
integer value 123. The resulting integer can then be used in arithmetic
operations, comparisons, or stored in a variable for further processing.
Output:
123.0
In this example, the float() function is used to convert the integer 123 to a
floating-point number 123.0. The resulting floating-point number can then
be used in arithmetic operations, comparisons, or stored in a variable for
further processing.
4 Python List
Introduction
In Python, a list is a built-in data structure that represents a collection of
items in a specific order. Lists are mutable, meaning that you can modify
their elements after they have been created. Lists can contain elements of
different data types, and they can grow or shrink dynamically as needed.
Here's a simple example of a Python list:
# Creating a list
my_list = [1, 2, 3, 4, 5]
In this example:
Modify Elements
To modify elements in a Python list, you can directly assign new values to
specific elements using their indices. Lists in Python are mutable, which
means you can change their elements after they have been created. Here's
how you can modify elements in a Python list:
# Define a list
my_list = ['apple', 'banana', 'cherry', 'date', 'elderberry']
In this example:
You can modify elements in a list using any valid Python expression. This
means you can assign new values of the same type, different types, or even
the result of an expression involving other elements in the list. Lists provide
a flexible and powerful way to manage collections of data in Python.
Add Elements
To add elements to a Python list, you can use various methods such as
append(), insert(), or concatenation (+ operator). Here's how you can add
elements to a list using these methods:
1 Using append() method: The append() method adds a single
element to the end of the list.
# Define a list
my_list = ['apple', 'banana', 'cherry']
In each example, we first define a list (my_list). Then, we use one of the
methods (append(), insert(), or concatenation) to add elements to the list.
Finally, we print the modified list to verify the changes.
These methods provide flexible ways to add elements to a list in Python,
allowing you to easily extend the list with new data as needed.
Insert Elements
To insert elements in the middle of a Python list, you can use the insert()
method. The insert() method allows you to specify the index where you
want to insert the new element. Here's how you can insert elements into the
middle of a list:
# Define a list
my_list = ['apple', 'banana', 'cherry', 'date']
In this example:
The insert() method modifies the original list in place by shifting existing
elements to make room for the new element. It's a convenient way to insert
elements at specific positions within a list.
Sort Permanently
To sort a Python list permanently using the sort() method, you can simply
call the sort() method on the list. The sort() method sorts the elements of the
list in ascending order by default. Here's how you can use the sort() method
to sort a list permanently:
# Define a list
my_list = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3]
In this example:
5 Python Tuple
Introduction
A Python tuple is an immutable, ordered collection of elements. Immutable
means that once a tuple is created, its elements cannot be changed or
modified. Tuples are similar to lists, but they are enclosed in parentheses ()
instead of square brackets [].
# You can also create a tuple without parentheses (not recommended for readability)
another_tuple = 1, 2, 3
Tuples are commonly used for grouping data that belongs together, like
coordinates, records from a database, or returning multiple values from a
function. Because tuples are immutable, they provide a certain level of
safety when dealing with data that should not be changed accidentally.
Loop
Looping through all values in a Python tuple is similar to looping through a
list. You can use a for loop to iterate over each element in the tuple. Here's
how you can do it:
my_tuple = (1, 2, 3, 4, 5)
This loop iterates over each element in the my_tuple tuple and prints each
value.
Alternatively, you can also use indexing to loop through a tuple if you need
access to the index:
my_tuple = (1, 2, 3, 4, 5)
length
In Python, you can use the len() function to get the length (number of
elements) of a tuple. Here's how you can use it:
my_tuple = (1, 2, 3, 4, 5)
Output:
Length of the tuple: 5
The len() function returns the number of elements in the tuple, in this case,
5. This function can be used with tuples as well as other sequences like
lists, strings, and dictionaries.
max/min
In Python, you can use the max() and min() functions to find the maximum
and minimum elements, respectively, in a tuple. Here's how you can use
them:
my_tuple = (3, 7, 1, 9, 2, 6)
Output:
Maximum element: 9
Minimum element: 1
Both max() and min() functions return the maximum and minimum
elements of the tuple, respectively. These functions work similarly for other
iterable data types like lists and strings as well.
tuple to string
To convert a tuple to a string in Python, you can use string manipulation
techniques. One common approach is to use the join() method along with a
string concatenation or formatting to convert the elements of the tuple into a
string. Here's how you can do it:
You can create a dictionary in Python using curly braces {} and specifying
key-value pairs separated by colons :. Here's how you can create a
dictionary:
# Creating an empty dictionary
empty_dict = {}
Loop Pairs
You can loop through all key-value pairs in a Python dictionary using a for
loop. Python dictionaries provide several methods to access keys, values, or
both. Here's how you can loop through all key-value pairs in a dictionary:
my_dict = {'name': 'John', 'age': 30, 'city': 'New York'}
Using .items() is the most common and efficient way to loop through all
key-value pairs in a dictionary in Python.
Access
You can access values in a Python dictionary using the keys as indices.
Here are a few methods to access values in a dictionary:
1 Using square brackets []:
my_dict = {'name': 'John', 'age': 30, 'city': 'New York'}
print("Name:", name)
print("Age:", age)
print("City:", city)
print("Name:", name)
print("Age:", age)
print("City:", city)
In both examples, we access the values in the dictionary my_dict using the
keys 'name', 'age', and 'city'. Using square brackets is straightforward and
raises a KeyError if the key is not found in the dictionary. Using the get()
method allows you to provide a default value if the key is not found, which
can help avoid KeyError exceptions.
Chapter 3 :
Operators
Introduction
In Python, arithmetic operators are used to perform mathematical
operations. Here's a list of arithmetic operators in Python:
1 Addition: +
2 Subtraction: -
3 Multiplication: *
4 Division: /
5 Floor Division (integer division): //
6 Modulus (remainder): %
7 Exponentiation: **
Usage
Here are examples illustrating the use of each arithmetic operator in Python:
1 Addition (+):
a=5
b=3
result = a + b
print("Addition:", result) # Output: Addition: 8
2 Subtraction (-):
a=7
b=4
result = a - b
print("Subtraction:", result) # Output: Subtraction: 3
3 Multiplication (*):
a=6
b=5
result = a * b
print("Multiplication:", result) # Output: Multiplication: 30
4 Division (/):
a = 10
b=3
result = a / b
print("Division:", result) # Output: Division: 3.3333333333333335
6 Modulus (%):
a = 10
b=3
result = a % b
print("Modulus:", result) # Output: Modulus: 1
7 Exponentiation ():**
a=2
b=3
result = a ** b
print("Exponentiation:", result) # Output: Exponentiation: 8
These examples demonstrate the use of each arithmetic operator in Python
with simple numerical values.
Handle Divide By Zero
To handle division by zero and multiple exceptions in Python, you can use
the try and except blocks. Here's how you can handle these scenarios:
1 Handling Divide By Zero: You can catch the ZeroDivisionError
exception when dividing by zero.
2 Handling Multiple Exceptions: You can catch multiple exceptions by
specifying them in a tuple after except.
# Example usage
divide_numbers(10, 0) # Division by zero
divide_numbers(10, 'a') # Type mismatch
In this example:
Integer Division
In Python, integer division is performed using the double-slash operator //.
This operator divides one number by another and returns the integer result,
discarding any fractional part.
Here's an example:
result = 10 // 3
print(result) # Output: 3
Common Divisors
You can find the common divisors of two numbers in Python by iterating
through the range of numbers from 1 to the minimum of the two numbers
and checking if both numbers are divisible by that number without
remainder. Here's how you can do it:
def common_divisors(num1, num2):
# Find the minimum of the two numbers
min_num = min(num1, num2)
return common_divisors_list
# Example usage
num1 = 12
num2 = 18
result = common_divisors(num1, num2)
print("Common divisors of", num1, "and", num2, ":", result)
In this example:
You can use this function to find the common divisors of any two numbers
by passing them as arguments to the function.
Sum of squares
To find the sum of squares of the first n natural numbers in Python, you can
use a simple formula and compute the sum directly. The formula to find the
sum of squares of the first n natural numbers is given by:
[ \sum_{i=1}^{n} i^2 = \frac{n(n+1)(2n+1)}{6} ]
In this implementation:
Usage
Here are examples illustrating the use of each bitwise operator in Python:
1 Bitwise AND (&):
a = 5 # 0101 in binary
b = 3 # 0011 in binary
result = a & b
print("Bitwise AND:", result) # Output: 1 (0001 in binary)
2 Bitwise OR (|):
a = 5 # 0101 in binary
b = 3 # 0011 in binary
result = a | b
print("Bitwise OR:", result) # Output: 7 (0111 in binary)
result = a ^ b
print("Bitwise XOR:", result) # Output: 6 (0110 in binary)
result = ~a
print("Bitwise NOT:", result) # Output: -6 (1010 in binary for 32-bit integers)
result = a << 2
print("Left Shift:", result) # Output: 20 (10100 in binary)
result = a >> 1
print("Right Shift:", result) # Output: 5 (0101 in binary)
Power of 2
You can determine whether a number is a power of two using bitwise
operators in Python. A number is a power of two if and only if it has exactly
one bit set in its binary representation. Here's how you can do it:
def is_power_of_two(num):
# A number is a power of two if it is greater than 0 and has exactly one bit set
return num > 0 and (num & (num - 1)) == 0
# Example usage
num1 = 4
num2 = 6
In this example:
# Example usage
number = 123456
Usage
Here are examples illustrating the use of each comparison operator in
Python:
1 Equal to (==):
a=5
b=5
result = a == b
print("Is", a, "equal to", b, "?", result) # Output: Is 5 equal to 5 ? True
result = a != b
print("Is", a, "not equal to", b, "?", result) # Output: Is 5 not equal to 6 ? True
result = a > b
print("Is", a, "greater than", b, "?", result) # Output: Is 6 greater than 5 ? True
result = a < b
print("Is", a, "less than", b, "?", result) # Output: Is 5 less than 6 ? True
result = a <= b
print("Is", a, "less than or equal to", b, "?", result) # Output: Is 5 less than or equal to 6 ? True
Usage
Here are examples illustrating the use of each logical operator in Python:
1 Logical AND (and):
a = True
b = False
result = a and b
print("Logical AND:", result) # Output: Logical AND: False
2 Logical OR (or):
a = True
b = False
result = a or b
print("Logical OR:", result) # Output: Logical OR: True
result = not a
print("Logical NOT:", result) # Output: Logical NOT: False
Combine
You can combine logical operators to create more complex conditions in
Python by using parentheses to group expressions and applying logical
operators (and, or, not) as needed. Here's an example that demonstrates
combining logical operators:
# Example: Check if a number is between 10 and 20, or outside the range 30 to 40
def check_number_range(num):
if (num >= 10 and num <= 20) or (num < 30 or num > 40):
return True
else:
return False
# Example usage
number1 = 15
number2 = 25
number3 = 35
print("Is", number1, "between 10 and 20 or outside the range 30 to 40?",
check_number_range(number1)) # Output: True
print("Is", number2, "between 10 and 20 or outside the range 30 to 40?",
check_number_range(number2)) # Output: False
print("Is", number3, "between 10 and 20 or outside the range 30 to 40?",
check_number_range(number3)) # Output: True
In this example:
# Example usage
number1 = 10
number2 = 20
number3 = 15
In this program:
In this example:
Usage
Here are examples illustrating the use of the ternary operator in Python:
1 Assigning Maximum Value:
x = 10
y = 20
Largest
You can create a Python program to find the largest of two numbers entered
by the user using ternary operators as follows:
# Input two numbers from the user
number1 = float(input("Enter first number: "))
number2 = float(input("Enter second number: "))
In this program:
Chapter 4 :
Statements
1 Python if
Introduction
In Python, the if statement is a control flow statement that allows you to
execute a block of code based on whether a specified condition evaluates to
True. It is used for decision-making in programming.
The syntax of the if statement in Python is as follows:
if condition:
# Code block to execute if the condition is True
statement1
statement2
...
if x > 5:
print("x is greater than 5")
In this example:
Syntax
The if statement in Python can be used in various ways to create conditional
logic. Here are the different forms of if statements along with their syntax:
1 Basic if statement:
if condition:
# Code block to execute if the condition is True
statement1
statement2
...
2 if-else statement:
if condition:
# Code block to execute if the condition is True
statement1
statement2
...
else:
# Code block to execute if the condition is False
statement3
statement4
...
4 Nested if statement:
if condition1:
if condition2:
# Code block to execute if both condition1 and condition2 are True
statement1
statement2
...
In each form of the if statement, you can include one or more conditions
and corresponding code blocks to execute based on the evaluation of those
conditions. The else and elif clauses are optional and can be used to specify
alternate code blocks to execute when the conditions are False.
Even Odd
You can check whether a given number is even or odd in Python using an if
statement with the modulo operator (%). Here's how you can do it:
def check_even_odd(number):
if number % 2 == 0:
print(number, "is even.")
else:
print(number, "is odd.")
# Example usage
number = 7
check_even_odd(number)
In this program:
# Assume the first number is both the largest and smallest initially
largest = num1
smallest = num1
In this program:
Positive or negative
You can create a Python program to check whether a given integer is
positive or negative using an if statement like this:
# Take input from the user
num = int(input("Enter an integer: "))
In this code:
2 Python while
Syntax
The syntax of a while loop in Python is as follows:
while condition:
# Code block to be executed repeatedly
# as long as the condition is True
In this syntax:
break
You can use the break statement to exit a while loop prematurely in Python.
Here's how you can use it:
while condition:
# Code block to be executed repeatedly
# as long as the condition is True
if some_condition:
break # Exit the loop if some condition is met
In this code:
continue
You can use the continue statement to skip the current iteration of a while
loop and proceed to the next iteration. Here's how you can use it:
while condition:
# Code block to be executed repeatedly
# as long as the condition is True
if some_condition:
continue # Skip the rest of the loop's code and start the next iteration
In this code:
In this syntax:
Output:
apple
banana
cherry
In this example, the for loop iterates over each item in the fruits list, and
during each iteration, the fruit variable takes on the value of the current
item, which is then printed.
Syntax
In Python, the for loop can be used in different ways depending on the type
of iterable you are iterating over or the specific requirement of the loop.
Here are some common variations of for loop statements:
1 Iterating over a sequence (list, tuple, string, etc.):
sequence = [1, 2, 3, 4, 5]
for item in sequence:
# Code block to be executed for each item in the sequence
Here, start is the starting value of the range (inclusive), stop is the ending
value of the range (exclusive), and step is the step size between each value
(default is 1).
These are some of the common ways you can use the for loop in Python,
but there can be more variations depending on the specific requirements of
your code.
Loop on array
In Python, you can print each element in an array (or list) using a for loop.
Here's how you can do it:
# Define an array (or list)
my_array = [1, 2, 3, 4, 5]
1 Placeholder for future code: You can use pass as a placeholder when
you want to indicate that a block of code will be implemented later, but you
want to have a syntactically correct placeholder in the meantime.
if condition:
# To be implemented later
pass
class MyClass:
pass
if condition:
# Placeholder for future
code
pass
Using pass allows your code to remain syntactically correct while providing
a clear indication that the block of code is intentionally left empty or will be
implemented later.
5 Python break
Introduction
In Python, the break statement is used to exit (or "break out of") a loop
prematurely. When a break statement is encountered inside a loop (such as a
for loop or a while loop), the loop is immediately terminated, and the
program execution continues from the statement immediately following the
loop.
In this example, the loop iterates over the range from 0 to 4. When i
becomes equal to 2, the if condition i == 2 becomes true, and the break
statement is executed. As a result, the loop is terminated prematurely, and
the program execution continues after the loop.
Output:
0
1
2
Syntax
In Python, the break statement is used within loops to exit the loop
prematurely. Here are some common ways to use the break statement with
different types of loops:
1 Using break in a for loop:
for item in iterable:
# Code block
if condition:
break
In both cases:
The break statement is used to exit the loop immediately when
a certain condition is met.
It can be placed inside a conditional statement (if statement) to
define the condition under which the loop should be
terminated.
Once the break statement is executed, the loop is terminated,
and the program execution continues from the statement
immediately following the loop.
Here's an example demonstrating the usage of break in both types of loops:
# Using break in a for loop
for i in range(5):
print(i)
if i == 2:
break
break for
In Python, you can use the break statement within a for loop to exit the loop
prematurely based on a certain condition. Here's how you can use the break
statement in a for loop:
# Example: Using break in a for loop
for item in iterable:
# Code block
if condition:
break
In this syntax:
Output:
apple
banana
cherry
In this example, the loop terminates prematurely when the fruit variable
becomes equal to "cherry" due to the break statement.
In this syntax:
Output:
1
2
3
4
5
In this example, the inner loop terminates prematurely when the element
variable becomes equal to 5 due to the break statement. The outer loop then
terminates immediately because of the break statement outside the inner
loop.
break while
In Python, you can use the break statement within a while loop to exit the
loop prematurely based on a certain condition. Here's how you can use the
break statement in a while loop:
# Example: Using break in a while loop
while condition:
# Code block
if condition:
break
In this syntax:
Output:
0
1
2
6 Python continue
Introduction
In Python, the continue statement is used inside loops (such as for loops and
while loops) to skip the rest of the code inside the loop for the current
iteration and continue with the next iteration of the loop.
Here's a basic syntax of the continue statement:
for item in iterable:
# Code block
if condition:
continue
# More code
Or:
while condition:
# Code block
if condition:
continue
# More code
In this syntax:
Syntax
In Python, the continue statement is used within loops (such as for loops
and while loops) to skip the rest of the code inside the loop for the current
iteration and continue with the next iteration of the loop. The syntax for
using the continue statement varies slightly depending on the type of loop:
1 Using continue in a for loop:
for item in iterable:
# Code block
if condition:
continue
# More code
In both cases:
Output:
0
1
3
4
0
1
3
4
continue for
To use the continue statement within a for loop in Python, you can place it
inside the loop's block to skip the remaining code for the current iteration
and move to the next iteration. Here's how you can use the continue
statement in a for loop:
# Example: Using continue in a for loop
for item in iterable:
# Code block
if condition:
continue
# More code
In this syntax:
Output:
apple
cherry
date
In this example, when the fruit variable becomes equal to "banana", the
continue statement is executed, causing the rest of the code inside the loop
for that iteration to be skipped. The loop proceeds to the next iteration, and
the remaining fruits are printed.
continue while
To use the continue statement within a while loop in Python, you can place
it inside the loop's block to skip the remaining code for the current iteration
and move to the next iteration. Here's how you can use the continue
statement in a while loop:
# Example: Using continue in a while loop
while condition:
# Code block
if condition:
continue
# More code
In this syntax:
Output:
1
2
4
5
Chapter 5 :
Functions
1 Python function
Introduction
In Python, a function is a block of reusable code that performs a specific
task. Functions provide a way to organize code into manageable pieces,
improve code reusability, and make the code more readable.
Here's the syntax to define and use a function in Python:
1 Defining a function:
def function_name(parameter1, parameter2, ...):
# Function body
# Code to perform the task
return result
In this example:
We define a function add_numbers that takes two parameters x
and y, adds them together, and returns the result.
We call the function add_numbers with arguments 3 and 5, and
store the result in the variable sum_result.
We print the result to the console.
Parameters
In Python, function parameters are variables that are specified in the
function definition and are used to pass values to the function when it is
called. Parameters allow functions to accept input values and perform
operations on them.
2 Using parameters:
result = function_name(argument1, argument2, ...)
In this example:
Keyword Parameters
Keyword parameters (also known as keyword arguments) in Python are
parameters that are passed to a function by specifying their corresponding
parameter names along with the values. Keyword parameters allow you to
provide arguments to a function in any order, making the function call more
readable and flexible.
In this example:
In this syntax:
In this example:
Return Values
In Python, you can return values from a function using the return statement.
The return statement is used to exit the function and specify the value(s)
that the function should return to the caller. Here's the syntax to return
values from a Python function:
def function_name(parameter1, parameter2, ...):
# Function body
# Code that performs the task
return value1, value2, ...
In this syntax:
In this example:
Introduction
Function recursion in Python refers to the concept of a function calling
itself, either directly or indirectly. Recursion is a powerful technique used in
programming where a function solves a problem by breaking it down into
smaller, similar subproblems and calling itself to solve each subproblem.
Recursion continues until it reaches a base case, which is a simple case that
can be solved directly without further recursion.
# Example usage
result = factorial(5)
print(result) # Output: 120 (5! = 5 * 4 * 3 * 2 * 1 = 120)
In this example:
Recursion can make code more concise and elegant for certain types of
problems. However, it can also lead to performance issues and stack
overflow errors if not implemented carefully, especially for problems with
deep recursion or overlapping subproblems. In such cases, iteration or other
optimization techniques may be preferred.
Pros and cons
Recursion and iteration are both techniques used in programming to solve
problems, and each has its own set of advantages and disadvantages. Here
are some pros and cons of recursion and iteration in Python:
Recursion:
Pros:
1 Elegant solution: Recursion often leads to concise and elegant
solutions for problems that can be divided into smaller, identical
subproblems.
2 Readability: Recursive solutions closely mimic the problem's
definition, making the code easier to understand and maintain, especially
for problems involving tree structures or mathematical sequences.
3 Divide and conquer: Recursion is well-suited for divide-and-conquer
algorithms, where a problem can be broken down into smaller, similar
subproblems that are easier to solve.
Cons:
1 Performance overhead: Recursive function calls involve additional
overhead, such as function call stack management, which can lead to slower
execution compared to iterative solutions, especially for deep recursion.
2 Stack overflow: Recursive solutions can lead to stack overflow errors if
not implemented carefully, particularly for problems with deep recursion or
when the base case is not reached.
3 Difficulty in debugging: Recursive functions can be more difficult to
debug due to their indirect nature, making it challenging to trace the
execution flow.
Iteration:
Pros:
1 Efficiency: Iterative solutions often have better performance compared
to recursive solutions, especially for problems with large inputs or deep
recursion levels, as they typically involve less overhead.
2 Control over execution: Iteration provides more explicit control over
the execution flow, making it easier to understand and debug, particularly
for complex algorithms.
3 Tail optimization: Some programming languages, including Python,
support tail call optimization, which allows certain tail-recursive functions
to be optimized into iterative form, eliminating the risk of stack overflow.
Cons:
1 Complexity: Iterative solutions can sometimes be more complex and
less intuitive, especially for problems that naturally lend themselves to
recursive solutions.
2 Verbose code: Iterative solutions may require more lines of code and
additional variables to maintain loop state, leading to less concise code
compared to recursive solutions for certain problems.
3 Difficulty with certain problems: Some problems may be inherently
difficult to solve iteratively, especially those involving tree traversal or
backtracking, where recursion provides a more natural and intuitive
approach.
In this code:
String Reverse
You can reverse a string using recursion in Python by recursively swapping
the characters at the beginning and end of the string until the entire string is
reversed. Here's how you can implement it:
def reverse_string(s):
if len(s) <= 1:
return s
else:
return reverse_string(s[1:]) + s[0]
In this code:
The base case is when the length of the string is less than or
equal to 1. In this case, the string itself is returned.
Otherwise, the function returns the result of recursively calling
reverse_string on the substring starting from the second
character (s[1:]) and then appending the first character (s[0]) at
the end.
The function keeps calling itself with substrings until it
reaches the base case, at which point the recursion stops and
the reversed string is constructed.
Chapter 6 :
Object Oriented
1 Python Modules
Introduction
A Python module is a file containing Python code, which can define
functions, classes, and variables. The purpose of a Python module is to
organize related code into a reusable and shareable unit. Modules provide a
way to structure large Python projects into smaller, manageable
components, making it easier to maintain, test, and collaborate on code.
Here are some key purposes and benefits of using Python modules:
1 Code Organization: Modules help organize code by grouping related
functionality together. This makes it easier to understand and maintain the
codebase.
5 Scoping: Modules define their own scope, which helps avoid polluting
the global namespace. Variables and functions defined within a module are
accessible only within that module unless explicitly imported or exported.
Create
To create a Python module, you simply need to create a Python file (.py)
containing the code you want to include in the module. Here's a step-by-
step guide on how to create a Python module:
1 Create a Python File: Create a new file with a .py extension. This file
will contain the code for your module. For example, you can name it
mymodule.py.
2 Write Module Code: Write the Python code for your module in the
created file. This can include function definitions, class definitions, variable
assignments, and any other Python code you want to include in the module.
3 Define Module Interface: Decide which functions, classes, and
variables you want to make accessible to users of your module. These will
be the public interface of your module.
4 Save the File: Save the Python file containing your module code.
5 Use the Module: You can now import and use your module in other
Python scripts or modules by using the import statement.
def greet(name):
return f"Hello, {name}!"
PI = 3.14159
To use this module in another Python script, you would import it like this:
# main.py
import mymodule
This structure allows you to organize your modules into logical groups and
namespaces, making it easier to manage and maintain larger codebases.
import Syntax
In Python, the import statement is used to include various Python modules
into your code. There are several syntaxes you can use depending on what
you want to achieve:
1 Importing the entire module:
import module_name
Example:
import math
2 Importing with an alias:
import module_name as alias
Example:
import numpy as np
Example:
from math import sqrt, pi
This imports all attributes defined in the module, but it's generally
discouraged because it can lead to namespace pollution and make it unclear
where certain functions or classes come from.
Example:
from math import
*
5 Importing a submodule:
import package_name.module_name
Example:
import matplotlib.pyplot as plt
These are the primary ways to use the import statement in Python. Each has
its use case depending on the requirements of your program and your
coding style preferences.
Replace module_name with the name of the module you want to import
from.
Example:
from math import
*
This imports all functions and attributes from the math module into the
current namespace. However, it's recommended to import only the specific
functions or attributes you need from a module to keep your code clean and
avoid potential naming conflicts.
Alias
In Python, you can give a module, a function, or a class an alias using the as
keyword. This is particularly useful when you want to shorten long module
names, clarify the purpose of a function or class, or avoid naming conflicts.
Here's how you can use as to give an alias:
1 Alias for a module:
import module_name as alias
Example:
import numpy as np
2 Alias for a function or a class:
from module_name import function_name_or_class_name as alias
Example:
from math import sqrt as square_root
In the above examples, np is an alias for the numpy module, and
square_root is an alias for the sqrt function from the math module.
Using aliases can make your code more readable and concise, especially
when dealing with long module names or when you need to clarify the
purpose of certain functions or classes.
Importing Specific Functions
You can import specific Python functions using the import statement along
with the from keyword. Here's the syntax:
from module_name import function_name1, function_name2, ...
Example:
Let's say you want to import the sqrt and cos functions from the math
module:
from math import sqrt, cos
Now you can use these functions directly in your code without prefixing
them with the module name:
print(sqrt(4)) # Output: 2.0
print(cos(0)) # Output: 1.0
This syntax is useful when you only need specific functions from a module
and don't want to import the entire module. It can also make your code
more readable by clearly indicating which functions are being used.
Importing Classes
To import classes from a module in Python, you can use the import
statement along with the from keyword, similar to how you import
functions. Here's the syntax:
from module_name import ClassName1, ClassName2, ...
Replace module_name with the name of the module containing the classes
you want to import, and list the class names you want to import separated
by commas.
Example:
Let's say you have a module named my_module containing two classes Dog
and Cat, and you want to import both classes:
from my_module import Dog, Cat
Now you can create objects of these classes directly in your code:
my_dog = Dog("Buddy")
my_cat = Cat("Whiskers")
This syntax is useful when you only need specific classes from a module
and don't want to import the entire module. It can also make your code
more readable by clearly indicating which classes are being used.
Importing Multiple Classes
To import multiple classes from a Python module, you can use the from
keyword followed by the module name, and then list the class names you
want to import, separated by commas. Here's the syntax:
from module_name import ClassName1, ClassName2, ...
Replace module_name with the name of the module containing the classes
you want to import, and list the class names you want to import separated
by commas.
Example:
Let's say you have a module named my_module containing two classes Dog
and Cat, and you want to import both classes:
from my_module import Dog, Cat
Now you can create objects of these classes directly in your code:
my_dog = Dog("Buddy")
my_cat = Cat("Whiskers")
This syntax allows you to import multiple classes from a module in a single
line, making your code more concise and readable.
Importing an Entire Module
If you want to import an entire module from another Python module, you
can use the simple import statement. Here's how:
import module_name
Replace module_name with the name of the module you want to import.
Example:
Let's say you have a module named my_module and you want to import the
entire module:
import my_module
This approach imports the entire module, including all functions, classes,
variables, etc. It's the simplest way to import an entire module, but it can
lead to namespace pollution if the module contains a lot of definitions.
Replace module_name with the name of the module containing the classes
you want to import.
Example:
Let's say you have a module named my_module containing several classes
(Class1, Class2, etc.), and you want to import all of them:
from my_module import *
After this import statement, you can directly use any class defined in
my_module without prefixing it with my_module. For example:
obj1 =
Class1()
obj2 =
Class2()
However, be cautious when using this approach because it can lead to
namespace pollution and make it unclear where certain classes come from,
especially if the module contains a large number of classes. It's generally
recommended to import specific classes or use an alias to avoid these
issues.
Importing a Module
To import a module into another Python module, you can use the import
statement. Here's the syntax:
import module_name
Replace module_name with the name of the module you want to import.
Example:
Let's say you have two Python modules, module1.py and module2.py, and
you want to import module1 into module2:
In module2.py:
import module1
some_function()
obj = SomeClass()
2 Python class
Introduction
In Python, a class is a blueprint for creating objects (instances). It defines
the properties (attributes) and behaviors (methods) that all objects created
from it will have. Classes are fundamental to object-oriented programming
(OOP), a programming paradigm that models real-world entities as objects
with attributes and behaviors.
2 Methods: These are functions defined within a class that can perform
operations on the class's data.
__init__()
In Python, __init__() is a special method (also known as a constructor) that
is automatically called when a new instance of a class is created. It is used
to initialize the attributes of the newly created object. The __init__()
method is optional, but it is commonly used to set up the initial state of an
object.
Here's the syntax for defining the __init__() method within a class:
class ClassName:
def __init__(self, parameter1, parameter2, ...):
# Initialization code here
In this example, the __init__() method initializes the name and age
attributes of each Person object when it is created. When you create a new
Person object (person1 and person2), you provide values for name and age,
which are then assigned to the corresponding attributes of the object.
Instance
To make an instance from a Python class, you need to follow these steps:
1 Define the class: Define the blueprint for the objects you want to create
by writing a class definition.
Now, you can use my_instance to access the attributes and methods of the
MyClass object:
print(my_instance.parameter1)
print(my_instance.parameter2)
Replace value1 and value2 with the values you want to initialize the
instance with. This is how you make an instance from a Python class.
Attributes
To access an attribute from a Python class, you use dot notation (.) followed
by the attribute name. Here's how you do it:
1 First, you need to create an instance of the class.
2 Then, you can use dot notation to access the attributes of
that instance.
Here's an example:
class MyClass:
def __init__(self, attribute):
self.attribute = attribute
In this example:
Calling Methods
To call methods defined in a Python class, you follow these steps:
1 Create an instance of the class.
2 Use dot notation (.) followed by the method name to call the method on
that instance.
def my_method(self):
print("Hello from my_method!")
In this example:
We define a class named MyClass with an __init__() method
that initializes an attribute (self.attribute) with the value passed
as an argument, and a my_method() method.
We create an instance of MyClass called my_instance and pass
the value "value" to the constructor.
We then call the my_method() method on the my_instance
object using dot notation (my_instance.my_method()).
This will print "Hello from my_method!", indicating that the method has
been called successfully on the instance of the class.
class Subclass(Superclass):
# Additional attributes and methods
Syntax
In Python, creating inheritance between classes involves defining a new
class that inherits from an existing class. Here's the syntax to create
inheritance in Python:
class BaseClass:
# Attributes and methods of the base class
class DerivedClass(BaseClass):
# Additional attributes and methods of the derived class
In this example, Dog and Cat are subclasses of Animal. They inherit the
sound() method from Animal but provide their own implementation of the
method. When you call sound() on instances of Dog and Cat, it prints the
sound specific to each subclass.
__init__()
To define and use the __init__() method for a child class (subclass) in
Python inheritance, you can override the __init__() method of the parent
class (superclass). This allows you to customize the initialization process
for instances of the child class while still leveraging the initialization logic
of the parent class if needed. Here's how you can do it:
class ParentClass:
def __init__(self, parent_attribute):
self.parent_attribute = parent_attribute
print("ParentClass initialized with:", self.parent_attribute)
class ChildClass(ParentClass):
def __init__(self, parent_attribute, child_attribute):
# Call the __init__() method of the parent class
super().__init__(parent_attribute)
self.child_attribute = child_attribute
print("ChildClass initialized with:", self.child_attribute)
This approach ensures that the initialization logic defined in the parent class
is executed before the initialization logic of the child class, allowing for
proper initialization of attributes in both classes.
Overriding Methods
In Python, you can override methods from the parent class in a child class
by defining a method with the same name in the child class. When an
instance of the child class calls the method, the overridden method in the
child class will be executed instead of the method from the parent class.
Here's how you can override methods from the parent class in Python:
class ParentClass:
def some_method(self):
print("This is a method from ParentClass")
class ChildClass(ParentClass):
def some_method(self):
print("This is an overridden method from ChildClass")
This demonstrates how you can override methods from the parent class in
Python. Overriding methods allows child classes to provide their own
implementations of methods inherited from the parent class, providing
flexibility and customization in object-oriented programming.
4 Python Abstract Base Classes
Introduction
Abstract Base Classes (ABCs) in Python are classes that cannot be
instantiated directly but are meant to be subclassed. They define a set of
abstract methods that must be implemented by concrete subclasses. ABCs
provide a way to define a common interface or behavior for a group of
related classes while enforcing a contract that specifies which methods must
be implemented by subclasses.
To use Abstract Base Classes in Python, you need to import the abc module
from the standard library, which provides the ABC class and other utilities
for defining and working with abstract classes. Here's how you can define
and use Abstract Base Classes in Python:
from abc import ABC, abstractmethod
class Shape(ABC):
@abstractmethod
def area(self):
pass
@abstractmethod
def perimeter(self):
pass
class Rectangle(Shape):
def __init__(self, length, width):
self.length = length
self.width = width
def area(self):
return self.length * self.width
def perimeter(self):
return 2 * (self.length + self.width)
ABC as concept
Abstract classes in Python serve as templates for other classes. They are not
meant to be instantiated directly but instead are designed to be subclassed.
Abstract classes define a blueprint for how subclasses should be structured
and what methods they should implement. They typically contain one or
more abstract methods, which are methods that are declared but not
implemented in the abstract class itself. Subclasses must provide concrete
implementations for these abstract methods.
ABC subclass
Subclassing an Abstract Base Class (ABC) in Python involves creating a
new class that inherits from the ABC and provides concrete
implementations for its abstract methods. This allows you to define a
common interface or behavior specified by the ABC and ensure that
subclasses adhere to this interface by implementing the required methods.
Here's how you can subclass an ABC and use it in Python:
3 Using the subclasses: Finally, you can instantiate and use the concrete
subclasses, which now adhere to the interface defined by the ABC.
class Shape(ABC):
@abstractmethod
def area(self):
pass
@abstractmethod
def perimeter(self):
pass
class Rectangle(Shape):
def __init__(self, length, width):
self.length = length
self.width = width
def area(self):
return self.length * self.width
def perimeter(self):
return 2 * (self.length + self.width)
class Circle(Shape):
def __init__(self, radius):
self.radius = radius
def area(self):
return 3.14 * self.radius ** 2
def perimeter(self):
return 2 * 3.14 * self.radius
In this example:
def __str__(self):
return f"({self.x}, {self.y})"
In this example:
We define a Point class to represent 2D points with x and y
coordinates.
We overload the +, -, and * operators by defining special
methods __add__, __sub__, and __mul__, respectively.
When we use the +, -, and * operators with Point objects,
Python automatically calls the corresponding special methods.
We also define a __str__ method to customize the string
representation of Point objects when using print().
Operator overloading allows you to write more expressive and concise code
by providing natural syntax for operations on user-defined objects. It's a
powerful feature of Python's object-oriented programming model that
enables customization of behavior to suit the needs of your classes.
Addition
To overload the addition operator (+) for numerical operations in Python,
you need to define the special method __add__() within your class. This
method will be automatically called when the addition operator is used with
instances of your class. Here's how to overload the addition operator for
numerical operations in Python:
class Number:
def __init__(self, value):
self.value = value
def __str__(self):
return str(self.value)
In this example:
You can now use the addition operator (+) with instances of the Number
class, and Python will automatically call the __add__() method to perform
the addition operation.
Subtraction
To overload the subtraction operator (-) for numerical operations in Python,
you need to define the special method __sub__() within your class. This
method will be automatically called when the subtraction operator is used
with instances of your class. Here's how to overload the subtraction
operator for numerical operations in Python:
class Number:
def __init__(self, value):
self.value = value
def __str__(self):
return str(self.value)
In this example:
def __str__(self):
return str(self.value)
In this example:
You can now use the multiplication operator (*) with instances of the
Number class, and Python will automatically call the __mul__() method to
perform the multiplication operation.
Chapter 7 :
Advanced
1 Python File
Access Modes
Python file access modes are used to specify the mode in which a file is
opened. Each mode determines the operations that can be performed on the
file, such as reading, writing, appending, or creating a new file. Here are the
commonly used file access modes in Python:
1 'r': Open for reading (default). If the file does not exist or cannot be
opened, an IOError will be raised.
2 'w': Open for writing. If the file already exists, its contents will be
overwritten. If the file does not exist, it will be created.
3 'a': Open for appending. The file pointer is positioned at the end of the
file. New data will be written to the end of the file. If the file does not exist,
it will be created.
4 'r+': Open for reading and writing. The file pointer is positioned at the
beginning of the file. If the file does not exist or cannot be opened, an
IOError will be raised.
5 'w+': Open for reading and writing. If the file already exists, its
contents will be overwritten. If the file does not exist, it will be created.
6 'a+': Open for reading and appending. The file pointer is positioned at
the end of the file. New data will be written to the end of the file. If the file
does not exist, it will be created.
Here's how you can use these file access modes in Python:
# Open a file in read mode
with open('file.txt', 'r') as file:
content = file.read()
print(content)
# Open a file in read and write mode (creating a new file if it doesn't exist)
with open('new_file.txt', 'w+') as file:
file.write('This is a new file')
# Open a file in read and append mode (creating a new file if it doesn't exist)
with open('new_file.txt', 'a+') as file:
file.write('\nThis is appended content')
Remember to always close the file using the with statement or by explicitly
calling the close() method after you are done working with it. This ensures
that any resources used by the file are properly released.
Handler
In Python, a file handler (also referred to as a file object or file descriptor)
is an object that represents an open file. It provides methods and attributes
that allow you to interact with the file, such as reading from it, writing to it,
or manipulating its contents.
File handlers are typically obtained by calling the open() function, which
returns a file handler associated with the specified file. You can then use
this file handler to perform various operations on the file.
Here's how to use a file handler in Python:
# Open a file in read mode and obtain a file handler
file_handler = open('file.txt', 'r')
In this example:
After executing this code, the file 'file.txt' will contain the original contents,
followed by the new data appended at the end. It's worth noting that the file
will be created if it does not already exist. If you want to append data to an
existing file, ensure it's present in the specified location.
Create
To create and write content to a file using a file handler in Python, you can
open the file in write mode ('w') and then use the file handler's write()
method to add the desired content. Here's how you can do it:
# Open the file in write mode and obtain a file handler
with open('file.txt', 'w') as file_handler:
# Write data to the file
file_handler.write('This is some content that we are writing to the file.\n')
file_handler.write('This is another line of content.\n')
In this example:
File size
You can use the os.path.getsize() function from the os module to get the size
of a file in bytes. Here's how you can use it:
import os
In this example:
Move File
To move a file from one directory to another in Python, you can use the
shutil.move() function from the shutil module. Here's how you can use it:
import shutil
# Move the file from the source directory to the destination directory
shutil.move(source_file, destination_file)
In this example:
In this example:
Read
To read from a file in Python, you can use the open() function to open the
file and obtain a file handler, and then use methods like read(), readline(), or
readlines() to read the content from the file. Here's how you can do it:
1 Reading the entire contents of a file at once using read():
# Open the file in read mode and obtain a file handler
with open('file.txt', 'r') as file_handler:
# Read the entire contents of the file
content = file_handler.read()
print(content)
In each example:
We use the open() function with the file name 'file.txt' and the
mode 'r' to open the file in read mode.
We use a context manager (with statement) to automatically
close the file handler after it's been opened.
We use one of the file handler's methods (read(), readline(), or
readlines()) to read the content from the file.
We print the content to the console.
Path
In Python, you can obtain both relative and absolute file paths using various
methods. Here are some common approaches:
1 Using the os.path Module:
The os.path.abspath() function returns the absolute path of a
file.
The os.path.relpath() function returns the relative path of a
file from a specified directory (or the current working
directory if not specified).
import os
# Absolute path
absolute_path = os.path.abspath('file.txt')
print("Absolute path:", absolute_path)
# Absolute path
absolute_path = Path('file.txt').resolve()
print("Absolute path:", absolute_path)
# Absolute path
absolute_path = os.path.join(cwd, relative_path)
print("Absolute path:", absolute_path)
Choose the method that best fits your requirements and coding style. The
pathlib module is recommended for its object-oriented interface and
improved readability.
Line
To access lines of a file in Python, you can use various methods provided
by file objects, such as readline(), readlines(), or iterating over the file
object itself. Here's how you can do it:
1 Using readline():
# Open the file in read mode and obtain a file handler
with open('file.txt', 'r') as file_handler:
# Read one line at a time
line = file_handler.readline()
while line:
# Process the line
print(line.strip()) # strip() to remove leading and trailing whitespace
# Read the next line
line = file_handler.readline()
2 Using readlines():
# Open the file in read mode and obtain a file handler
with open('file.txt', 'r') as file_handler:
# Read all lines into a list
lines = file_handler.readlines()
# Iterate over the lines
for line in lines:
# Process each line
print(line.strip()) # strip() to remove leading and trailing whitespace
In each example:
We use the open() function with the file name 'file.txt' and the
mode 'r' to open the file in read mode.
We use a context manager (with statement) to automatically
close the file handler after it's been opened.
We use one of the methods (readline(), readlines(), or iterating
over the file object) to access lines from the file.
We process each line as needed, such as stripping leading and
trailing whitespace using strip(), and then print it to the
console.
Write
To write a line to a file using Python, you can use the write() method of the
file object. Here's how you can do it:
# Open the file in write mode and obtain a file handler
with open('output.txt', 'w') as file_handler:
# Write a line to the file
file_handler.write("This is a line written to the file.\n")
In this example:
We use the open() function with the file name 'output.txt' and
the mode 'w' to open the file in write mode. If the file does not
exist, it will be created. If the file already exists, its contents
will be overwritten.
We use a context manager (with statement) to automatically
close the file handler after it's been opened.
We use the write() method of the file handler to write the
specified line to the file. The '\n' character is used to add a
newline at the end of the line.
After executing this code, the file 'output.txt' will contain the line "This is a
line written to the file." followed by a newline character.
3 Python Exceptions
Introduction
An exception in Python is an event that occurs during the execution of a
program that disrupts the normal flow of the program's instructions. When
an exceptional condition arises, such as an error or unexpected behavior,
Python raises an exception to handle the situation.
try-except
In Python, you use the try and except blocks to handle exceptions. The
basic syntax is as follows:
try:
# Code that may raise an exception
# ...
except ExceptionType:
# Code to handle the exception
# ...
The try block contains the code that may raise an exception.
It's the block where you expect the potential error to occur.
The except block specifies the type of exception that you want
to catch and handle. If an exception of the specified type (or a
subclass of it) occurs within the try block, the corresponding
except block is executed.
You can have multiple except blocks to handle different types
of exceptions, or a single except block to catch all exceptions.
If no specific exception type is specified, it will catch all
exceptions (not recommended unless you have a good reason).
try:
# Code that may raise an exception
num1 = int(input("Enter a number: "))
num2 = int(input("Enter another number: "))
result = num1 / num2
print("Result:", result)
except ValueError:
# Handle ValueError (e.g., invalid input)
print("Please enter valid integers.")
except ZeroDivisionError:
# Handle ZeroDivisionError (e.g., division by zero)
print("Error: Division by zero is not allowed.")
except Exception as e:
# Handle any other type of exception
print("An error occurred:", e)
In this example:
else
In Python, you can use a try...else block to handle exceptions in a way that
distinguishes between the code that may raise an exception and the code
that should run if no exception occurs. The else block is executed only if no
exception is raised in the try block. Here's the syntax:
try:
# Code that may raise an exception
# ...
except ExceptionType:
# Code to handle the exception
# ...
else:
# Code to execute if no exception occurs
# ...
The try block contains the code that may raise an exception.
This is the block where you expect the potential error to occur.
The except block specifies the type of exception that you want
to catch and handle. If an exception of the specified type (or a
subclass of it) occurs within the try block, the corresponding
except block is executed.
In this example:
The try block contains the code that may raise an exception.
This is the block where you expect the potential error to occur.
The except block specifies the type of exception that you want
to catch and handle. If an exception of the specified type (or a
subclass of it) occurs within the try block, the corresponding
except block is executed.
In this example:
The try block attempts to open a file 'file.txt' for reading and
read its contents.
If a FileNotFoundError occurs (e.g., if the file does not exist),
the corresponding except FileNotFoundError block handles it.
The finally block ensures that the file is closed using the
close() method, even if an exception occurs or not. This
cleanup action is executed regardless of whether an exception
is raised, ensuring that the file is properly closed and resources
are released.
4 Python Testing
Introduction
Unit testing is a software testing technique where individual units or
components of a software application are tested in isolation to ensure they
behave as expected. In Python, unit testing is commonly performed using
the built-in unittest module or third-party libraries like pytest.
Identify bugs early: Unit tests can catch bugs early in the
development process, making them easier and cheaper to
fix.
Ensure code quality: Unit tests help maintain code quality
by providing a safety net for refactoring and code changes.
They ensure that existing functionality remains intact as the
codebase evolves.
Facilitate collaboration: Unit tests serve as documentation
for how a piece of code should behave. They make it easier
for developers to understand and collaborate on the
codebase.
Promote confidence: Having a comprehensive suite of unit
tests gives developers confidence that their code works as
intended. It allows them to make changes with the assurance
that existing functionality won't be inadvertently broken.
3 How to write unit tests: In Python, unit tests are written using the
unittest framework or other testing libraries like pytest. You define test
cases as subclasses of unittest.TestCase and write test methods that verify
the behavior of individual functions or classes. Test methods typically use
assertions to check expected outcomes against actual results.
class TestAddFunction(unittest.TestCase):
def test_add_positive_numbers(self):
self.assertEqual(add(2, 3), 5)
def test_add_negative_numbers(self):
self.assertEqual(add(-2, -3), -5)
if __name__ == '__main__':
unittest.main()
In this example, we define a simple add function and write unit tests to
verify its behavior for different input scenarios.
pytest install
You can install pytest using pip, the package installer for Python. Here's the
command to install pytest:
pip install pytest
You can run this command in your terminal or command prompt to install
pytest. Make sure you have pip installed and configured properly in your
Python environment.
Once pytest is installed, you can use it to write and run tests for your
Python code.
3 Write test functions: Write test functions using the test_ prefix to
indicate that they are test cases. Within these functions, use assertions to
verify the expected behavior of the code being tested.
def test_add_positive_numbers():
assert add(2, 3) == 5
def test_add_negative_numbers():
assert add(-2, -3) == -5
4 Run pytest: To run your tests, navigate to the directory containing your
test file(s) in your terminal or command prompt, and run the pytest
command:
pytest
pytest will automatically discover and run any test functions defined in files
with names that start with test_. It will display the results of the tests,
including any failures or errors.
You can also specify the name of the test file(s) or directories containing
test files to run specific tests:
pytest test_example.py
This command runs only the tests defined in test_example.py.