Practical Python
Practical Python
The "Hello, World!" program is a simple and traditional way to demonstrate the basic syntax and
structure of a programming language. In Python, creating a "Hello, World!" program is quite
straightforward. Here's a theoretical explanation of how it works:
1. print() Function: In Python, the print() function is used to display output. It takes one or more
arguments and prints them to the console. In this case, we are passing a single argument, which
is the string "Hello, World!".
2. String: "Hello, World!" is enclosed in double quotes (") to indicate that it is a string. A string is a
sequence of characters, and it can contain letters, numbers, symbols, or any combination
thereof. In this case, it contains the text "Hello, World!".
3. Parentheses: The print() function is followed by parentheses (). In Python, functions are called
by placing the function name inside parentheses. The print() function requires the string you
want to print to be enclosed in these parentheses.
When you run this Python code, it instructs the computer to display "Hello, World!" on the screen. This
is a common first program in many programming languages because it helps beginners understand how
to write, execute, and see the output of a basic program.
Practical theory
Practical 1B:- mathematical calculations
Mathematical calculations in Python involve performing various arithmetic and mathematical operations
on numbers and data. Python provides a rich set of built-in mathematical functions and operators that
make it a powerful tool for numerical computations. Here's a theoretical overview of mathematical
calculations in Python:
1. num1 = int(input('Enter first number: ')): This line prompts the user to enter the first number as
input using the input() function. The input is treated as a string by default, so it is converted to
an integer using the int() function and stored in the variable num1.
2. num2 = int(input('Enter second number: ')): Similarly, this line prompts the user to enter the
second number, converts it to an integer, and stores it in the variable num2.
3. add = num1 + num2: This line calculates the sum of num1 and num2 and stores the result in the
variable add.
4. print("the addition of two number is ====>", add): Here, the code prints the result of the
addition operation along with a message. It uses the print() function to display the message and
the value of add.
5. print("======================================="): This line prints a separator line made
up of equal signs to separate the output for different operations.
6. sub = num1 - num2: This line calculates the difference between num1 and num2 and stores it in
the variable sub.
7. print("the addition of two number is ====>", sub): The code prints the result of the subtraction
operation along with a message.
8. mul = num1 * num2: This line calculates the product of num1 and num2 and stores it in the
variable mul.
9. print("the addition of two number is ====>", mul): The code prints the result of the
multiplication operation along with a message.
10. div = num1 / num2: This line calculates the division of num1 by num2 and stores it in the
variable div. Note that this division operation results in a floating-point number.
11. print("the addition of two number is ====>", div): The code prints the result of the division
operation along with a message.
12. print("======================================="): Finally, another separator line is
printed to separate the output for the division operation.
Practical theory
Practical 2:- Write a program to find all prime numbers within a given range
This code is designed to find and print all prime numbers within a given range. Let's break down the
code step by step:
1. User Input: The code starts by asking the user to input two integers: lower_value and
upper_value. These values represent the lower and upper bounds of the range within which the
program will search for prime numbers.
2. Print Statement: After taking user input, the code prints a message to indicate that it will display
the prime numbers within the specified range.
3. For Loop: The program uses a for loop to iterate through all the numbers in the range from
lower_value to upper_value + 1. The +1 is added to ensure that the upper bound is inclusive.
4. Prime Number Check: Inside the loop, there is an if statement that checks whether the current
number (number) is greater than 1. This is because prime numbers are defined as positive
integers greater than 1.
5. Nested For Loop: If the current number is greater than 1, a nested for loop is used. This nested
loop iterates through all numbers from 2 to number - 1.
6. Prime Determination: Within the nested loop, the code checks whether the current number
(number) is divisible by any number in the range from 2 to number - 1. If it finds any divisor, it
immediately breaks out of the loop using the break statement. This is because a prime number
should have no divisors other than 1 and itself.
7. Prime Number Printing: If the nested loop completes without finding any divisors, it means that
the current number is prime. In this case, the code prints the prime number using the
print(number) statement.
8. Loop Continuation: The outer for loop continues to the next number in the range and repeats
the prime-checking process for that number.
Output: As a result, all prime numbers within the specified range are printed to the console.
Practical theory
Practical 3) write a program to print "n" terms of Fibonacci Series using Iteration
The Fibonacci series is a sequence of numbers where each number is the sum of the two preceding
ones. It typically starts with 0 and 1. In mathematical terms, the Fibonacci series can be defined as
follows:
1. User Input: The code begins by prompting the user to enter the number of terms they want in
the Fibonacci sequence. This input is stored in the variable nterms.
2. Initialization: Two variables, n1 and n2, are initialized with values 0 and 1, respectively. These
represent the first two terms of the Fibonacci sequence.
3. Count Initialization: Another variable count is initialized to 0. This variable will be used to keep
track of how many terms have been generated and displayed so far.
4. Validity Check: The code checks if the value of nterms is less than or equal to 0. If nterms is not a
positive integer, the code prints a message asking the user to enter a positive integer and
terminates.
5. Handling n = 1: If the user enters nterms equal to 1, the code prints a message indicating that
only the first term of the Fibonacci sequence will be displayed, which is 0.
6. Fibonacci Sequence Generation (n > 1): If nterms is greater than 1, the code enters a loop to
generate and print the Fibonacci sequence.
The loop begins with the message "Fibonacci sequence:" to indicate the start of the sequence.
It calculates the next term in the sequence (nth) by adding n1 and n2.
It increments the count variable by 1 to keep track of the number of terms generated.
The loop continues until count is equal to nterms, at which point it will have generated and printed the
requested number of terms in the Fibonacci sequence.
7. Output: The code generates and displays the Fibonacci sequence as per the user's input.
Practical theory
Practical 4 write a program to demonstrate the use of slicing in string.
Python slicing is about obtaining a sub-string from the given string by slicing it respectively from start
to end.
For understanding slicing we will use different methods, here we will cover 2 methods of string
slicing, one using the in-build slice() method and another using the [:] array slice. String slicing in
Python is about obtaining a sub-string from the given string by slicing it respectively from start to end.
1. a slice() method
2. Using the array slicing [:: ] method
Index tracker for positive and negative index: String indexing and slicing in python. Here, the Negative
comes into consideration when tracking the string in reverse.
The slice() constructor creates a slice object representing the set of indices specified by range(start,
stop, step).
Syntax:
• slice(stop)
• slice(start, stop, step)
Parameters: start: Starting index where the slicing of object starts. stop: Ending index where the slicing
of object stops. step: It is an optional argument that determines the increment between each index for
slicing. Return Type: Returns a sliced object containing elements in the given range only.
In Python, indexing syntax can be used as a substitute for the slice object. This is an easy and convenient
way to slice a string using list slicing and Array slicing both syntax-wise and execution-wise. A start, end,
and step have the same mechanism as the slice() constructor.
Practical theory
Syntax
arr[start:stop] # items start through stop-1
arr[start:] # items start through the rest of the array
arr[:stop] # items from the beginning through stop-1
arr[:] # a copy of the whole array
arr[start:stop:step] # start through not past stop, by step
Function:
A function is a block of reusable code that is used to perform a particular task. Functions are used to
keep repeated tasks, and a function call is made when you want to perform the same task.
Functions also help reduce the length of your code and prevent DRY. A function must be called in order
for it to run.
1. import math: This line imports the Python math module. The math module provides
mathematical functions and constants for performing various mathematical operations in
Python.
2. print("Square root of 16:", math.sqrt(16)): This line uses the print() function to display the result
of calculating the square root of 16 using the math.sqrt() function from the math module.
• math.sqrt(16) calculates the square root of the number 16.
• The result is then printed as part of the message "Square root of 16:" followed by the calculated
square root value.
In this output:
• "Square root of 16:" is the message you provided to indicate what is being calculated.
• math.sqrt(16) evaluates to 4.0 because the square root of 16 is 4
Modules in Python:
A module in Python is a file containing Python code, including functions, classes, and variables, that can
be imported and used in other Python programs. Modules help organize and encapsulate code into
separate files, making it easier to manage and maintain large codebases.
To create a Python module named " def my_func()" that contains several mathematical functions and
then use this module in another Python script to perform mathematical operations.
1. def my_func():: This line defines a Python function named my_func(). The function definition
starts with the def keyword, followed by the function name, parentheses (which can contain
Practical theory
parameters, but in this case, there are none), and a colon : to indicate the start of the function
body.
2. print("Greetings User! Welcome to Javatpoint."): Inside the function body, there is a print()
statement. When this function is called, it will print the message "Greetings User! Welcome to
Javatpoint." to the console.
3. my_func(): This line calls (or invokes) the my_func() function. When this line is executed, it
triggers the execution of the code inside the my_func() function.
This Python program demonstrates the principles of functional programming using three built-in
functions: map(), filter(), and reduce(). Functional programming is a programming paradigm that treats
computation as the evaluation of mathematical functions and avoids changing state and mutable data.
In this theory, we will explain how these functions are used in the program and their role in functional
programming.
The program starts by importing the reduce function from the functools module. This function is used
for performing a cumulative operation on a sequence.
numbers = [1, 2, 3, 4, 5]
A sample list of numbers is defined. This list will be used for various operations.
The square function is defined to calculate the square of a number x. This function will be used with the
map() function to square each number in the list.
The is_even function is defined to check if a number x is even. This function will be used with the filter()
function to filter out even numbers from the list.
The add function is defined to calculate the sum of two numbers x and y. This function will be used with
the reduce() function to calculate the total sum of all numbers in the list.
The map() function is used to apply the square function to each element in the numbers list. It returns
an iterable of squared numbers, which is then converted to a list.
The filter() function is used to filter out even numbers from the numbers list using the is_even function.
It returns an iterable of even numbers, which is then converted to a list.
The reduce() function is used to calculate the total sum of all numbers in the numbers list by applying
the add function cumulatively.
Explanation:
1. We use the map() function to apply the square lambda function to each element in the numbers
list. This produces a new iterable of squared numbers.
2. We use the reduce() function from the functools module to calculate the sum of the squared
numbers. The reduce() function takes a lambda function that accumulates the result as it
iterates through the squared numbers.
3. The result is the sum of the squares, which is displayed using print().
Practical 7 Write a program to demonstrate the use of list & related functions.
This Python code demonstrates various operations that can be performed on lists, a commonly used
data structure in Python. Lists are ordered collections of items that can hold a variety of data types. In
this theory, we will explain the code step by step and provide a comprehensive overview of list
manipulation operations in Python.
Accessing elements in a list is achieved using indexing. Lists are zero-indexed, meaning the first element
is at index 0, the second at index 1, and so on.
Negative indexing allows you to access elements from the end of the list.
Lists are mutable, which means you can change the values of individual elements by assigning new
values to them using their indices.
Practical theory
3. Adding Elements to a List:
You can add elements to the end of a list using the append() method.
You can use the in operator to check if a specific element exists in the list.
7. Sorting a List:
The sort() method sorts the list in ascending order. You can use the reverse parameter to sort in
descending order.
8. Reversing a List:
9. Copying a List:
You can create a copy of a list using the copy() method or by slicing the entire list (fruits_copy = fruits[:]).
- The `clear()` method removes all elements from the list, leaving it empty.
Program Explanation:
The provided Python code demonstrates all these list manipulation operations using a list of fruits. It
showcases how to access, modify, add, remove, find the length, check for elements, sort, reverse, copy,
and clear a list.
Practical 8. Write a program to demonstrate the use of Dictionary & related functions
Dictionaries in Python are unordered collections of data that consist of key-value pairs. Each key in a
dictionary is associated with a specific value. Dictionaries are commonly used to store and retrieve data
based on unique keys. In this code example, we create a dictionary named student_info to store
information about a student, and we'll provide a full explanation of the code.
• We create a dictionary named student_info using curly braces {}. Inside the dictionary, we have
key-value pairs separated by colons :.
• Each key is a string and represents a piece of information about the student, such as 'name',
'age', 'grade', and 'courses'.
Practical theory
• The corresponding values are associated with each key. In this case, 'John' is the value
associated with the 'name' key, 20 is associated with 'age', 'A' with 'grade', and a list of courses
with 'courses'.
You can access the values in a dictionary using square brackets [] and specifying the key:
• Here, we access the 'name' and 'age' values from the student_info dictionary.
You can add new key-value pairs or modify existing ones in a dictionary:
• We add a new key 'city' with the value 'New York' to the dictionary, and we also modify the 'age'
value to 21.
You can iterate through the keys, values, or key-value pairs in a dictionary using loops:
• These loops demonstrate different ways to iterate through the dictionary's keys, values, and
key-value pairs
Output:
When you print the dictionary or run the code above, it will display the content of the dictionary in a
formatted manner.
A tuple is a built-in data type in Python used to store collections of items. Tuples are similar to lists in
that they can hold multiple elements, but they have a few key differences:
• An empty tuple named empty_tuple is created using parentheses (). Since tuples are immutable,
you can create an empty tuple or a tuple with one or more elements.
• A tuple named int_tuple containing integers is created. Tuples can hold elements of different
data types, including integers.
• A tuple named mixed_tuple is created with elements of different data types, including an
integer, a string, and a floating-point number.
• A nested tuple named nested_tuple is created. It contains elements of various data types,
including a string, a dictionary, and another tuple.
Tuples in Python have several important use cases due to their unique characteristics:
Tuples can store elements of different data types in an ordered sequence. This makes them useful for
representing records or data points with multiple attributes. For example, you can create a tuple to
represent a person's information:
Tuples are immutable, which means their elements cannot be modified after creation. This immutability
ensures that the data remains constant throughout the program.
3. Unpacking Values:
You can easily unpack the elements of a tuple into separate variables, which is especially useful when
you want to assign individual attributes to meaningful variable names:
Functions in Python can return multiple values as a tuple. This is a convenient way to return multiple
pieces of data from a function. For example, a function that calculates the area and perimeter of a
rectangle can return both values as a tuple:
5. Dictionary Keys:
Tuples are immutable and hashable, making them suitable as keys in dictionaries. Lists, being mutable,
cannot be used as dictionary keys. Tuples can be used as keys to represent, for example, coordinates in
a 2D grid:
6. Named Tuples:
Python provides the collections.namedtuple function that allows you to define a named tuple with
named fields. Named tuples improve code readability by giving meaningful names to elements. For
example:
from collections import namedtuple Person = namedtuple('Person', ['name', 'age', 'email']) person =
Person('Alice', 25, '[email protected]') print(person.name) # Accessing fields by name
print(person.age) print(person.email)
Regular expressions (regex or regexp) are a powerful tool for pattern matching and text manipulation in
Python and many other programming languages. They allow you to search for, match, and manipulate
strings based on specific patterns or rules.
import re
The re.search() function is used to search for a specified pattern within a string. It returns a match object
if a match is found or None if no match is found.
The re.findall() function is used to find all occurrences of a pattern in a string and returns them as a list.
4. Splitting a String:
You can use regular expressions to split a string into a list of substrings based on a specified pattern. The
re.split() function accomplishes this:
5. Replacing Text:
The re.sub() function allows you to replace occurrences of a pattern in a string with a specified
replacement text.
Regular expression patterns are a combination of characters and symbols that define the search criteria.
Common symbols include:
[]: Defines a character class. For example, [aeiou] matches any vowel.
In object-oriented programming (OOP), classes and objects are fundamental concepts. A class is a
blueprint or template for creating objects, and objects are instances of a class. Python is an object-
oriented programming language that makes it easy to work with classes and objects.
1. Defining a Class:
In Python, a class is defined using the class keyword. Let's define a simple class called Person to
represent individuals with attributes like name and age.
Practical theory
• The __init__ method is a special method (constructor) that gets called when an object of the
class is created. It initializes the object's attributes.
2. Creating Objects (Instances):
You can create objects (instances) of a class by calling the class constructor. Here, we create two
Person objects:
You can access an object's attributes using dot notation. For example, to access the name and age of
person1:
A class can also have methods (functions) that can perform operations related to the class. Let's add
a method to the Person class to greet the person:
You can modify the attributes of an object by reassigning new values to them. For example, to
change the age of person2:
6. Class Attributes:
Class attributes are shared by all instances of a class. They are defined outside of any methods.
Here's an example of a class attribute for the Person class:
• Key Concepts:
1. Superclass (Base Class):
A superclass, also known as a base class or parent class, is the existing class from which attributes and
methods are inherited.
A subclass, also known as a derived class or child class, is a new class created by inheriting attributes and
methods from a superclass.
3. Inheritance Relationship:
Practical theory
The inheritance relationship can be visualized as a hierarchy, where the subclass inherits characteristics
from the superclass.
The subclass can have additional attributes and methods, making it more specialized.
• Advantages of Inheritance:
▪ Code Reusability:
Inheritance allows you to reuse code from existing classes, reducing duplication and promoting efficient
coding.
▪ Modularity:
Inheritance promotes modular design by allowing you to create a hierarchy of related classes.
▪ Ease of Maintenance:
Changes made to a superclass automatically affect all its subclasses, making maintenance more
manageable.
▪ Polymorphism:
Inheritance supports polymorphism, where objects of different classes can be treated as objects of a
common superclass.
• Working of Inheritance:
1. Defining a Superclass:
Start by defining a superclass with attributes and methods that are common to multiple classes.
2. Creating a Subclass:
▪ Create one or more subclasses that inherit from the superclass.
▪ Subclasses use the class Subclass(Superclass) syntax to specify their inheritance.
4. Adding Specialization:
▪ Subclasses can add their own attributes and methods to specialize their behavior.
In Python, method overloading is accomplished by defining multiple methods with the same name
within a class, but each method has a different number or type of parameters. When you call a method
Practical theory
with specific arguments, Python automatically determines which method to invoke based on the
provided arguments. This process is known as "overloading by default."
Key Concepts:
You can define multiple methods with the same name in a class, but each method must have a different
number of parameters. This allows you to create methods with varying parameter counts to handle
different cases.
2. Python's Flexibility:
1) Python's dynamic typing and argument flexibility make it suitable for method overloading.
2) The Python interpreter selects the appropriate method to call based on the number and
type of arguments provided.
• How Method Overloading Works in Python:
1. Defining Methods with Different Parameters:
1) In a class, you can define multiple methods with the same name but different parameter
lists. These methods are considered overloaded methods.
2. Method Selection at Runtime:
1) When a method is called, Python determines which method to invoke based on the number
and types of arguments provided during the function call.
3. Automatic Dispatch:
1) Python performs automatic method dispatch by matching the provided arguments to the
parameter lists of the defined methods.
4. Handling Different Cases:
1) Each overloaded method can handle a specific case or set of input parameters, allowing you to
create more flexible and expressive class designs.
1. List Definition:
even_numbers = [2, 4, 6, 8]
In this line, a list named even_numbers is defined, containing four even integers.
print(even_numbers[5])
• This line attempts to access the element at index 5 in the even_numbers list, which is beyond
the valid index range.
• As a result, this operation raises an IndexError because the index is out of bounds for the list.
Practical theory
3. except Block (IndexError Handling):
• This block is an exception handler specifically designed to catch and handle IndexError
exceptions.
• When an IndexError occurs (as in the previous line), the Python interpreter jumps to this block
to execute the code within it.
• Python's exception handling mechanism allows you to gracefully manage errors and exceptional
situations that may occur during program execution.
• The try block is used to enclose the code that might raise an exception.
• The except block(s) are used to catch and handle specific types of exceptions.
• Multiple except blocks can be used to handle different types of exceptions.
• When an exception occurs, Python searches for the appropriate except block to execute based
on the exception type.
• If no matching except block is found, the program terminates with an error message.