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

Python Imp

Uploaded by

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

Python Imp

Uploaded by

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

UNIT-1 OVERIVIEW OF PYTHON PROGRAMMING LANGAUAGE:

Q:1 EXPLAIN PYTHON AND ITS CHARACTERSTICS?(4 MARK)

ANS.Python is a high-level, interpreted programming language known for its readability and
versatility. Here are some key characteristics:

1. **Readability**: Python's syntax is clear and concise, making it easy for beginners to learn and for
experienced developers to maintain code.

2. **Interpreted Language**: Python code is executed line by line, which allows for quick testing and
debugging, enhancing productivity.

3. **Dynamically Typed**: Variables in Python do not require explicit declaration of data types,
enabling flexibility in coding but necessitating careful handling of types during execution.

4. **Extensive Libraries**: Python boasts a vast standard library and a rich ecosystem of third-party
packages, making it suitable for various applications, from web development to data analysis and
machine learning.

These features make Python a popular choice for both beginners and professionals across different
domains.

Q:2 EXPLAIN APPLICATION OF PYTHON?(4 MARK)

ANS.Python is a versatile language with a wide range of applications. Here are some key areas where
Python is commonly used:

1. **Web Development**: Python frameworks like Django and Flask facilitate the creation of
dynamic web applications, allowing for rapid development and scalability.

2. **Data Analysis and Visualization**: Libraries such as Pandas, NumPy, and Matplotlib enable data
manipulation and visualization, making Python a preferred choice for data scientists and analysts.

3. **Machine Learning and Artificial Intelligence**: Python offers powerful libraries like TensorFlow,
Keras, and Scikit-learn, which simplify the development of machine learning models and AI
applications.

4. **Automation and Scripting**: Python is often used for automating repetitive tasks, writing scripts
for data processing, and system administration, enhancing efficiency in various workflows.

These applications demonstrate Python's flexibility and capability in solving real-world problems
across multiple domains.

Q:3 EXPLAIN FEATURES OF PYTHON?( 4 MARK)

Python has several distinctive features that contribute to its popularity and usability. Here are four
key features:

1. **Simplicity and Readability**: Python's clear and straightforward syntax makes it accessible for
beginners and encourages writing clean, maintainable code.

Krish Patel
2. **Cross-Platform Compatibility**: Python runs on various operating systems (Windows, macOS,
Linux) without requiring changes to the code, promoting portability.

3. **Extensive Standard Library**: Python comes with a rich set of built-in modules and libraries,
enabling developers to perform many tasks without needing to write code from scratch.

4. **Community Support**: Python has a large, active community that contributes to a wealth of
resources, libraries, and frameworks, making it easier to find help and documentation for developers.

These features make Python a powerful and user-friendly language for a wide range of applications.

Q:4 EXPLAIN THE TYPES OF LOOP IN PYTHON AND ITS CONDITIONAL STATEMENTS?(8MARK)

ANS.In Python, loops and conditional statements are essential for controlling the flow of a program.
Here’s an overview of the types of loops and conditional statements:

### Types of Loops in Python

1. **For Loop**:

- The `for` loop iterates over a sequence (like a list, tuple, string, or range).

- **Syntax**:

for variable in sequence:

# code block

- **Example**:

for i in range(5):

print(i)

- This will print numbers 0 to 4.

2. **While Loop**:

- The `while` loop continues to execute as long as a specified condition is `True`.

- **Syntax**:

while condition:

# code block

