0% found this document useful (0 votes)
3 views

Python Program With Explanation

The document provides various examples of Python programming concepts, including defining classes with constructors, calculating factorials, working with tuples, and using Pandas Series for arithmetic operations. It also includes user interaction for inputting student information and reading from text files with error handling. Each example is explained in detail, outlining the execution flow and expected outputs.

Uploaded by

Gulam Ansari
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

Python Program With Explanation

The document provides various examples of Python programming concepts, including defining classes with constructors, calculating factorials, working with tuples, and using Pandas Series for arithmetic operations. It also includes user interaction for inputting student information and reading from text files with error handling. Each example is explained in detail, outlining the execution flow and expected outputs.

Uploaded by

Gulam Ansari
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 13

1. Defining instance variables using a constructor.

class Person:
# Constructor (__init__) to initialize instance variables
def __init__(self, name, age):
self.name = name # instance variable 'name'
self.age = age # instance variable 'age'

def introduce(self):
print(f"Hi, I'm {self.name} and I'm {self.age} years old.")

# Creating an instance of Person


person1 = Person("Alice", 30)

# Accessing instance variables


print(person1.name) # Output: Alice
print(person1.age) # Output: 30

# Calling the method


person1.introduce() # Output: Hi, I'm Alice and I'm 30 years old.

Your code looks great! It's a solid example of using a constructor to initialize instance
variables and calling methods on an instance in Python. Here's a breakdown of what you've
done:

1. Class Definition (Person):


o You defined a Person class with an __init__ method to initialize the instance
variables name and age.
o The introduce method prints a message introducing the person with their
name and age.
2. Creating an Object (person1):
o When you created an instance of Person using person1 = Person("Alice",
30), the __init__ constructor automatically initialized the name and age for
person1.
3. Accessing Instance Variables:
o You accessed person1.name and person1.age to print the values of the
instance variables.
4. Calling a Method (introduce):
o The introduce method was called with person1.introduce(), and it
successfully printed the introduction message.

This is exactly how you'd define and use constructors and instance variables in Python.
Everything works as expected.

Execution Flow:

1. Class Definition (Person):


o Python reads and processes the class definition. However, it does not execute
any code inside the class just yet; it only "knows" the structure of the class
(i.e., it knows there is an __init__ method and an introduce method).
2. Creating an Object (person1 = Person("Alice", 30)):
o When you create an instance of the Person class (person1 =
Person("Alice", 30)), Python does the following:
 First, Python calls the __init__ constructor method with the
arguments name="Alice" and age=30.
 Inside the __init__ method:
 self.name = name assigns the value "Alice" to the name
instance variable for this object (person1).
 self.age = age assigns the value 30 to the age instance
variable for this object (person1).
 The constructor completes execution and returns None (this is implicit
in Python constructors).

At this point, the object person1 has been created with the following instance
variables:

o person1.name = "Alice"
o person1.age = 30
3. Accessing Instance Variables (print(person1.name) and print(person1.age)):
o The print(person1.name) statement prints the value of the name instance
variable of person1, which is "Alice".
o The print(person1.age) statement prints the value of the age instance
variable of person1, which is 30.
4. Calling the Method (person1.introduce()):
o The statement person1.introduce() calls the introduce method of the
person1 object.
o Inside the introduce method:
 The method accesses the name and age instance variables of person1
(i.e., self.name and self.age), which have been set earlier to
"Alice" and 30, respectively.
 The method then prints the formatted string: "Hi, I'm Alice and
I'm 30 years old."

In Summary:

 Object Creation: person1 = Person("Alice", 30) triggers the execution of the


__init__ constructor, initializing name to "Alice" and age to 30.
 Instance Variable Access: The print(person1.name) and print(person1.age)
statements access and print the name and age of person1.
 Method Call: The person1.introduce() statement calls the introduce method,
which prints an introduction message using the instance variables name and age.

2. Write a Python function to calculate the factorial of a number (a non-negative


integer). The function accepts the number as an argument.
def factorial(n):
if n < 0:
return "Factorial is not defined for negative numbers"
result = 1
for i in range(1, n + 1):
result *= i
return result

# Example usage:
number = 5
print(f"Factorial of {number} is {factorial(number)}")

Execution Flow:

1. Function Definition (def factorial(n):):


o The factorial function is defined, but Python doesn't execute it yet. It only
knows how the function works, i.e., it takes an argument n, checks if n is
negative, and if not, calculates the factorial of n using a loop.
2. Function Call (factorial(5)):
o The line factorial(5) calls the factorial function with the argument n =
5.

Inside the function:

o First Step: Check if n is negative:

python
Copy
if n < 0:
return "Factorial is not defined for negative numbers"
 Since n = 5, which is not negative, this condition is not met, and
