Python Program With Explanation
Python Program With Explanation
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.")
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:
This is exactly how you'd define and use constructors and instance variables in Python.
Everything works as expected.
Execution Flow:
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:
# Example usage:
number = 5
print(f"Factorial of {number} is {factorial(number)}")
Execution Flow:
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
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
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)
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:
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.
Example Execution:
Let's go through an example where the user inputs the following details:
Step-by-step example:
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:
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.
import pandas as pd
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
try:
with open(file_name, 'r') as file:
# Read the entire content of the file
content = file.read()
except FileNotFoundError:
print(f"The file '{file_name}' was not found.")
except Exception as e:
print(f"An error occurred: {e}")
explanation:
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:
"""
@author: Admin-PC
"""
class Person:
def introduce(self):
print(person1.age) # Output: 30
division = None
else:
print(f"\nResults:")
Explanation:
Division Check: If the second number is 0, it handles the division operation to avoid division by zero
and prints "undefined".