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

python 5m

The document explains various concepts in Python, including file reading and writing processes, control flow statements, data types, inheritance types, and the use of libraries like Matplotlib. It provides examples for each concept, such as how to read from and write to files, use break and continue statements in loops, and plot graphs. Additionally, it covers tuple methods, decision-making statements, and the advantages of using web APIs.

Uploaded by

av5bkc
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)
5 views

python 5m

The document explains various concepts in Python, including file reading and writing processes, control flow statements, data types, inheritance types, and the use of libraries like Matplotlib. It provides examples for each concept, such as how to read from and write to files, use break and continue statements in loops, and plot graphs. Additionally, it covers tuple methods, decision-making statements, and the advantages of using web APIs.

Uploaded by

av5bkc
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/ 19

12. Explain file reading and writing process in python with an example.

 Python provides built-in functions for creating, writing, and reading files. Two types of files can
be handled in Python, normal text files, csv files and binary files.
File Reading Process
 Open the File: Use the open() function to open a file. You need to specify the file name and the
mode
 Read the File: Use methods like .read(), .readline(), or .readlines() to read the contents of the
file.
 Close the File: Use the .close() method to close the file after you're done.
File Writing Process
 Open the File: Use the open() function with the mode 'w' (write) or 'a' (append).
 Write to the File: Use the .write() or .writelines() methods to write data to the file.
 Close the File: Use the .close() method to close the file.
Here’s a complete example demonstrating both reading from and writing to a file:
file_name = 'example.txt'

with open(file_name, 'w') as file:


file.write("Hello, World!\n")
file.write("This is a file handling example in Python.\n")
file.writelines(["Line 1\n", "Line 2\n", "Line 3\n"])

with open(file_name, 'r') as file:


# Read the entire content of the file
content = file.read()
print("File Content:")
print(content)

with open(file_name, 'r') as file:


print("Reading line by line:")
for line in file:
print(line.strip())
13.What does break and continue statements do in Python ?
In Python, the break and continue statements are used to control the flow of loops (like for and while
loops).
break Statement
 The break statement is used to exit a loop prematurely.
 When the break statement is encountered, the loop stops executing immediately, and the
program control moves to the first line of code after the loop.
 EX-
for i in range(10):
print(i)
if i == 2:
break
continue Statement
 The continue statement is used to skip the rest of the code inside the loop for the current
iteration and jump to the next iteration.
 EX-
for i in range(1, 6):
if i == 3:
continue
print(i)
14. What are Data Types? Explain the Python Built in Data Types.
 Data types specify the type of value a variable can hold in a programming language.
 They determine the operations that can be performed on the data and how the data is stored in
memory.
Python Built-in Data Types
Python provides several built-in data types, categorized into the following groups:
1. Text Type
 str (String): Represents a sequence of characters.
o Example: "Hello, World!"
2. Numeric Types
 int (Integer): Represents whole numbers, positive or negative.
o Example: 10, -5
 float (Floating-point): Represents numbers with a decimal point.
o Example: 3.14, -0.001
 complex (Complex Numbers): Represents numbers with a real and imaginary part.
o Example: 3+4j, 1j
3. Sequence Types
 list: An ordered, mutable (changeable) collection of items.
o Example: [1, 2, 3], ["apple", "banana"]
 tuple: An ordered, immutable (unchangeable) collection of items.
o Example: (1, 2, 3), ("a", "b")
 range: Represents a sequence of numbers, typically used in loops.
o Example: range(5) (generates 0, 1, 2, 3, 4)
4. Boolean Type
 bool: Represents two values: True or False.
o Example: True, False
15. What is the difference between writing and appending data to a file?
 The only difference they have is, when you open a file in the write mode, the file is reset,
resulting in deletion of any data already present in the file.
 While in append mode this will not happen. Append mode is used to append or add data to the
existing data of file, if any.
16. Explain different types of inheritance in Python. (1,2) down

