Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
3 views

Python Lab 60

The document is a comprehensive Python lab guide covering various programming concepts including comments, variables, data types, operators, control flow, functions, modules, file handling, and decision-making. It also includes examples of looping, string manipulation, operator precedence, and the definition of functions, along with practical code snippets for each topic. Additionally, it explains recursion, predefined functions, and user-defined functions, providing a thorough overview for learners.

Uploaded by

study018969
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

Python Lab 60

The document is a comprehensive Python lab guide covering various programming concepts including comments, variables, data types, operators, control flow, functions, modules, file handling, and decision-making. It also includes examples of looping, string manipulation, operator precedence, and the definition of functions, along with practical code snippets for each topic. Additionally, it explains recursion, predefined functions, and user-defined functions, providing a thorough overview for learners.

Uploaded by

study018969
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 14

Python Lab

Question no 1
Here’s a Python program demonstrating all these components:

# 1. Comments – Used for explanations


# This is a single-line comment

"""
This is a multi-line comment.
Python ignores comments when executing the program.
"""

# 2. Variables – Store values


x = 10 # Integer
name = "Alice" # String

# 3. Data Types – Different types of data


age = 25 # Integer
height = 5.7 # Float
is_student = True # Boolean
hobbies = ["Reading", "Cycling", "Gaming"] # List
person = {"name": "Alice", "age": 25, "city": "New York"} # Dictionary

# 4. Operators – Arithmetic, Comparison, Logical Operators


a=5
b=3

sum_result = a + b # Arithmetic: Addition


is_equal = a == b # Comparison: False
logical_check = (a > 2 and b < 5) # Logical: True

# 5. Control Flow – If-else and loops


if age >= 18:
print("You are an adult.")
else:
print("You are a minor.")

# For Loop
for hobby in hobbies:
print("Hobby:", hobby)

# While Loop
count = 0
while count < 3:
print("Count:", count)
count += 1

# 6. Functions – Blocks of reusable code


def greet(user_name):
return f"Hello, {user_name}!"

print(greet(name))

# 7. Modules & Libraries – Import external code


import math
print("Square root of 16:", math.sqrt(16))

# 8. File Handling – Read and write files


# Writing to a file

Python Lab 1
with open("example.txt", "w") as file:
file.write("Hello, this is a sample file!")

# Reading from a file


with open("example.txt", "r") as file:
content = file.read()
print("File Content:", content)

Question 2 Show the use of documentation , indentation ,type conversion and


input/output of python programming.

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.

def add(a, b):


"""
This function takes two numbers and returns their sum.

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.

# Converting string to integer


str_num = "123"
int_num = int(str_num)
print(f"String converted to integer: {int_num}")

# Converting integer to float


int_value = 10

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.

# Taking user input


name = input("Enter your name: ")
age = int(input("Enter your age: "))

# 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!

Q3 :- Make a chart for operator precedence and associativity of operators in python.

Sure! Here's a chart summarizing the operator precedence and associativity of operators in Python:

Operator Precedence and Associativity in Python


Precedence Level Operator Description Associativity

1 () Parentheses Left-to-Right

2 ** Exponentiation Right-to-Left

3 +, - Unary plus, Unary minus Right-to-Left

4 * , / , // , % Multiplication, Division, Floor division, Modulus Left-to-Right

5 +, - Addition, Subtraction Left-to-Right

6 << , >> Bitwise shift operators Left-to-Right

7 & Bitwise AND Left-to-Right

8 ^ Bitwise XOR Left-to-Right

9 ` ` Bitwise OR

10 == , != , > , < , >= , <= , is , is not , in , not in Comparison operators Left-to-Right

11 not Boolean NOT Right-to-Left

12 and Boolean AND Left-to-Right

13 or Boolean OR Left-to-Right

14 if else Ternary conditional Right-to-Left

15 lambda Lambda expression Right-to-Left

Example Usage
Let's see some examples that illustrate operator precedence and associativity:

Example 1: Exponentiation ( * ) and Multiplication ( )

result = 2 ** 3 * 4 # Exponentiation has higher precedence


print(result) # Output: 32

Example 2: Unary Minus ( ) and Multiplication ( )

result = -3 * 5 # Unary minus has higher precedence


print(result) # Output: -15

Example 3: Bitwise AND ( & ) and Bitwise OR ( | )

result = 5 | 3 & 2 # Bitwise AND has higher precedence


print(result) # Output: 7

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!

Q4 :- Define decision making . write types with syntax.

Decision Making in Python


Decision making in Python refers to the process of executing certain parts of the code based on specific conditions. It's an essential
aspect of programming that allows you to control the flow of your program.

Types of Decision Making Statements


There are three main types of decision-making statements in Python:

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

if score >= 90:


grade = "A"
elif score >= 80:
grade = "B"
elif score >= 70:
grade = "C"
else:
grade = "D"

print(f"Your grade is {grade}.")

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.

# Example of while loop


# Print numbers from 1 to 5
count = 1
while count <= 5:
print(count)
count += 1

2. For Loop
A for loop is used to iterate over a sequence (like string, tuple, list) or other iterable objects.

Example with String:

# Iterating through a string


message = "Python"
for char in message:
print(char)

Example with Tuple:

# Iterating through a tuple


fruits = ("apple", "banana", "orange")
for fruit in fruits:
print(f"I like {fruit}")

Example with List:

# Iterating through a list


numbers = [1, 2, 3, 4, 5]

Python Lab 5
sum = 0
for num in numbers:
sum += num
print(f"Sum of numbers: {sum}")

# Using range() with for loop


for i in range(3):
print(f"Iteration {i + 1}")

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.

Q6 :- Define string and it’s pre-defined function’s in python with code.

What is a String in Python?


A string in Python is a sequence of characters enclosed in single ( ' ), double ( " ) or triple ( ''' """ ) quotes. Strings are immutable,
meaning they cannot be changed after creation.

