python 8m-1-31
python 8m-1-31
Below is a Python program that demonstrates the basic data types in Python, including integers,
floats, strings, booleans, lists, tuples, sets, and dictionaries.
# Demonstrating Basic Data Types in Python
# Integer
integer_value = 10
print("Integer:", integer_value)
# Float
float_value = 20.5
print("Float:", float_value)
# String
string_value = "Hello, Python!"
print("String:", string_value)
# Boolean
boolean_value = True
print("Boolean:", boolean_value)
# List
list_value = [1, 2, 3, "Python", True]
print("List:", list_value)
# Dictionary
dict_value = {"name": "Alice", "age": 25}
print("Dictionary:", dict_value)
b.Explain function definition and function call with examples
Function Definition: This is where the function is created. It specifies the name, parameters (if
any), and the block of code that the function will execute when called.
Some Benefits of Using Functions
Increase Code Readability
Increase Code Reusability
Complete Example:
Key Points
Both operators only check for keys, not values.
They are efficient and provide a straightforward way to verify key existence.
These operators can be used in conditional statements to control the flow of the program based
on key presence.
b) Differentiate between Lists and Tuples.
The list is better for performing operations, such as A Tuple data type is appropriate for
3
insertion and deletion. accessing the elements
Unexpected changes and errors are more likely to Because tuples don’t change they are far
6
occur less error-prone.
Accessibility: Private members are only accessible within the class where they are defined. They
are name-mangled to prevent direct access from outside the class or its subclasses.
class Dog(Animal):
def speak(self):
return "Dog barks"
class Cat(Animal):
def speak(self):
return "Cat meows"
x = [1, 2, 3, 4, 5]
y = [1, 4, 9, 16, 25]
plt.legend()
plt.show()
7.a) Explain the various built - in functions in python with their syntax and example.
Python provides a wide range of built-in functions that simplify programming tasks.
These functions can perform operations related to data types, mathematics, input/output, and
more.
1. len()
Purpose: Returns the number of elements in the tuple.
Syntax: len(s)
Usage:
my_tuple = (1, 2, 3, 4)
print(len(my_tuple)) # Output: 4
2. max()
Purpose: Returns the largest item in the tuple.
Syntax: max(iterable, *[, key])
Usage:
my_tuple = (1, 5, 3, 9)
print(max(my_tuple)) # Output: 9
3. min()
Purpose: Returns the smallest item in the tuple.
Syntax: min(iterable, *[, key])
Usage:
my_tuple = (1, 5, 3, 9)
print(min(my_tuple)) # Output: 1
4. sum()
Purpose: Calculates the sum of all elements in the tuple.
Syntax: sum(iterable, start=0)
Usage:
my_tuple = (1, 2, 3, 4)
print(sum(my_tuple)) # Output: 10
5.float(): Converts a value to a floating-point number.
Syntax: float(x)
Example:
print(float("3.14")) # Outputs: 3.14
6.abs(): Returns the absolute value of a number.
Syntax: abs(x)
Example: print(abs(-5))
b) Write a python program to print a number is positive or negative.
# Program to check if a number is positive, negative, or zero
Syntax -
substring = s[start : end : step]
Ex-
s = "Hello, Python!"
s2 = s[0:5]
print(s2)
3. Comparing Strings
String comparison checks if two strings are equal or how they relate lexicographically
(alphabetical order). Python uses comparison operators like ==, !=, <, >, <=, and >=.
str1 = "apple"
str2 = "banana"
str3 = "apple
# Comparisons
print(str1 == str3) # Output: True (they are equal)
print(str1 < str2) # Output: True ('apple' comes before 'banana')
print(str1 != str2) # Output: True (they are not equal)
4. Finding Substring
You can find the position of a substring within a string using the find() method. It returns the
lowest index of the substring if found, otherwise it returns -1.
Ex:
# Finding a substring
my_string = "Hello, World!"
position = my_string.find("World") # Finds the index of "World"
print(position) # Output: 7
# b. Use get()
# Using get() to access a value
age = my_dict.get('age')
print(f"\nUsing get() to access age: {age}")
class Child(Parent):
def display(self):
print("This is the child class")
obj = Child()
obj.show() # Accessing parent class method
obj.display() # Accessing child class method
Multiple Inheritance
class Parent1:
def method1(self):
print("This is Parent1")
class Parent2:
def method2(self):
print("This is Parent2")
obj = Child()
obj.method1()
obj.method2()
obj.method3()
Multilevel Inheritance
class Grandparent:
def method1(self):
print("This is the grandparent class")
class Parent(Grandparent):
def method2(self):
print("This is the parent class")
class Child(Parent):
def method3(self):
print("This is the child class")
obj = Child()
obj.method1()
obj.method2()
obj.method3()
Hierarchical Inheritance
class Parent:
def method(self):
print("This is the parent class")
class Child1(Parent):
def method1(self):
print("This is child class 1")
class Child2(Parent):
def method2(self):
print("This is child class 2")
obj1 = Child1()
obj1.method()
obj1.method1()
obj2 = Child2()
obj2.method()
obj2.method2()
Hybrid Inheritance
class Parent:
def method(self):
print("This is the parent class")
class Child1(Parent):
def method1(self):
print("This is child class 1")
class Child2(Parent):
def method2(self):
print("This is child class 2")
obj = GrandChild()
obj.method()
obj.method1()
obj.method2()
obj.method3()
11.a) Explain the set data type with suitable example.
A Set in Python programming is an unordered collection data type that is iterable and has no
duplicate elements.
While sets are mutable, meaning you can add or remove elements after their creation, the
individual elements within the set must be immutable and cannot be changed directly.
Set are represented by { } (values enclosed in curly braces)
Sets are useful when you want to store non-redundant items or perform operations like union,
intersection, and difference on collections of data.
EX:
numbers_list = [1, 2, 2, 3, 4, 4, 5]
unique_numbers = set(numbers_list)
print(unique_numbers) # Output: {1, 2, 3, 4, 5}
b). Create a list in python and apply.
i. Slice operator.
ii. append()
iii. Pop() and
iv. len ().
# Step 1: Create a list
my_list = [1, 2, 3, 4, 5]
After applying these operations, the list my_list contains [1, 2, 3, 4, 5] and the list_length variable holds
the value 5.
12. Write a python code to read a CSV file using pandas module and print the first and last five lines of
a file.
import pandas as pd
Replace 'your_file.csv' with the actual path to your CSV file. This code will read the file and display the
first and last five rows of the DataFrame.
13. a) What are looping statements? Explain with example.
Looping statements are used to execute a block of code repeatedly based on a condition or a
sequence.
Python supports two main types of loops:
1. for Loop
The for loop is used to iterate over a sequence (like a list, tuple, dictionary, set, or string) or
other iterable objects.
Example:
n=4
for i in range(0, n):
print(i)
2. while Loop
A while loop executes as long as a condition is True.
If the condition becomes False, the loop stops.
Example:
count = 0
while (count < 3):
count = count + 1
print("Hello Divyanshu")
These are the basics of looping in Python with examples.
b) Write a Python program to calculate area of triangle
Here is a Python program to calculate the area of a triangle using the Heron's formula and a
basic formula for right triangles.
def areaTriangle(a, b, c):
s = (a+b+c)/2
return (s*(s-a)*(s-b)*(s-c))**0.5
a=7
b=8
c=9
print('Area = {:.2f}'.format(areaTriangle(a, b, c)))
14) a) Explain any 4 functions in random module.
The random module in Python provides functions to generate random numbers and make
random selections. Here are four commonly used functions:
1. random()
Purpose: Generates a random floating-point number between 0.0 (inclusive) and 1.0 (exclusive).
Example:
import random
print(random.random()) # Output: e.g., 0.7531
2. randint(a, b)
Purpose: Returns a random integer between a and b (both inclusive).
Example:
print(random.randint(1, 10))
3. choice(seq)
Purpose: Selects a random element from a non-empty sequence (like a list, tuple, or string).
Example:
options = ['apple', 'banana', 'cherry']
print(random.choice(options))
4. shuffle(seq)
Purpose: Randomly shuffles the elements of a mutable sequence (like a list) in place.
Example:
numbers = [1, 2, 3, 4, 5]
random.shuffle(numbers)
print(numbers)
It throws index error in case of It throws value error in case It throws index error in case of
the index doesn’t exist in the of value doesn’t exist in the an index doesn’t exist in the
list. list. list.
b) Explain keys(), values() and items of Dictionary.
In Python, a dictionary is a collection of key-value pairs.
The methods keys(), values(), and items() are used to access the dictionary's components in
different ways.
1. keys() Method
Purpose: Returns a view object containing all the keys in the dictionary.
Type: The view object acts like a set, meaning it doesn't allow duplicate keys and supports set
operations.
Usage:
my_dict = {'a': 1, 'b': 2, 'c': 3}
print(my_dict.keys()) # Output: dict_keys(['a', 'b', 'c'])
2. values() Method
Purpose: Returns a view object containing all the values in the dictionary.
Type: The view object can contain duplicate values, unlike keys.
Usage:
my_dict = {'a': 1, 'b': 2, 'c': 3}
print(my_dict.values()) # Output: dict_values([1, 2, 3])
3. items() Method
Purpose: Returns a view object containing all the key-value pairs in the dictionary as tuples.
Type: Each element in the view object is a tuple (key, value).
Usage:
my_dict = {'a': 1, 'b': 2, 'c': 3}
print(my_dict.items())
16. a) How can a CSV file be created and manipulated in Python using CSV module ?
b) Explain the methods for Pickling and Unpickling.
Pickling
Pickling is the process of converting a Python object into a byte stream (serialization).
This byte stream can be written to a file or sent over a network.
Steps for Pickling:
1. Import the pickle module.
2. Open a file in binary write mode (wb).
3. Use pickle.dump() to serialize the object and write it to the file.
Example:
import pickle
# Define a Python object
person = {
"name": "Alice",
"age": 30,
"gender": "female"
}
# Pickle the object to a binary file
with open("person.pickle", "wb") as file:
pickle.dump(person, file)
print("Pickling completed")
Unpickling
Unpickling is the process of converting a byte stream back into the original Python object
(deserialization).
Steps for Unpickling:
1. Import the pickle module.
2. Open the file containing the pickled data in binary read mode (rb).
3. Use pickle.load() to deserialize the byte stream into a Python object.
Example:
import pickle
# load the data from a file
with open('data.pkl', 'rb') as f:
data = pickle.load(f)
# print the data
print(data)
17.a) Explain seek() and tell() with an example.
In Python, seek() and tell() are methods used with file objects to work with the file's current
position (file pointer).
1. seek(offset, whence):
Moves the file pointer to a specified location in the file.
Parameters:
o offset: Number of bytes to move the pointer.
o whence: The reference point from where the offset is applied.
0 (default): Start of the file.
1: Current file position.
2: End of the file.
2. tell():
Returns the current position of the file pointer (in bytes) from the start of the file.
Example:
# Open a file in read mode
with open("example.txt", "r") as file:
# Read the first 10 characters
content = file.read(10)
print("Content read:", content)
# Move the file pointer 5 bytes forward from the current position
file.seek(5, 0)
print("Position after moving 5 bytes forward:", file.tell())
18. a) Write a Python program to create a Bar Chart from CSV files using Matplotlib.
import pandas as pd
def create_bar_chart(csv_file):
df = pd.read_csv(csv_file)
plt.xlabel('Category')
plt.ylabel('Value')
plt.show()
csv_file = 'data.csv'
create_bar_chart(csv_file)
b) What is JSON? Explain different JSON formats.
JSON (JavaScript Object Notation) is widely used in Python for data interchange.
Python too supports JSON with a built-in package called JSON.
This package provides all the necessary tools for working with JSON Objects
JSON Formats in Python
1.json.dumps(): Converts a Python object into a JSON string.
2.json.loads(): Parses a JSON string and converts it into a Python object.
3.json.dump(): Writes a Python object to a file in JSON format.
4.json.load(): Reads a JSON file and converts it into a Python object.
EXAMPLE:
import json
print("JSON String:")
print(json_str)
print("\nPython Object:")
print(data_from_json)
16. a) How can a CSV file be created and manipulated in Python using CSV module ?
The csv module in Python makes it easy to work with CSV files, enabling you to read, write, and
manipulate data in a structured way.