3.Multilevel Inheritance :
In multilevel inheritance, features of the base class and the derived class are further inherited into the
new derived class.

4.Hierarchical Inheritance:
When more than one derived class are created from a single base this type of inheritance is called
hierarchical inheritance.
5. Hybrid Inheritance:
Inheritance consisting of multiple types of inheritance is called hybrid inheritance.

17. What is Matplotlib? Write the features of Matplotlib.


 Matplotlib is a powerful plotting library in Python used for creating static, animated, and
interactive visualizations.
 Matplotlib’s primary purpose is to provide users with the tools and functionality to
represent data graphically, making it easier to analyze and understand.
Key Features of Matplotlib:
1. Versatility: Matplotlib can generate a wide range of plots, including line plots, scatter plots, bar
plots, histograms, pie charts, and more.
2. Customization: It offers extensive customization options to control every aspect of the plot,
such as line styles, colors, markers, labels, and annotations.
3. Integration with NumPy: Matplotlib integrates seamlessly with NumPy, making it easy to plot
data arrays directly.
4. Publication Quality: Matplotlib produces high-quality plots suitable for publication with fine-
grained control over the plot aesthetics.
5. Cross-Platform: It is platform-independent and can run on various operating systems,
including Windows, macOS, and Linux.
18. Explain any 6 Built in functions in Tuple.
Python Tuples is an immutable collection of that are more like lists. Python Provides a couple of
methods to work with tuples.
1. len()
 Purpose: Returns the number of elements in the tuple.
 Usage:
my_tuple = (1, 2, 3, 4)
print(len(my_tuple)) # Output: 4
2. max()
 Purpose: Returns the largest item in the tuple.
 Usage:
my_tuple = (1, 5, 3, 9)
print(max(my_tuple)) # Output: 9
3. min()
 Purpose: Returns the smallest item in the tuple.
 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.
 Usage:
my_tuple = (1, 2, 3, 4)
print(sum(my_tuple)) # Output: 10
5. index()
 Purpose: Returns the index of the first occurrence of a specified value.
 Usage:
my_tuple = (1, 2, 3, 2)
print(my_tuple.index(2)) # Output: 1
6. count()
 Purpose: Returns the number of times a specified value appears in the tuple.
 Usage:
my_tuple = (1, 2, 2, 3, 4)
print(my_tuple.count(2)) # Output: 2
1.Describe decision control flow statements in python.
 Decision control flow statements in Python allow a program to execute different blocks of code
based on certain conditions.
 Python provides several types of decision control statements:
IF STATEMENT
 The if statement evaluates a condition, and if the condition is true, the associated block of code
is executed.
 Syntax-
if condition:
# Code to execute if the condition is true
if-else Statement
 The if-else statement provides an alternate block of code to execute if the condition is false.
 Syntax-
if condition:
# Code to execute if the condition is true
else:
# Code to execute if the condition is false
if-elif-else Statement
 The if-elif-else statement allows checking multiple conditions. The first true condition executes,
and the rest are skipped.
 Syntax-
if condition1:
# Code to execute if condition1 is true
elif condition2:
# Code to execute if condition2 is true
else:
# Code to execute if none of the conditions are true
Nested if Statements
 An if statement can be placed inside another if statement to check conditions in a hierarchical
manner.
 Syntax-
if condition1:
if condition2:
# Code to execute if condition1 and condition2 are true
2. Explain string slicing and joining operations.
String Slicing in Python
 String slicing in Python is a way to get specific parts of a string by using start, end, and step
values.
 It’s especially useful for text manipulation and data parsing.
 Syntax -
substring = s[start : end : step]

 Ex-

s = "Hello, Python!"

s2 = s[0:5]

print(s2)

joining operations

 The join() function in Python is used to merge items from a collection, such as a list or tuple, into a