```

- **Example**:

count = 0

while count < 5:

print(count)

Krish Patel
count += 1

- This will also print numbers 0 to 4.

### Conditional Statements in Python

1. **If Statement**:

- The `if` statement executes a block of code if its condition is `True`.

- **Syntax**:

if condition:

# code block

- **Example**:

if x > 10:

print("x is greater than 10")

2. **If-Else Statement**:

- This extends the `if` statement to provide an alternative block if the condition is `False`.

- **Syntax**:

if condition:

# code block if True

else:

# code block if False

- **Example**:

if x > 10:

print("x is greater than 10")

else:

print("x is 10 or less")

3. **Elif Statement**:

- Used for multiple conditions, allowing you to check several expressions sequentially.

- **Syntax**:

if condition1:

Krish Patel
# code block for condition1

elif condition2:

# code block for condition2

else:

# code block if all conditions are False

- **Example**:

if x > 10:

print("x is greater than 10")

elif x == 10:

print("x is equal to 10")

else:

print("x is less than 10")

UNIT-2 FUNCTION:

Q:5 What is a string in Python? Explain string operations ?(5 MARK)


ANS. In Python, a **string** is a sequence of characters enclosed within single quotes (`' '`),
double quotes (`" "`), or triple quotes (`''' '''` or `""" """`). Strings are immutable, meaning
once created, their contents cannot be changed.

### String Operations


1. **Concatenation**:
- Combining two or more strings using the `+` operator.
- **Example**:

str1 = "Hello"
str2 = "World"
result = str1 + " " + str2 # Output: "Hello World"

2. **Repetition**:

- Repeating a string multiple times using the `*` operator.


- **Example**:

Krish Patel
str1 = "Hello"
result = str1 * 3 # Output: "HelloHelloHello"

3. **Slicing**:
- Extracting a portion of a string using indexing.
- **Example**:
str1 = "Hello, World!"

slice = str1[0:5] # Output: "Hello"

4. **String Length**:
- Finding the length of a string using the `len()` function.

- **Example**:
str1 = "Hello"
length = len(str1) # Output: 5

5. **String Methods**:

- Python provides numerous built-in methods for string manipulation. Some common
methods include:
- `str.lower()`: Converts to lowercase.
str1 = "HELLO"

result = str1.lower() # Output: "hello"


- `str.upper()`: Converts to uppercase.
result = str1.upper() # Output: "HELLO"
- `str.strip()`: Removes whitespace from both ends.

str1 = " Hello "


result = str1.strip() # Output: "Hello"
- `str.split()`: Splits a string into a list.
str1 = "Hello World"

result = str1.split() # Output: ["Hello", "World"]


- `str.replace(old, new)`: Replaces occurrences of a substring.

Krish Patel
str1 = "Hello World"
result = str1.replace("World", "Python") # Output: "Hello Python"

Q:6 What is a list in Python? Explain list operations with examples?(5MARK)


ANS. In Python, a **list** is an ordered, mutable collection of items that can contain
elements of different data types, including integers, floats, strings, and even other lists. Lists
are defined by enclosing the elements in square brackets (`[ ]`).

### List Operations


1. **Creating a List**:
- You can create a list by simply enclosing elements in square brackets.
- **Example**:

my_list = [1, 2, 3, "Python", 4.5]

2. **Accessing Elements**:
- Elements can be accessed using indexing, where the index starts from `0`.
- **Example**:

print(my_list[3]) # Output: "Python"

3. **Adding Elements**:
- Use `append()` to add a single element to the end of the list.

- **Example**:
my_list.append(6)
print(my_list) # Output: [1, 2, 3, "Python", 4.5, 6]
- Use `insert(index, element)` to add an element at a specific position.

- **Example**:
my_list.insert(2, "Hello")
print(my_list) # Output: [1, 2, "Hello", 3, "Python", 4.5, 6]

4. **Removing Elements**:
- Use `remove(value)` to remove the first occurrence of a specified value.

Krish Patel
- **Example**:
my_list.remove("Hello")
print(my_list) # Output: [1, 2, 3, "Python", 4.5, 6]

- Use `pop(index)` to remove and return an element at a specific index (or the last element
if no index is specified).
- **Example**:
last_element = my_list.pop()

print(last_element) # Output: 6
print(my_list) # Output: [1, 2, 3, "Python", 4.5]

5. **List Slicing**:

- You can extract a subset of the list using slicing.


- **Example**:
sub_list = my_list[1:4] # Output: [2, 3, "Python"]

6. **List Length**:

- Find the number of elements in a list using the `len()` function.


- **Example**:
length = len(my_list) # Output: 5

Q:7 What is a list in Python? Explain list operations with examples?(4MARK)


ANS. In Python, a **list** is a built-in data type that allows you to store an ordered
collection of items. Lists can hold elements of different data types, including numbers,
strings, and even other lists. They are mutable, meaning you can change their content after
creation.
### Basic List Operations:
1. **Creating a List**:
my_list = [1, 2, 3, 'apple', 'banana']

2. **Accessing Elements**:
You can access elements by their index (0-based).

Krish Patel
first_item = my_list[0] # Output: 1
last_item = my_list[-1] # Output: 'banana'

3. **Adding Elements**:
- **Append**: Adds an item to the end of the list.
my_list.append('orange')
# my_list now becomes [1, 2, 3, 'apple', 'banana', 'orange']

- **Insert**: Adds an item at a specified position.


my_list.insert(2, 'grape')
# my_list now becomes [1, 2, 'grape', 3, 'apple', 'banana', 'orange']

4. **Removing Elements**:
- **Remove**: Removes the first occurrence of a specified value.
my_list.remove('apple')
# my_list now becomes [1, 2, 'grape', 3, 'banana', 'orange']

- **Pop**: Removes and returns an item at a specified index (or the last item if no index is
specified).
last_item = my_list.pop() # Removes 'orange'

# my_list now becomes [1, 2, 'grape', 3, 'banana']

5. **Slicing**:
You can create a sublist using slicing.

sublist = my_list[1:3] # Output: [2, 'grape']

### Example of List Operations:


# Creating a list

fruits = ['apple', 'banana', 'cherry']

Krish Patel
# Adding elements
fruits.append('orange') # ['apple', 'banana', 'cherry', 'orange']
fruits.insert(1, 'grape') # ['apple', 'grape', 'banana', 'cherry', 'orange']

# Removing elements
fruits.remove('banana') # ['apple', 'grape', 'cherry', 'orange']
popped_fruit = fruits.pop() # 'orange', fruits now: ['apple', 'grape', 'cherry']
# Accessing elements

first_fruit = fruits[0] # 'apple'


last_fruit = fruits[-1] # 'cherry'
# Slicing
sublist_fruits = fruits[1:3] # ['grape', 'cherry']

These operations make lists a versatile and powerful data structure in Python.

Q:8 Explain Slicing & Indexing in list with example?( 4 MARK)


ANS. ### Slicing and Indexing in Python Lists
**Indexing** and **slicing** are powerful features in Python that allow you to access and
manipulate parts of a list.
### Indexing
Indexing refers to accessing individual elements in a list using their position (index). In
Python, indexing starts at **0**.

- **Example of Indexing**:
fruits = ['apple', 'banana', 'cherry', 'date']
# Accessing elements using indexing
first_fruit = fruits[0] # Output: 'apple'

second_fruit = fruits[1] # Output: 'banana'


last_fruit = fruits[-1] # Output: 'date' (negative index)
### Slicing
Slicing allows you to access a subset of the list by specifying a range of indices. The syntax for
slicing is `list[start:stop]`, where `start` is inclusive and `stop` is exclusive.

Krish Patel
- **Example of Slicing**:
fruits = ['apple', 'banana', 'cherry', 'date', 'fig', 'grape']

# Slicing the list


sublist1 = fruits[1:4] # Output: ['banana', 'cherry', 'date']
sublist2 = fruits[:3] # Output: ['apple', 'banana', 'cherry'] (from start to index 2)
sublist3 = fruits[3:] # Output: ['date', 'fig', 'grape'] (from index 3 to end)

sublist4 = fruits[-3:] # Output: ['date', 'fig', 'grape'] (last three elements)

### Key Points


- **Indexing** allows access to individual elements.

- **Slicing** returns a new list containing elements from the specified range.
- Negative indices can be used to access elements from the end of the list.
### Full Example
fruits = ['apple', 'banana', 'cherry', 'date', 'fig', 'grape']

# Indexing
print(fruits[0]) # Output: 'apple'
print(fruits[-2]) # Output: 'fig'
# Slicing

print(fruits[1:4]) # Output: ['banana', 'cherry', 'date']


print(fruits[:3]) # Output: ['apple', 'banana', 'cherry']
print(fruits[3:]) # Output: ['date', 'fig', 'grape']
print(fruits[-3:]) # Output: ['date', 'fig', 'grape']

These features make it easy to access and manipulate data in lists efficiently.

Krish Patel
UNIT-3 SET, TUPLES,DICTIONARY:
Q:9 difference between tuple and set?(4 MARKS)(100%)
ANS. Here are the key differences between **tuples** and **sets** in Python:
### 1. **Definition**
- **Tuple**: An ordered collection of items that can contain duplicate elements. Tuples are
defined using parentheses `()`.
- **Set**: An unordered collection of unique items that cannot contain duplicates. Sets are
defined using curly braces `{}` or the `set()` function.

### 2. **Order**
- **Tuple**: Ordered, meaning the items have a defined position. You can access elements
using indexing.
- **Set**: Unordered, meaning there is no defined position for the items. You cannot access
elements by index.

### 3. **Mutability**
- **Tuple**: Immutable, meaning once a tuple is created, its contents cannot be changed
(you cannot add, remove, or modify elements).

- **Set**: Mutable, meaning you can add or remove items after the set is created.

### 4. **Use Cases**


- **Tuple**: Typically used for storing related items and ensuring the order is maintained
(e.g., coordinates, function return values).
- **Set**: Used for membership testing, removing duplicates from a collection, and
performing mathematical set operations (like union and intersection).

Krish Patel
### Summary Table
| Feature | Tuple | Set |
|------------------|---------------------------|---------------------------|

| Definition | Ordered collection | Unordered collection |


| Order | Yes | No |
| Mutability | Immutable | Mutable |
| Duplicates | Allowed | Not allowed |

| Syntax | `()` | `{}` or `set()` |

### Example Code


# Tuple example

my_tuple = (1, 2, 2, 3)
print(my_tuple[1]) # Output: 2

# Set example
my_set = {1, 2, 2, 3}

print(my_set) # Output: {1, 2, 3} (duplicates removed)


This highlights the primary distinctions between tuples and sets in Python.

Q:10 what is dictionary ? explain any 5 methods of dictionary in python?(5

MARKS)
ANS. A **dictionary** in Python is a built-in data type that stores data in key-value pairs. It is
unordered, mutable, and indexed by keys. Dictionaries are defined using curly braces `{}` or
the `dict()` function.

### Key Features of Dictionaries:


- **Unordered**: The items do not have a defined order.
- **Mutable**: You can change the content of a dictionary after it is created.

- **Indexed by Keys**: Each value is associated with a unique key.

Krish Patel
### Common Methods of Dictionary

1. **`get(key, default)`**:

Retrieves the value associated with the specified key. If the key is not found, it returns the
default value (if provided).

```python