Python proceeds to the next step.
o Second Step: Initialize result to 1:

python
Copy
result = 1

 resultis initialized to 1. This will hold the cumulative product as we


calculate the factorial.
o Third Step: Loop for calculating the factorial:

python
Copy
for i in range(1, n + 1):
result *= i

 The for loop will iterate over the values from 1 to n (i.e., from 1 to 5,
inclusive). This is achieved using range(1, n + 1), where n = 5.
 Let's walk through the loop iteration by iteration:
 First iteration (i = 1):
 result *= i becomes result = 1 * 1 = 1
 Second iteration (i = 2):
 result *= i becomes result = 1 * 2 = 2
 Third iteration (i = 3):
 result *= i becomes result = 2 * 3 = 6
 Fourth iteration (i = 4):
 result *= i becomes result = 6 * 4 = 24
 Fifth iteration (i = 5):
 result *= i becomes result = 24 * 5 = 120
o After the loop finishes, result holds the value 120, which is the factorial of 5.
3. Return the result:
o The line return result is executed, returning the value 120 to the calling
code (i.e., factorial(5)).
4. Printing the result (print(f"Factorial of {number} is
{factorial(number)}")):
o The factorial(number) call returns 120, so the print statement outputs:

csharp
Copy
Factorial of 5 is 120

Summary of the Execution:

1. You call the function factorial(5).


2. The function checks if n is negative, which it's not, so it proceeds.
3. It initializes result = 1 and then starts a loop to multiply result by each number
from 1 to n (5 in this case).
4. After completing the loop, result holds 120, which is the factorial of 5.
5. Finally, the factorial function returns 120, and this value is printed as Factorial
of 5 is 120.
Additional Notes:

 If n were negative, the function would return the message "Factorial is not
defined for negative numbers" instead of calculating anything.

3. Write a python program to create a tuple and to find greatest and smallest element
form the tuple.
my_tuple = (10, 20, 4, 45, 99, 2)

# Find the greatest and smallest element


greatest = max(my_tuple)
smallest = min(my_tuple)

# Print the results


print(f"The greatest element in the tuple is: {greatest}")
print(f"The smallest element in the tuple is: {smallest}")

4. Implement a class Student with information as rollno , class ,name. The information
must be entered by the user.
class Student:
def __init__(self):
# Initialize attributes
self.rollno = None
self.student_class = None
self.name = None

def input_student_info(self):
# Input details from user
self.rollno = input("Enter roll number: ")
self.student_class = input("Enter class: ")
self.name = input("Enter name: ")

def display_student_info(self):
# Display the entered student details
print(f"Roll Number: {self.rollno}")
print(f"Class: {self.student_class}")
print(f"Name: {self.name}")

# Example usage
student = Student()
student.input_student_info() # User inputs the student information
student.display_student_info() # Displays the entered information

Execution Flow:

1. Class Definition (Student):


o The Student class is defined with three attributes (rollno, student_class, and
name) and two methods (input_student_info and display_student_info).
o Inside the __init__ constructor, the instance variables self.rollno,
self.student_class, and self.name are initialized to None. This means when a
Student object is created, these attributes will initially have no values.
2. Creating an Object (student = Student()):
o The statement student = Student() creates an instance of the Student class.
This calls the __init__ constructor.
 Inside the constructor:
 self.rollno = None assigns None to the rollno attribute.
 self.student_class = None assigns None to the
student_class attribute.
 self.name = None assigns None to the name attribute.
3. Calling input_student_info() Method:
o The statement student.input_student_info() calls the
input_student_info method for the student object.
o Inside the input_student_info method:
 The method uses the input() function to prompt the user for each piece of
information:
 self.rollno = input("Enter roll number: ") asks the
user to input the roll number. The user's input is stored in
self.rollno.
 self.student_class = input("Enter class: ") asks the
user to input the class. The user's input is stored in
self.student_class.
 self.name = input("Enter name: ") asks the user to input
the name. The user's input is stored in self.name.

After the user inputs all the details (roll number, class, and name), the
input_student_info method finishes and control returns to the main program.

4. Calling display_student_info() Method:


o The statement student.display_student_info() calls the
display_student_info method for the student object.
o Inside the display_student_info method:
 The method prints the details of the student object:
 print(f"Roll Number: {self.rollno}") prints the roll
number stored in self.rollno.
 print(f"Class: {self.student_class}") prints the class
stored in self.student_class.
 print(f"Name: {self.name}") prints the name stored in
self.name.

This results in displaying the student's details as entered by the user.

Example Execution:

Let's go through an example where the user inputs the following details:

 Roll Number: 101


 Class: 10
 Name: Alice

Step-by-step example:

1. Creating the Student object:


o The code creates an instance of the Student class: student = Student().
o This calls the __init__ method, initializing rollno, student_class, and name to
None.
2. Inputting student information:
o The user is prompted to enter information via input_student_info():
 Enter roll number: 101 (User enters 101).
 Enter class: 10 (User enters 10).
 Enter name: Alice (User enters Alice).

After these inputs, the student object's attributes are now:

o rollno = "101"
o student_class = "10"
o name = "Alice"
3. Displaying student information:
o The display_student_info() method is called.
o The method prints:
yaml
Copy
Roll Number: 101
Class: 10
Name: Alice

Summary of Execution:

1. The class Student is defined with the __init__, input_student_info, and


display_student_info methods.
2. An object student is created, initializing its attributes to None.
3. The input_student_info() method is called, and the user inputs the roll number, class,
and name.
4. The display_student_info() method is called, which displays the entered student
information.

The program interacts with the user to gather information and then outputs that information in a
formatted way. This is an example of encapsulating the details of a student (like roll number, class,
and name) inside a class and using methods to input and display those details.

5. Write a Python program to ADD, SUBSTRACT, MULTIPLY, AND DIVIDE two


Pandas Series

import pandas as pd

# Create two Pandas Series


series1 = pd.Series([10, 20, 30, 40])
series2 = pd.Series([1, 2, 3, 4])

# Add the two Series


addition_result = series1 + series2
print("Addition result:\n", addition_result)

# Subtract the second Series from the first


subtraction_result = series1 - series2
print("\nSubtraction result:\n", subtraction_result)
# Multiply the two Series
multiplication_result = series1 * series2
print("\nMultiplication result:\n", multiplication_result)

# Divide the first Series by the second


# We should handle division by zero, if any
division_result = series1 / series2
print("\nDivision result:\n", division_result)

output
Addition result:
0 11
1 22
2 33
3 44
dtype: int64

Subtraction result:
0 9
1 18
2 27
3 36
dtype: int64

Multiplication result:
0 10
1 40
2 90
3 160
dtype: int64
Division result:
0 10.0
1 10.0
2 10.0
3 10.0
dtype: float64

6. Write a python program to read an entire text file.


file_name = input("Enter the file name (with extension): ")

try:
with open(file_name, 'r') as file:
# Read the entire content of the file
content = file.read()

# Display the content of the file


print("File Content:\n")
print(content)

except FileNotFoundError:
print(f"The file '{file_name}' was not found.")
except Exception as e:
print(f"An error occurred: {e}")

explanation:

1. input(): Prompts the user to enter the name of the file.


2. open(file_name, 'r'): Opens the file in read mode.
3. file.read(): Reads the entire content of the file.
4. Exception handling:
o If the file isn't found, it raises a FileNotFoundError.
o Any other errors are caught by the generic Exception handler.

Notes:

 Ensure that the file is in the correct directory or provide the full path to the file when
prompted.
 You can also add additional error handling to check if the file is empty or handle other
edge cases as needed.

output
Enter the file name (with extension): program1.py(any file name you can take)

File Content:

# -*- coding: utf-8 -*-

"""

Created on Wed Apr 2 10:37:58 2025

@author: Admin-PC

"""

class Person:

# Constructor (__init__) to initialize instance variables

def __init__(self, name, age):

self.name = name # instance variable 'name'

self.age = age # instance variable 'age'

def introduce(self):

print(f"Hi, I'm {self.name} and I'm {self.age} years old.")

# Creating an instance of Person

person1 = Person("Alice", 30)


# Accessing instance variables

print(person1.name) # Output: Alice

print(person1.age) # Output: 30

# Calling the method

person1.introduce() # Output: Hi, I'm Alice and I'm 30 years old.

7. Write a program to perform different Arithmetic Operations on numbers in Python.


# Input two numbers from the user

num1 = float(input("Enter the first number: "))

num2 = float(input("Enter the second number: "))

# Perform arithmetic operations

addition = num1 + num2

subtraction = num1 - num2

multiplication = num1 * num2

division = None

if num2 != 0: # Avoid division by zero

division = num1 / num2

else:

division = "undefined (cannot divide by zero)"

# Display the results

print(f"\nResults:")

print(f"Addition: {num1} + {num2} = {addition}")

print(f"Subtraction: {num1} - {num2} = {subtraction}")

print(f"Multiplication: {num1} * {num2} = {multiplication}")

print(f"Division: {num1} / {num2} = {division}")

Explanation:

Input: The program prompts the user to enter two numbers.


Arithmetic Operations: It performs addition, subtraction, multiplication, and division on these two
numbers.

Division Check: If the second number is 0, it handles the division operation to avoid division by zero
and prints "undefined".

You might also like