Python Lab 60
Python Lab 60
Question no 1
Here’s a Python program demonstrating all these components:
"""
This is a multi-line comment.
Python ignores comments when executing the program.
"""
# For Loop
for hobby in hobbies:
print("Hobby:", hobby)
# While Loop
count = 0
while count < 3:
print("Count:", count)
count += 1
print(greet(name))
Python Lab 1
with open("example.txt", "w") as file:
file.write("Hello, this is a sample file!")
Sure! Let's go through each concept one by one with practical examples.
Documentation
Python documentation is essential for making your code understandable. You can use docstrings to provide information about your
functions, classes, and modules.
Parameters:
a (int or float): The first number.
b (int or float): The second number.
Returns:
int or float: The sum of the two numbers.
"""
return a + b
# Example usage:
print(add(2, 3))
Indentation
Indentation is crucial in Python, as it defines the blocks of code. Proper indentation ensures that the code runs correctly.
def check_even_odd(number):
if number % 2 == 0:
print(f"{number} is even.")
else:
print(f"{number} is odd.")
# Example usage:
check_even_odd(4)
check_even_odd(7)
Type Conversion
Type conversion in Python allows you to convert one data type to another. Common conversions include converting strings to
integers, floats to integers, etc.
Python Lab 2
float_value = float(int_value)
print(f"Integer converted to float: {float_value}")
Input/Output
Input and output are fundamental for interacting with users. You can use input() to take user input and print() to display output.
# Displaying output
print(f"Hello, {name}! You are {age} years old.")
Feel free to try these examples in your Python environment and let me know if you have any questions!
Sure! Here's a chart summarizing the operator precedence and associativity of operators in Python:
1 () Parentheses Left-to-Right
2 ** Exponentiation Right-to-Left
9 ` ` Bitwise OR
13 or Boolean OR Left-to-Right
Example Usage
Let's see some examples that illustrate operator precedence and associativity:
Python Lab 3
Feel free to experiment with these operators and their precedence in your Python programs. If you have any questions, just let me
know!
1. if statement
2. if-else statement
3. if-elif-else statement
1. if statement
The if statement evaluates a condition, and if the condition is True , it executes the block of code inside it.
Syntax:
if condition:
# block of code
Example:
age = 18
if age >= 18:
print("You are an adult.")
2. if-else statement
The if-else statement evaluates a condition, and if the condition is True , it executes the block of code inside the if statement. If the
condition is False , it executes the block of code inside the else statement.
Syntax:
if condition:
# block of code for true condition
else:
# block of code for false condition
Example:
age = 17
if age >= 18:
print("You are an adult.")
else:
print("You are a minor.")
3. if-elif-else statement
The if-elif-else statement evaluates multiple conditions. The first if condition is checked, and if it's True , the corresponding block of
code is executed. If the condition is False , the next elif condition is checked. If none of the conditions are True , the else block is
executed.
Syntax:
if condition1:
# block of code for condition1
elif condition2:
# block of code for condition2
Python Lab 4
elif condition3:
# block of code for condition3
else:
# block of code for none of the conditions
Example:
score = 85
By using these decision-making statements, you can control the flow of your Python programs based on different conditions. If you
have any further questions or need more examples, feel free to ask!
Q5 :- Define looping in python. Write program for while loop , for loop ( String ,tuple & list ).
Looping in Python
Looping in Python is a way to execute a block of code repeatedly until a certain condition is met. Python provides two main types of
loops: while loop and for loop.
1. While Loop
A while loop executes a block of code as long as a condition is True.
2. For Loop
A for loop is used to iterate over a sequence (like string, tuple, list) or other iterable objects.
Python Lab 5
sum = 0
for num in numbers:
sum += num
print(f"Sum of numbers: {sum}")
These examples demonstrate different ways to use loops in Python. The while loop is typically used when you don't know the exact
number of iterations beforehand, while the for loop is perfect for iterating over sequences with a known length.
Example:
# Defining strings
string1 = 'Hello'
string2 = "Python"
string3 = '''This is a multi-line string.'''
Python Lab 6
text = "I love Java"
print(text.replace("Java", "Python")) # Output: I love Python
text = "apple,banana,cherry"
print(text.split(",")) # Output: ['apple', 'banana', 'cherry']
isalnum() – Returns True if all characters are alphanumeric (letters and numbers).
Example:
Python Lab 7
text1 = "Hello"
text2 = "12345"
text3 = "Python123"
print(text1.isalpha()) # True
print(text2.isdigit()) # True
print(text3.isalnum()) # True
num = "5"
print(num.zfill(3)) # Output: 005
Complete Example
Functions in Python
A function is a block of reusable code that performs a specific task. Functions help in making code modular, readable, and efficient.
2. User-defined Functions – Functions created by the programmer using the def keyword.
Python Lab 8
(i) Recursion
A recursive function is one that calls itself. Here's an example of a recursive function to calculate the factorial of a number:
def factorial(n):
if n == 0:
return 1
else:
return n * factorial(n - 1)
These examples should give you a good starting point for understanding different types of functions in Python. Let me know if you
have any questions or if there's anything else you'd like to explore!
Let's break it down into three steps: creating a module, importing a module, and reloading a module.
Creating a Module
A module is a file containing Python definitions and statements. You can create a module by writing your Python code in a .py file.
For example, create a file named mymodule.py with the following content:
# mymodule.py
def greet(name):
return f"Hello, {name}!"
Importing a Module
You can import the mymodule module into another Python script or the interactive shell using the import statement. Here's how you can
do it:
# main.py
Python Lab 9
import mymodule
Reloading a Module
If you modify the module and want to reload it without restarting your Python interpreter, you can use the importlib.reload() function.
Here's how:
import importlib
import mymodule
These steps should help you create, import, and reload module packages in Python. If you have any questions or need further
assistance, feel free to ask!
Q9 :- Exceptions in python. List all built in exceptions use in python. Write program of
(i) pre define exceptions (ii) user define exception
Exceptions in Python
Exceptions in Python are events that occur during the execution of a program and disrupt its normal flow. When an error occurs,
Python creates an exception object, which represents the error. If the exception is not handled, it will terminate the program. Let's
start with a list of built-in exceptions in Python.
Built-in Exceptions
Here are some common built-in exceptions in Python:
Exception
ArithmeticError
BufferError
LookupError
AssertionError
AttributeError
EOFError
FloatingPointError
GeneratorExit
ImportError
ModuleNotFoundError
IndexError
Python Lab 10
KeyError
KeyboardInterrupt
MemoryError
NameError
NotImplementedError
OSError
OverflowError
RecursionError
ReferenceError
RuntimeError
StopIteration
StopAsyncIteration
SyntaxError
IndentationError
TabError
SystemError
SystemExit
TypeError
UnboundLocalError
UnicodeError
UnicodeEncodeError
UnicodeDecodeError
UnicodeTranslateError
ValueError
ZeroDivisionError
OR
Arithmetic Errors:
Import Errors:
ValueError : Raised when a function receives an argument of the correct type but inappropriate value.
Python Lab 11
(i) Predefined Exceptions
Here's an example program that demonstrates how to handle a predefined exception, specifically the ZeroDivisionError :
try:
result = 10 / 0
except ZeroDivisionError:
print("You can't divide by zero!")
else:
print("Division successful:", result)
finally:
print("This will always be executed.")
# Output:
# You can't divide by zero!
# This will always be executed.
class CustomError(Exception):
pass
def check_positive_number(number):
if number <= 0:
raise CustomError("The number must be positive!")
try:
check_positive_number(-5)
except CustomError as e:
print(e)
# Output:
# The number must be positive!
In this example, we define a custom exception CustomError and raise it when the provided number is not positive. The try block
attempts to call check_positive_number(-5) , and when the custom exception is raised, the except block catches it and prints the error
message.
I hope this helps! If you have any questions or need further clarification, feel free to ask.
File management in Python involves various operations such as creating, reading, writing, and deleting files
Let's explore file management in Python and write programs for both opening a file and opening a folder.
Python Lab 12
# Close the file
file.close()
Alternatively, you can use the with statement to automatically handle closing the file:
import os
In this example, replace 'path/to/your/folder' with the actual path to the folder you want to open. The os.listdir() function returns a list of all
files and directories in the specified folder, which are then printed.
These examples should help you get started with file management in Python. If you have any questions or need further assistance,
feel free to ask!
Q 11:- Creating & destroying object in python and accessing & editing attributes in python
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
In the example above, we define a Person class with an __init__ method (constructor) that initializes the name and age attributes. We
then create an instance of the Person class ( person1 ) with the name "Alice" and age 30.
Destroying Objects
Python uses automatic garbage collection to manage memory, so you don't need to manually destroy objects. However, you can use
the del statement to delete a reference to an object, which may help with memory management:
del person1
After calling del , the person1 reference is removed, and if there are no other references to the object, it will be garbage collected.
Python Lab 13
# Define a class with some attributes
class Car:
def __init__(self, make, model, year):
self.make = make
self.model = model
self.year = year
In this example, we define a Car class with make , model , and year attributes. We create an instance of the Car class ( car1 ) and access
its attributes using dot notation. We then edit the year attribute of the car1 object.
I hope this gives you a clear understanding of creating, destroying, accessing, and editing attributes in Python. If you have any more
questions or need further assistance, feel free to ask!
Python Lab 14