Example:

# Defining strings
string1 = 'Hello'
string2 = "Python"
string3 = '''This is a multi-line string.'''

Predefined String Functions in Python


Python provides many built-in string functions to manipulate and process strings efficiently.

1. len() – Get String Length


Returns the number of characters in a string.

text = "Python Programming"


print(len(text)) # Output: 18

2. lower() – Convert to Lowercase


Converts all characters to lowercase.

text = "HELLO WORLD"


print(text.lower()) # Output: hello world

3. upper() – Convert to Uppercase


Converts all characters to uppercase.

text = "hello world"


print(text.upper()) # Output: HELLO WORLD

4. strip() – Remove Whitespaces


Removes leading and trailing spaces.

text = " Python "


print(text.strip()) # Output: Python

5. replace() – Replace Substring


Replaces a specified substring with another.

Python Lab 6
text = "I love Java"
print(text.replace("Java", "Python")) # Output: I love Python

6. split() – Split String into List


Splits a string into a list of words.

text = "apple,banana,cherry"
print(text.split(",")) # Output: ['apple', 'banana', 'cherry']

7. join() – Join List into String


Joins elements of a list into a string.

words = ["Python", "is", "fun"]


print(" ".join(words)) # Output: Python is fun

8. find() – Find Substring Index


Finds the index of the first occurrence of a substring.

text = "Python is great"


print(text.find("is")) # Output: 7

9. count() – Count Occurrences of Substring


Counts occurrences of a substring in a string.

text = "apple apple banana"


print(text.count("apple")) # Output: 2

10. startswith() & endswith() – Check Start/End


Checks if a string starts or ends with a specific substring.

text = "Hello Python"


print(text.startswith("Hello")) # Output: True
print(text.endswith("Java")) # Output: False

11. capitalize() – Capitalize First Letter


Capitalizes the first character.

text = "python programming"


print(text.capitalize()) # Output: Python programming

12. title() – Convert to Title Case


Converts the first letter of each word to uppercase.

text = "hello world"


print(text.title()) # Output: Hello World

13. isalpha() , isdigit() , isalnum() – Check Type


isalpha() – Returns True if all characters are letters.

isdigit() – Returns True if all characters are digits.

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

14. swapcase() – Swap Case


Converts uppercase to lowercase and vice versa.

text = "Python IS Fun"


print(text.swapcase()) # Output: pYTHON is fUN

15. zfill() – Zero Padding


Adds leading zeros to a string.

num = "5"
print(num.zfill(3)) # Output: 005

Complete Example

text = " Hello Python! "

print(len(text)) # 1. Length of string


print(text.lower()) # 2. Convert to lowercase
print(text.upper()) # 3. Convert to uppercase
print(text.strip()) # 4. Remove whitespace
print(text.replace("Python", "World")) # 5. Replace substring
print(text.split()) # 6. Split string into list
print("-".join(["A", "B", "C"])) # 7. Join list into string
print(text.find("Python")) # 8. Find substring
print(text.count("o")) # 9. Count occurrences
print(text.startswith("Hello")) # 10. Check start
print(text.endswith("!")) # 11. Check end
print(text.capitalize()) # 12. Capitalize first letter
print(text.title()) # 13. Title case
print("12345".isdigit()) # 14. Check if digits
print("Python123".isalnum()) # 15. Check alphanumeric
print(text.swapcase()) # 16. Swap case
print("7".zfill(3)) # 17. Zero padding

