Uploaded by Rashi Sharma

DAP 5

advertisement
Aditya sain
23MCAN0152
D.A.P.
Assignment 5
SECTION A
1. Output:
1
4
2
6
d
-5
e
3
dtype: int64
2. extend() method appends elements to the original list.
append() method appends passed element as a single element to the original list.
3. Output:
1
Explanation: 1**3 is 1
4. Duck typing refers to checking if an object walks like a duck and quacks like a duck instead of
checking the actual type of the object. It focuses more on the behaviors/methods than the actual
class type.
5. Variables declared inside a function have local scope, they can be accessed only inside function.
Variables declared outside have global scope, they can be accessed globally throughout program.
SECTION B
1. Here is program to convert Celsius to Fahrenheit:
```python
celsius = float(input("Enter temperature in celsius: "))
fahrenheit = (celsius * 9/5) + 32
print(celsius, "degree Celsius =", fahrenheit, "Fahrenheit")
```
2. Here is program to check leap year:
```python
year = int(input("Enter year: "))
if (year%4==0 and year%100!=0) or year%400==0:
print(year, "is a Leap Year")
else:
print(year, "is not a Leap Year")
```
3. Here is a program for multiplication table with functions:
```python
"""Multiplication table program in Python"""
def print_table(num):
"""Function to print multiplication table"""
for i in range(1,11):
print(f"{num} x {i} = {num*i}")
num = int(input("Enter number: "))
print_table(num)
```
SECTION C
1. Exception handling allows us to handle errors and exceptions in Python instead of program
crashing. We use try, except and finally blocks to handle exceptions.
Example:
```python
try:
num = int(input("Enter a number: "))
print(100/num)
except ValueError:
print("Enter only integer value")
except ZeroDivisionError:
print("Cannot divide by zero")
```
2. A. Enumerate returns counter/index along with list item:
```python
l1 = ["A", "B", "C"]
for i, item in enumerate(l1):
print(i, item)
# 0A
#1B
#2C
```
B. Zip stiches elements of two lists:
```python
colors = ['red','blue']
values = [100, 50]
for color, val in zip(colors,values):
print(f"{color} - {val}")
# red - 100
# blue - 50
```
C. List comprehension for compact way to create lists:
```python
nums = [i*2 for i in range(10)]
print(nums)
# [0, 2, 4, 6 ... 16, 18]
```
3. Here is the program:
```python
L1 = [4,6,6,4,2,2,4,5,7,5,7]
result = {}
for x in L1:
if x not in result:
result[x] = [x]
else:
result[x].append(x)
print(result)
```
Output:
{2: [2, 2], 4: [4, 4, 4], 5: [5, 5], 6: [6, 6], 7: [7, 7]}
Download