my_dict = {'a': 1, 'b': 2}


value = my_dict.get('b') # Output: 2
value_not_found = my_dict.get('c', 'Not Found') # Output: 'Not Found'
```

2. **`keys()`**:
Returns a view object that displays a list of all the keys in the dictionary.

```python

my_dict = {'a': 1, 'b': 2}


keys = my_dict.keys() # Output: dict_keys(['a', 'b'])
```

3. **`values()`**:
Returns a view object that displays a list of all the values in the dictionary.

```python

my_dict = {'a': 1, 'b': 2}


values = my_dict.values() # Output: dict_values([1, 2])
```

4. **`items()`**:
Returns a view object that displays a list of the dictionary's key-value pairs as tuples.

Krish Patel
```python
my_dict = {'a': 1, 'b': 2}
items = my_dict.items() # Output: dict_items([('a', 1), ('b', 2)])

```

5. **`update(other_dict)`**:
Updates the dictionary with elements from another dictionary or from an iterable of key-
value pairs. If keys already exist, their values are updated.
```python
my_dict = {'a': 1, 'b': 2}
my_dict.update({'b': 3, 'c': 4}) # Now my_dict is {'a': 1, 'b': 3, 'c': 4}

```

### Example Code


```python
# Creating a dictionary

my_dict = {'a': 1, 'b': 2}