single string.

 It takes a separator and combines the elements of the collection with that separator in between.

 For example, if you have a list of words ["Hello", "world", "Python"] and want to join them
with spaces, you would use join() like this:

.join(["Hello", "world", "Python"])

 The result would be "Hello world Python". You can choose any separator, such as a comma,
dash, or even no separator at all.

 this makes it easy to create strings from collections without needing complex
loops or logic.
3. Explain traversing a list in python with suitable example.
 Traversing a list in Python means accessing each element of the list sequentially, typically to
perform some operation on it.
 Python provides several ways to traverse a list, including for loops, while loops, and list
comprehensions.
1. Using a for Loop
# Example
numbers = [10, 20, 30, 40, 50]
# Traverse using a for loop
for number in numbers:
print(number)
2. Using for Loop with Indexes
# Example
numbers = [10, 20, 30, 40, 50]
# Traverse using index
for i in range(len(numbers)):
print(f"Index {i}: {numbers[i]}")
3. Using enumerate()
# Example
numbers = [10, 20, 30, 40, 50]
# Traverse with enumerate
for index, value in enumerate(numbers):
print(f"Index {index}: {value}")
4. Using a while Loop
# ExampleS
numbers = [10, 20, 30, 40, 50]
# Traverse using while loop
i=0
while i < len(numbers):
print(numbers[i])
i += 1
4. Distinguish between single and multiple Inheritance with examples.
Single Inheritance
 Single inheritance occurs when a class inherits from only one parent class.
 This means that the child class can access the properties and methods of a single parent class.

Multiple Inheritance
 Multiple inheritance occurs when a class inherits from more than one parent class.
 This allows the child class to access attributes and methods from multiple parent classes.

Key Differences:
Aspect Single Inheritance Multiple Inheritance

Number of  Multiple parent classes.


 One parent class.
Parents
 Simple hierarchy,  Complex hierarchy, can
Hierarchy combine classes.
linear structure.

 Used for simpler  Useful when a class needs


Usage models and features from multiple
structures. sources.
5.What are the advantages of using web API?
 Web API is a great framework for exposing your data and service to different devices.
Advantages :
Scalability:
 Python's performance and tools like load balancers can support large-scale web applications.
Asynchronous coding:
 Python can manage asynchronous code, eliminating deadlocks and research contention.
Easy to learn and use:
 Python's flexibility and adaptability allows developers to quickly iterate and prototype.
Rapid prototyping:
 It's easy to set up a work environment for developing an API with Python.
Documentation support:
 Frameworks can provide assistance, solutions to challenges, and share best practices.
Speed:
 Some frameworks, like FastAPI, are very fast and comparable to Go and Node.js.
6. What are the steps followed to plot a simple line graph in python.
To plot a simple line graph in Python, you can use the popular library Matplotlib. Below are the steps
you need to follow:
1. Install Matplotlib (if not already installed)
pip install matplotlib

2. Import Matplotlib
import matplotlib.pyplot as plt

3. Prepare the Data


x = [1, 2, 3, 4, 5] # x-coordinates
y = [2, 4, 6, 8, 10] # y-coordinates

4. Create the Plot


plt.plot(x, y)

5. Customize the Plot (Optional)


plt.title("Simple Line Graph") # Add a title
plt.xlabel("X-axis Label") # Label for the X-axis
plt.ylabel("Y-axis Label") # Label for the Y-axis

6. Display the Plot


plt.show()
Complete Example:
import matplotlib.pyplot as plt

# Data
x = [1, 2, 3, 4, 5]
y = [2, 4, 6, 8, 10]

# Plot
plt.plot(x, y)

# Customization
plt.title("Simple Line Graph")
plt.xlabel("X-axis")
plt.ylabel("Y-axis")

# Display
plt.show()
7. Explain the key features of python.
 Python is a high-level, interpreted programming language known for its simplicity and
readability. Created by Guido van Rossum and first released in 1991

