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

python1

The document provides an overview of various Python programming concepts, including dictionaries, data structures, sorting methods, and the use of libraries like Matplotlib, NumPy, and Pandas. It also explains membership operators, indentation, and file handling functions such as `open()` and `write()`. Additionally, it covers multiple inheritance and provides code examples for generating random numbers and defining a student class.

Uploaded by

Rohan Unde
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)
6 views

python1

The document provides an overview of various Python programming concepts, including dictionaries, data structures, sorting methods, and the use of libraries like Matplotlib, NumPy, and Pandas. It also explains membership operators, indentation, and file handling functions such as `open()` and `write()`. Additionally, it covers multiple inheritance and provides code examples for generating random numbers and defining a student class.

Uploaded by

Rohan Unde
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/ 4

Q1 what is Dictionary Q.

5 data structures that are commonly used py

A dictionary in Python is an unordered collection of 1. **Lists**:.2. **Tuples3. **Dictionaries**:


key-value pairs. It is a built-in data type that allows
4. **Sets**: 5. **Strings**: 6. **Arrays**:
you to store data in the form of key-value mappings.
In other programming languages, dictionaries may 8. **Stacks**: 9. **Queues**:
be referred to as associative arrays or hash maps.
Q7. membership operators
my_dict = {'name': 'Alice', 'age': 30, 'city': 'New
York'} In Python, membership operators (`in` and `not in`)
are used to test for membership within a sequence
Q2 syntac for method to sort a list (such as a list, tuple, string, or set). These operators
return `True` if the specified value is found in the
In Python, you can use the `sorted()` function or the
sequence, and `False` otherwise. Here's how
`sort()` method to sort a list.
membership operators are typically used:
1. **Using `sorted()` function**:
1. *Using `in` Operator**:
The `sorted()` function returns a new sorted list
2. **Using `not in` Operator**:
from the elements of any iterable object, including
lists. Q8.describe indetation variable
sorted_list = sorted(original_list) In Python, indentation refers to the spaces or tabs
that are used at the beginning of a line to define the
2. **Using `sort()` method**:
structure and hierarchy of code blocks. Unlike many
The `sort()` method sorts the elements of a list in other programming languages that use braces `{}` or
place, modifying the original list. keywords like `begin` and `end` to denote code
blocks, Python relies on indentation to indicate the
original_list.sort()
beginning and end of blocks of code. The consistent
sorted_list_desc = sorted(original_list, reverse=True) use of indentation is a fundamental aspect of
Python's syntax and is crucial for the readability and
original_list.sort(reverse=True) correctness of Python code.
Q3. use of matplotlib in py 1. **Indentation Levels**: Each level of indentation
1. **Data Visualization**: Matplotlib is primarily typically represents a nested block of code.
used for creating various types of plots and charts to 2. **Consistency**: Python requires consistent
visualize data. indentation throughout the code. This means that all
2. **Scientific Plotting**: It's extensively used in lines within the same block must be indented by the
scientific computing and data analysis for visualizing same amount.
experimental results, mathematical functions, and 3. **Blocks of Code**: Blocks of code are defined by
simulations. indentation rather than curly braces or keywords.
3. **Customization**: Matplotlib allows users to For example, in a `for` loop or an `if` statement, the
customize every aspect of the plots, including colors, indented lines following the loop or conditional
line styles, markers, fonts, labels, legends, and 4. **Indentation Errors**: Incorrect indentation can
annotations. lead to syntax errors or logical errors in Python code.
4. **Integration with Pandas and NumPy**: 5. **Whitespace Sensitivity**: Python is whitespace-
Matplotlib seamlessly integrates with popular sensitive, meaning that the indentation level
libraries like Pandas and NumPy, making it easy to determines the meaning of the code. Therefore, care
plot data directly from these data structures. must be taken to ensure that the indentation
Q6.Operators in py accurately reflects the intended structure of the
code.
1 arithmaric 2.logical 3.relational 4.bitwise
Q.print following pattern - Supports broadcasting, which allows arithmetic
operations on arrays of different shapes.
101010
4. **Linear Algebra**:
10101
- Includes functions for linear algebra operations,
101
such as dot products, matrix decompositions, and
0 solving linear systems.

def print_pattern(): 5. **Random Sampling**:

rows = 4 - Provides capabilities for generating random


numbers and performing random sampling.
for i in range(rows):
### Pandas
for j in range(i):
**Pandas** is a powerful data analysis and
print(" ", end=" ") manipulation library for Python. It provides data
for j in range(rows - i): structures and functions needed to work with
structured data seamlessly.
if j % 2 == 0:
#### Key Features:
print("1", end=" ")
1. **DataFrame**:
else:
- The primary data structure in Pandas, similar to a
print("0", end=" ") table in a relational database or an Excel
print() spreadsheet.

print_pattern() - Supports labeled axes (rows and columns),


making it easier to manipulate and analyze data.
Q9expalin following packages numpy and pandas
2. **Series**:
### NumPy
- A one-dimensional labeled array, capable of
**NumPy** (Numerical Python) is a fundamental holding any data type.
package for scientific computing in Python. It
provides support for arrays, matrices, and a 3. **Data Cleaning and Preparation**:
collection of mathematical functions to operate on - Offers tools for handling missing data, filtering,
these data structures. grouping, and merging datasets.
#### Key Features: 4. **Time Series Analysis**:
1. **N-Dimensional Arrays**: - Provides specialized functions for working with
- Provides the `ndarray` object, a fast and space- time series data, including date parsing, indexing,
efficient multidimensional array. and resampling.

- Arrays can be of any type, and mathematical 5. **Input/Output**:


operations on these arrays are optimized for - Supports reading from and writing to various file
performance. formats, including CSV, Excel, SQL databases, and
2. **Mathematical Functions**: JSON.

- Offers a wide range of mathematical functions for


operations on arrays, including trigonometric,
statistical, and algebraic functions.

3. **Broadcasting**:
Q.Difff Bet List And Tuple Q.Design a class student with data members :
name, roll no., department,mobile no. Create
List Tuple List Tuple suitable methods for reading and printing student
Lists are mutable Tuples Lists are mutable Tuples
are immutable are immutable information.
The implication of The implication of class Student:
iterations is Time- iterations is Time-
consuming consuming def __init__(self):
The implication of The implication of
iterations is iterations is self.name = ""
comparatively Faster comparatively Faster self.roll_no = ""

self.department = ""

self.mobile_no = ""
Q. description of the `open()` and `write()`
def read_student_info(self):
functions in Python, along with examples.
self.name = input("Enter student name: ")
### `open()`
self.roll_no = input("Enter roll number: ")
The `open()` function is used to open a file in Python.
It returns a file object, which can then be used to self.department = input("Enter department: ")
read from or write to the file. The `open()` function
has the following syntax: self.mobile_no = input("Enter mobile number: ")

```python def print_student_info(self):

open(file, mode='r', buffering=-1, encoding=None, print("Student Information:")


errors=None, newline=None, closefd=True, print("Name:", self.name)
opener=None)
print("Roll Number:", self.roll_no)
### `write()`
print("Department:", self.department)
The `write()` function is used to write data to a file. It
writes the specified string to the file and returns the print("Mobile Number:", self.mobile_no)
number of characters written. This function is used # Create an instance of the Student class
with a file object that has been opened in a mode
that allows writing (`'w'`, `'a'`, `'wb'`, etc.). student = Student()

#### Example: # Read and set student information

```python student.read_student_info()

file = open('example.txt', 'w') # Print student information

file.write('Hello, World!') student.print_student_info()

file.close()
Q.code for following output def method2(self):

Cursor=”python” print("Method from BaseClass2")

Cursor=[:3] class DerivedClass(BaseClass1, BaseClass2):

Cursor=[3:] def __init__(self):

Cursor=[:] BaseClass1.__init__(self)

Cursor=[2:2] BaseClass2.__init__(self)

Cursor=[-1] print("DerivedClass initialized")

Cursor=[1] def method3(self):

Thus, the corrected outputs for the operations are: print("Method from DerivedClass")

derived_object = DerivedClass()
Cursor = Cursor[:3] -> 'pyt'
Cursor = Cursor[3:] -> 'hon' derived class
Cursor = Cursor[:] -> 'python'
Cursor = Cursor[2:2] -> '' derived_object.method1()
Cursor = Cursor[-1] -> 'n' derived_object.method2()
Cursor = Cursor[1] -> 'y'
derived_object.method3()

print(derived_object.str1)
Q. code for generate radom num 10 to 50 using
numpy lib print(derived_object.str2)

import numpy as np

# Generate a random integer between 10 (inclusive) Q.Explain any four file modes in Python.
and 51 (exclusive)

random_number = np.random.randint(10, 51)

print(random_number)

Q. multiple inheritance code py

class BaseClass1:

def __init__(self):

self.str1 = "BaseClass1"

print("BaseClass1 initialized")

def method1(self):

print("Method from BaseClass1")

class BaseClass2:

def __init__(self):

self.str2 = "BaseClass2"

print("BaseClass2 initialized")

You might also like