# Using get method


print(my_dict.get('b')) # Output: 2

print(my_dict.get('c', 'Not Found')) # Output: 'Not Found'

# Using keys method


print(my_dict.keys()) # Output: dict_keys(['a', 'b'])

# Using values method


print(my_dict.values()) # Output: dict_values([1, 2])

# Using items method


print(my_dict.items()) # Output: dict_items([('a', 1), ('b', 2)])

Krish Patel
# Using update method
my_dict.update({'b': 3, 'c': 4})

print(my_dict) # Output: {'a': 1, 'b': 3, 'c': 4}


```
These methods provide powerful ways to interact with and manipulate dictionary data in
Python.

Q:11 explain tuples and set its use any 3 method with example?(5 mark)
ANS. ### Tuples in Python

A **tuple** is an ordered collection of items, which can be of different data types. Tuples
are defined using parentheses `()` and are immutable, meaning once they are created, their
elements cannot be changed, added, or removed.

#### Use Cases for Tuples:

- Storing related data together (like coordinates or RGB color values).


- Returning multiple values from a function.
- Creating fixed collections of items.

### Common Methods of Tuples

1. **`count(value)`**:
Returns the number of occurrences of a specified value in the tuple.

```python
my_tuple = (1, 2, 3, 2, 4)
count_of_2 = my_tuple.count(2) # Output: 2

```

Krish Patel
2. **`index(value, start, end)`**:
Returns the index of the first occurrence of the specified value. You can also specify the
start and end indices for the search.

```python
my_tuple = (1, 2, 3, 2, 4)
index_of_2 = my_tuple.index(2) # Output: 1