Would you like explanations on any specific function? 🚀


Q7:- Define functions in python. Write program of
(i) Recursion
(ii) Pre defined functions
(iii) User defined functions

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.

Types of Functions in Python:


1. Predefined (Built-in) Functions – Functions already available in Python, like print() , len() , sum() , etc.

2. User-defined Functions – Functions created by the programmer using the def keyword.

3. Recursive Functions – Functions that call themselves to solve problems.

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)

# Test the recursive function


print(factorial(5)) # Output: 120

(ii) Predefined Functions


Python has many built-in functions (predefined functions) that you can use. Here's an example using the len() function to find the
length of a string:

# Using the predefined function len()


my_string = "Hello, World!"
length = len(my_string)

print("The length of the string is:", length) # Output: 13

(iii) User Defined Functions


A user-defined function is a function that you define yourself using the def keyword. Here's an example of a user-defined function to
add two numbers:

def add_numbers(a, b):


return a + b

# Test the user-defined function


sum_result = add_numbers(3, 7)

print("The sum is:", sum_result) # Output: 10

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!

Q8 :- Creating ,importing and reloading module packages in python.

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}!"

def add(a, b):


return a + b

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

# Use the functions from mymodule


print(mymodule.greet("Alice")) # Output: Hello, Alice!
print(mymodule.add(5, 3)) # Output: 8

You can also import specific functions from the module:

from mymodule import greet, add

print(greet("Bob")) # Output: Hello, Bob!


print(add(2, 4)) # Output: 6

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

# Use the module


print(mymodule.greet("Charlie")) # Output: Hello, Charlie!

# Modify the mymodule.py file here...

# Reload the module


importlib.reload(mymodule)

# Use the updated module


print(mymodule.greet("David")) # Output will depend on the updated code in mymodule.py

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:

ArithmeticError : Base class for arithmetic errors.

ZeroDivisionError : Raised when division or modulo by zero occurs.

OverflowError : Raised when a numerical operation exceeds the maximum limit.

Attribute and Name Errors:

AttributeError : Raised when an invalid attribute reference is made.

NameError : Raised when a local or global name is not found.

Index and Key Errors:

IndexError : Raised when a sequence subscript is out of range.

KeyError : Raised when a dictionary key is not found.

Import Errors:

ImportError : Raised when an import statement fails.

ModuleNotFoundError : Raised when a module cannot be located.

Type and Value Errors:

TypeError : Raised when an operation is applied to an object of inappropriate type.

ValueError : Raised when a function receives an argument of the correct type but inappropriate value.

File and OS Errors:

FileNotFoundError : Raised when a file or directory is requested but doesn't exist.

PermissionError : Raised when trying to perform an operation without adequate permissions.

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.

(ii) User-defined Exception


You can create your own exceptions by inheriting from the built-in Exception class. Here's an example of a user-defined exception:

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.

Q10 :- File management in python. Write program in python for


(i) Open a file (ii) Open a folder

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.

(i) Open a File


To open a file in Python, you can use the built-in open() function. Here's an example that demonstrates how to open a file, read its
contents, and close it:

# Open the file in read mode


file = open('example.txt', 'r')

# Read the contents of the file


content = file.read()

# Print the content


print(content)

Python Lab 12
# Close the file
file.close()

Alternatively, you can use the with statement to automatically handle closing the file:

# Using the with statement to open and read the file


with open('example.txt', 'r') as file:
content = file.read()
print(content)

(ii) Open a Folder


To open a folder and list its contents, you can use the os module. Here's an example that demonstrates how to open a folder and list
all files and directories within it:

import os

# Define the path to the folder


folder_path = 'path/to/your/folder'

# List the contents of the folder


contents = os.listdir(folder_path)

# Print the contents


for item in contents:
print(item)

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

Creating and Destroying Objects in Python


In Python, objects are created by instantiating classes. Here's an example of creating an object:

class Person:
def __init__(self, name, age):
self.name = name
self.age = age

# Create an instance of the Person class


person1 = Person("Alice", 30)

print(person1.name) # Output: Alice


print(person1.age) # Output: 30

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.

Accessing and Editing Attributes


You can access and edit the attributes of an object using dot notation. Here's an example:

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

# Create an instance of the Car class


car1 = Car("Toyota", "Camry", 2020)

# Access the attributes


print(car1.make) # Output: Toyota
print(car1.model) # Output: Camry
print(car1.year) # Output: 2020

# Edit the attributes


car1.year = 2022

print(car1.year) # Output: 2022

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

You might also like