Python is a programming language with many key features, including:


 Free and open source
Python is free to use and download because it's open source and has an OSI approved license.
 Object-oriented
Python is fully object-oriented, which means developers can create classes and objects to model real-
world entities.
 Language interpretation
Python uses indentation to indicate blocks of code, which makes the code structure more readable.
 Dynamic language
Python is a dynamic-typed language that supports integration with other languages and tools.
 Easy to code
Python is easier to learn than other programming languages, and beginners can learn to code in
Python in a few days.
 Large standard library
Python has a large standard library that contains predefined modules and functions for certain tasks.
 Extensible
Python code can be written in other languages like C++, making it a highly extensible language.
8. What is indentation on in python? Explain with a suitable example.
 indentation is used to define blocks of code.
 It tells the Python interpreter that a group of statements belongs to a specific block.
 All statements with the same level of indentation are considered part of the same block.
 Indentation is achieved using whitespace (spaces or tabs) at the beginning of each line.

For Example:

if 10 > 5:
print("This is true!")
print("I am tab indentation")

print("I have no indentation")

 The first two print statements are indented by 4 spaces, so they belong to the if block.
 The third print statement is not indented, so it is outside the if block.
9. Write a python program for filter () to filter only even numbers from a given list.
Here's a Python program using the filter() function to filter only even numbers from a given list:
# Function to check if a number is even
def is_even(num):
return num % 2 == 0

# Given list of numbers


numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

# Using filter() to get even numbers


even_numbers = list(filter(is_even, numbers))

# Print the result


print("Even numbers:", even_numbers)

10. Explain indexing and slicing in tuples with an example.


1. Indexing
 Indexing is used to access individual elements of a tuple. Python uses zero-based indexing,
meaning the first element is at index 0, the second at 1, and so on.
 Syntax:
tuple[index]

 Example:
my_tuple = (10, 20, 30, 40, 50)
print(my_tuple[0]) # Access first element (10)
print(my_tuple[3]) # Access fourth element (40)
print(my_tuple[-1]) # Access last element (50)
2. Slicing
 Slicing
s
is used to access a subset (a slice) of the tuple.
 The slice is defined by a start index, an end index, and an optional step.
 Syntax:
tuple[start:end:step]

Example:

my_tuple = (10, 20, 30, 40, 50, 60)

# Slice from index 1 to 4 (exclusive)


print(my_tuple[1:4]) # Output: (20, 30, 40)

# Slice from start to index 3 (exclusive)


print(my_tuple[:3]) # Output: (10, 20, 30)

# Slice from index 2 to the end


print(my_tuple[2:]) # Output: (30, 40, 50, 60)

# Slice with step 2


print(my_tuple[::2]) # Output: (10, 30, 50)

# Slice in reverse order


print(my_tuple[::-1]) # Output: (60, 50, 40, 30, 20, 10)
11. Explain the concepts of class and objects in python with an example.
1. Class:
 A class is a blueprint for creating objects. It defines the properties (attributes) and behaviors
(methods) that the objects created from the class will have.
 Classes are created by keyword class.
 Attributes are the variables that belong to a class.
 Attributes are always public and can be accessed using the dot (.) operator. Eg.: My
class.Myattribute

2. Object:
 An object is an instance of a class. It represents a specific example of the class with actual values
for the attributes defined in the class.
 An object consists of:
State: It is represented by the attributes of an object. It also reflects the properties of an object.
Behavior: It is represented by the methods of an object. It also reflects the response of an object
to other objects.
Identity: It gives a unique name to an object and enables one object to interact with other
objects.

Example:

# instantiating a class
class Dog:

attr1 = "mammal"
attr2 = "dog"

# A sample method
def fun(self):
print("I'm a", self.attr1)
print("I'm a", self.attr2)

Rodger = Dog()

# Accessing class attributes


# and method through objects
print(Rodger.attr1)
Rodger.fun()

You might also like