# index_of_2_with_range = my_tuple.index(2, 2) # Output: 3 (searching starts from index


2)
```

3. **`len()`** (function, not a method):


Returns the number of items in the tuple.

```python
my_tuple = (1, 2, 3)

length = len(my_tuple) # Output: 3


```

### Example Code for Tuples

```python
# Creating a tuple
my_tuple = (1, 2, 3, 2, 4)

# Using count method


count_of_2 = my_tuple.count(2)
print(f"Count of 2: {count_of_2}") # Output: Count of 2: 2

# Using index method

Krish Patel
index_of_3 = my_tuple.index(3)
print(f"Index of 3: {index_of_3}") # Output: Index of 3: 2

# Using len function


length_of_tuple = len(my_tuple)
print(f"Length of tuple: {length_of_tuple}") # Output: Length of tuple: 5
```

### Sets in Python

A **set** is an unordered collection of unique items. Sets are defined using curly braces `{}`
or the `set()` function, and they are mutable.

#### Use Cases for Sets:


- Removing duplicates from a list.
- Membership testing (checking if an item exists in the set).

- Performing mathematical operations like unions and intersections.

### Common Methods of Sets

1. **`add(value)`**:
Adds a new element to the set. If the element already exists, it won't be added again.

```python

my_set = {1, 2, 3}
my_set.add(4) # Now my_set becomes {1, 2, 3, 4}
```

2. **`remove(value)`**:

Krish Patel
Removes a specified element from the set. If the element is not found, it raises a
`KeyError`.

```python
my_set = {1, 2, 3}
my_set.remove(2) # Now my_set becomes {1, 3}
# my_set.remove(5) # Raises KeyError

```

3. **`union(other_set)`**:
Returns a new set containing all elements from both sets.

```python
set_a = {1, 2, 3}
set_b = {3, 4, 5}
union_set = set_a.union(set_b) # Output: {1, 2, 3, 4, 5}

```

### Example Code for Sets

```python
# Creating a set
my_set = {1, 2, 3}

# Using add method


my_set.add(4)
print(my_set) # Output: {1, 2, 3, 4}

# Using remove method


my_set.remove(2)

Krish Patel
print(my_set) # Output: {1, 3, 4}

# Using union method

set_a = {1, 2, 3}
set_b = {3, 4, 5}
union_set = set_a.union(set_b)
print(union_set) # Output: {1, 2, 3, 4, 5}

```

These examples illustrate the characteristics and functionalities of tuples and sets in Python,
highlighting their usefulness in various scenarios.

Q:12 Expain Tuple Operations?(4 mark)


ANS. Tuples in Python support several operations that allow you to interact with and
manipulate the data they contain. Here are the main tuple operations:

### 1. **Accessing Elements**


You can access individual elements in a tuple using indexing. Python uses zero-based
indexing, so the first element is at index 0.

```python
my_tuple = (10, 20, 30, 40)

# Accessing elements

first_element = my_tuple[0] # Output: 10


last_element = my_tuple[-1] # Output: 40 (negative index)
```

### 2. **Slicing**
You can create a sub-tuple by slicing, which allows you to retrieve a range of elements.

Krish Patel
```python
my_tuple = (10, 20, 30, 40, 50)

# Slicing
sub_tuple = my_tuple[1:4] # Output: (20, 30, 40)
```

### 3. **Concatenation**
You can combine two or more tuples using the `+` operator.

```python
tuple_a = (1, 2, 3)
tuple_b = (4, 5, 6)

# Concatenation

combined_tuple = tuple_a + tuple_b # Output: (1, 2, 3, 4, 5, 6)


```

### 4. **Repetition**

You can repeat the elements of a tuple using the `*` operator.

```python
my_tuple = (1, 2)

# Repetition
repeated_tuple = my_tuple * 3 # Output: (1, 2, 1, 2, 1, 2)
```

Krish Patel
### Example Code

```python

# Define a tuple
my_tuple = (10, 20, 30, 40)

# Accessing elements

print(my_tuple[0]) # Output: 10
print(my_tuple[-1]) # Output: 40

# Slicing

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

# Concatenation
tuple_a = (1, 2, 3)
tuple_b = (4, 5, 6)

combined_tuple = tuple_a + tuple_b


print(combined_tuple) # Output: (1, 2, 3, 4, 5, 6)

# Repetition

repeated_tuple = my_tuple * 2
print(repeated_tuple) # Output: (10, 20, 30, 40, 10, 20, 30, 40)
```

Krish Patel

You might also like