Python Sem- Answer's
Python Sem- Answer's
● Low-Level Languages:
○ Machine Language: Consists of binary code directly understood by
the computer.
○ Assembly Language: A step above machine language, uses
human-readable mnemonics.
● High-Level Languages:
○ Procedural Languages (e.g., C, Fortran): Focus on sequences of
operations (functions).
○ Object-Oriented Languages (e.g., Java, Python): Organize code into
objects and classes.
○ Functional Languages (e.g., Haskell, Lisp): Focus on mathematical
functions and immutability.
○ Scripting Languages (e.g., Python, JavaScript): Often used for
automating tasks or web development.
● Compiler: Translates the entire program into machine code in one go,
which is then executed. Example: GCC for C.
● Interpreter: Translates the code line by line and executes it immediately,
without generating a separate machine code file. Example: Python
interpreter.
● Assembler: Translates assembly language into machine code.
1. Start
2. Input the value of n.
3. Initialize sum = 0.
4. For i = 1 to n, do:
○ sum = sum + i
5. Output sum.
6. End.
Algorithm:
1. Start
2. Input radius r.
3. Calculate area: area = π * r^2.
4. Calculate circumference: circumference = 2 * π * r.
5. Output area and circumference.
6. End.
Flowchart:
● Simple Syntax: Python is easy to read and write, making it a great choice
for beginners.
● Interpreted Language: Python code is executed line by line by the Python
interpreter.
● Object-Oriented: Python supports classes and objects for creating
reusable code.
● Dynamic Typing: Python automatically detects the type of variable, so
explicit type declarations are not needed.
● Extensive Standard Library: Python includes many built-in modules that
simplify complex tasks.
● Cross-platform: Python is available on various platforms like Windows,
Linux, and MacOS.
Example:
age = 25
name = "John"
In Python, you can assign values to multiple variables in a single line. This is
called multiple assignment.
Example:
x, y, z = 10, 20, 30
Error Errors are reported after Errors are reported line by line
Checking compilation during execution
Export to Sheets
3. Else largest = b
4. Output largest
Export to Sheets
● Flowchart Symbols:
○ Oval: Start/End
○ Rectangle: Process/Instruction
○ Diamond: Decision/Condition
○ Parallelogram: Input/Output
○ Arrow: Flow of control
● B. Algorithm and Flowchart for Area and Circumference of a circle:
○ Algorithm:
6. Features of Python:
(A neat sketch would show the .py file going into the compiler, producing
.pyc/.pyo, which then goes into the PVM for execution.)
8. Variables:
1. Programming Language
2. Language Translator
Types:
3. Compiler vs Interpreter
Compiler:
Interpreter:
Example:
Algorithm:
1. Initialize sum to 0.
2. For i from 1 to n, add i to sum.
3. Return sum.
5. Flowchart
Symbols:
● Oval: Start/End
● Rectangle: Process
● Diamond: Decision
● Parallelogram: Input/Output
Algorithm:
1. Input radius.
2. Calculate area as π * radius^2.
3. Calculate circumference as 2 * π * radius.
4. Output area and circumference.
Flowchart: (Not able to draw, but imagine a flow with input, process, and output
symbols connected sequentially.)
6. Features of Python
Definition: The PVM is the runtime engine of Python that executes the
bytecode.
Steps:
8. Variables in Python
Rules:
Example:
python
variable_name = 10
Comments:
Docstrings:
python
def example():
"""This is a docstring."""
pass
Multiple Assignment:
python
a, b, c = 1, 2, 3
Keywords:
● Predefined reserved words in Python like if, else, while, for, def.
Unit - 2
Here are detailed explanations and Python program solutions for the questions
provided:
Python has several built-in data types used to store data. Below are the primary
data types in Python:
● Numeric Types:
Arithmetic Operators:
● + : Addition (e.g., 5 + 3 = 8)
● - : Subtraction (e.g., 5 - 3 = 2)
● * : Multiplication (e.g., 5 * 3 = 15)
● / : Division (e.g., 5 / 3 = 1.666)
● // : Floor Division (e.g., 5 // 3 = 1)
● % : Modulus (remainder of division) (e.g., 5 % 3 = 2)
● ** : Exponentiation (e.g., 5 ** 3 = 125)
Relational Operators:
These operators compare two values and return a boolean result (True or
False).
Logical Operators:
● and : Returns True if both conditions are true (e.g., True and False →
False)
● or : Returns True if at least one condition is true (e.g., True or False
→ True)
● not : Returns the opposite of the condition (e.g., not True → False)
● & (AND): Sets each bit to 1 if both bits are 1. Example: 5 & 3 → 101 &
011 = 001 → Result is 1
● << (Left Shift): Shifts bits to the left by a specified number of positions.
Example: 5 << 1 → 0101 << 1 = 1010 → Result is 10
● >> (Right Shift): Shifts bits to the right by a specified number of positions.
Example: 5 >> 1 → 0101 >> 1 = 0010 → Result is 2
Identity Operators:
is : Returns True if two variables point to the same object in memory. Example:
x = [1, 2]
y=x
print(x is y) # True
is not : Returns True if two variables do not point to the same object.
Example:
x = [1, 2]
y = [1, 2]
print(x is not y) # True
Membership Operators:
These operators test if a value is found within a sequence (e.g., list, tuple,
string).
●
not in : Returns True if the value is not present in the sequence. Example:
lst = [1, 2, 3]
print(4 not in lst) # True
Syntax:
if condition:
# Code to execute if condition is True
else:
# Code to execute if condition is False
Example:
x = 10
if x > 5:
print("x is greater than 5")
else:
print("x is less than or equal to 5")
The else-if ladder is used to check multiple conditions. If the first if condition
is False, the elif condition is evaluated, and so on. If none of the conditions
are true, the else block is executed.
Syntax:
if condition1:
# Code if condition1 is true
elif condition2:
# Code if condition2 is true
else:
# Code if none of the above conditions are true
5. B. Write a Python program that finds the largest number among three
numbers.
num1 = int(input("Enter the first number: "))
num2 = int(input("Enter the second number: "))
num3 = int(input("Enter the third number: "))
A while loop in Python repeatedly executes a block of code as long as the given
condition is True.
Syntax:
while condition:
# Code to execute while condition is True
Example:
i=1
while i <= 5:
print(i)
i += 1
A for loop in Python is used to iterate over a sequence (such as a list, string, or
range). It executes the block of code for each item in the sequence.
Syntax:
Example:
A. break statement
Example:
if i == 3:
print(i)
Output:
Explanation: The loop starts at i = 1 and prints each number. When i becomes
3, the break statement is executed, and the loop stops, printing only 1 and 2.
B. continue statement
The continue statement is used to skip the current iteration of the loop and
proceed to the next iteration without executing the remaining code in the loop
for that iteration.
Example:
if i == 3:
print(i)
Output:
Explanation: The loop starts at i = 1 and prints each number. When i is 3, the
continue statement is executed, skipping the print statement for that
iteration, and the loop continues with i = 4 and i = 5.
Assertions in Python are used for debugging purposes. They are used to check
if a given condition is True. If the condition is False, the program raises an
AssertionError with an optional message. Assertions can help catch bugs in
code early by validating assumptions.
Syntax:
Example:
x=5
assert x < 0, "x should be less than 0" # This will raise AssertionError
Output:
The zip() function in Python is used to combine two or more iterables (like
lists, tuples) element-wise into tuples. The result is an iterator of tuples, where
each tuple contains one element from each of the input iterables.
Syntax:
Example:
Output:
Explanation: The zip() function pairs the elements of names and ages in
corresponding positions to create tuples, and then the loop prints each pair.
temp = num1
num1 = num2
num2 = temp
print("After swapping:")
print("After swapping:")
Explanation: In the first program, we use a temporary variable temp to hold the
value of num1 while we swap the values. In the second program, Python's
multiple assignment allows swapping without needing a temporary variable.
10. B. Write a Python program to check whether the given year is a leap
year or not.
A leap year occurs every 4 years, except for years that are divisible by 100 but
not divisible by 400.
Python program:
else:
Explanation:
Example:
● Numeric:
○ int: Integers (e.g., 10, -5, 0).
○ float: Floating-point numbers (e.g., 3.14, -2.5, 0.0).
○ complex: Complex numbers (e.g., 2 + 3j).
● Sequence:
○ str: Strings (e.g., "hello", 'Python'). Immutable.
○ list: Ordered, mutable sequences (e.g., [1, 2, "apple"]).
○ tuple: Ordered, immutable sequences (e.g., (1, 2, "apple")).
○ range: Generates a sequence of numbers (e.g., range(10)).
● Set: Unordered collections of unique elements (e.g., {1, 2, 3}). Mutable.
● Mapping:
○ dict: Dictionaries (key-value pairs) (e.g., {"name": "Alice", "age": 30}).
Mutable.
● Boolean:
○ bool: True or False.
2. Operators in Python:
4. if-else Statement:
Python
else:
Python
largest = num1
largest = num2
else:
largest = num3
6. while Loop:
Python
i=1
if num % i == 0:
print(i)
i += 1
7. for Loop:
if num > 1:
if num % i == 0:
break
else:
Python
# break example
if i == 3:
break
print(i) # Output: 1 2
# continue example
if i == 3:
continue
print(i) # Output: 1 2 4 5
Python
return x / y
Python
# Output:
● A. Swapping Numbers:
Python
a = 10
b = 20
temp = a
a=b
b = temp
a = 10
b = 20
a, b = b, a # Pythonic swap
def is_leap_year(year):
return True
return False
if is_leap_year(year):
else:
●
list: Ordered sequence of elements.
python
d = [1, 2, 3]
2. Operators in Python
● Arithmetic Operators:
○ Addition: +
○ Subtraction: -
○ Multiplication: *
○ Division: /
Example:
python
a = 10
b=5
c = a + b # 15
○
● Relational Operators:
○ Equal to: ==
○ Not equal to: !=
○ Greater than: >
○ Less than: <
Example:
python
a = 10
b=5
○
● Logical Operators:
○ And: and
○ Or: or
○ Not: not
Example:
python
a = True
b = False
3. Operators
● A. Bitwise Operators:
○ AND: &
○ OR: |
○ XOR: ^
○ NOT: ~
Example:
python
a = 5 # 0101 in binary
b = 3 # 0011 in binary
○
● B. Identity and Membership Operators:
○ Identity Operators:
■ is
■ is not
Example:
python
a = [1, 2, 3]
b = [1, 2, 3]
print(a is b) # False
■
○ Membership Operators:
■ in
■ not in
Example:
python
a = [1, 2, 3]
print(1 in a) # True
4. Control Statements
A. if-else Statement:
python
a = 10
if a > 5:
print("Greater")
else:
print("Lesser")
b = 20
if a > b:
largest = a
else:
largest = b
print("Largest:", largest)
5. else-if Ladder
if a == 10:
print("Equal to 10")
else:
●
B. Python Program to Find Largest Number Among 3 Numbers:
python
a = 10
b = 20
c = 15
largest = a
largest = b
else:
largest = c
print("Largest:", largest)
6. while Statement
while i <= 5:
print(i)
i += 1
if num % i == 0:
print(i)
7. for Statement
print(i)
is_prime = True
if num % i == 0:
is_prime = False
break
if is_prime:
else:
A. break Statement:
python
for i in range(10):
if i == 5:
break
print(i)
B. continue Statement:
python
for i in range(10):
if i == 5:
continue
print(i)
A. Assertions:
python
assert 2 + 2 == 4 # This will pass
B. zip() Function:
python
a = [1, 2, 3]
zipped = zip(a, b)
b = 10
temp = a
a=b
b = temp
a, b = b, a
print(a, b)
else:
Here are detailed explanations and examples for each of your requested topics:
Indexing: Strings in Python are indexed starting from 0. You can access a
character at a specific index using square brackets.
Example:
my_string = "Hello"
Slicing: You can extract a portion of the string using slicing with the syntax
string[start:end]. The start index is included, but the end index is not.
Example:
A. replace()
Example:
Example:
text = "hello"
D. find()
The find() method returns the index of the first occurrence of the specified
substring. If the substring is not found, it returns -1.
Example:
print(text.find("World")) # Output: 7
print(text.find("Python")) # Output: -1
A. lower()
Example:
text = "HELLO"
B. join()
The join() method is used to join a sequence of strings using a specified
delimiter.
Example:
D. partition()
The partition() method splits the string into a tuple of three parts: the
substring before the separator, the separator itself, and the substring after the
separator.
Example:
result = text.partition(",")
Creating a List: A list can be created by placing elements inside square brackets
[].
Example:
my_list = [1, 2, 3, 4, 5]
Indexing: Lists are indexed starting from 0. You can access elements using the
index.
Example:
print(my_list[2]) # Output: 30
Slicing: You can slice a list to extract a part of it using the syntax
list[start:end].
Example:
A. insert()
The insert() method is used to add an element at a specific index in the list.
Example:
my_list = [1, 2, 3]
B. clear()
Example:
my_list = [1, 2, 3]
my_list.clear()
print(my_list) # Output: []
C. pop()
The pop() method removes and returns the element at a specified index. If no
index is provided, it removes the last element.
Example:
my_list = [1, 2, 3]
print(popped_item) # Output: 2
D. sort()
The sort() method sorts the list in ascending order by default. You can specify
the reverse=True argument to sort in descending order.
Example:
my_list = [3, 1, 2, 4]
my_list.sort()
Example:
my_tuple = (1, 2, 3)
Indexing: Tuples are indexed starting from 0. You can access tuple elements
using the index.
Example:
print(my_tuple[1]) # Output: 20
Slicing: You can slice a tuple to extract a portion of it using the syntax
tuple[start:end].
Example:
Properties of a Tuple:
Example:
# count() example
print(my_tuple.count(20)) # Output: 2
# index() example
print(my_tuple.index(30)) # Output: 2
Properties of a Set:
Example:
my_set = {1, 2, 3}
# add() example
my_set.add(4)
# remove() example
my_set.remove(3)
# discard() example
my_set.discard(2)
A. union()
The union() method returns a new set containing all the elements from both
sets, excluding duplicates.
Example:
set1 = {1, 2, 3}
set2 = {3, 4, 5}
result = set1.union(set2)
B. intersection()
The intersection() method returns a new set containing only the common
elements from both sets.
Example:
set1 = {1, 2, 3}
set2 = {3, 4, 5}
result = set1.intersection(set2)
C. difference()
The difference() method returns a new set containing elements in the first
set that are not in the second set.
Example:
set1 = {1, 2, 3}
set2 = {3, 4, 5}
result = set1.difference(set2)
D. isdisjoint()
set1 = {1, 2, 3}
set2 = {4, 5, 6}
● Creation: Strings are created using single quotes ('...'), double quotes
("..."), or triple quotes ('''...''' or """...""" for multi-line
strings).
○ my_string = "Hello, Python!"
● Indexing: Accessing individual characters using their position (index),
starting from 0.
○ my_string[0] (returns 'H')
○ my_string[7] (returns 'P')
○ my_string[-1] (returns '!') (negative indexing starts from the end)
● Slicing: Extracting a substring.
○ my_string[0:5] (returns 'Hello') (from index 0 up to, but not
including, index 5)
○ my_string[7:] (returns 'Python!') (from index 7 to the end)
○ my_string[:5] (returns 'Hello') (from the beginning up to index 5)
○ my_string[::2] (returns 'Hlo Pto!') (every second character)
○ my_string[::-1] (returns '!nohtyP ,olleH') (reverses the string)
● A. union(): Returns a new set containing all elements from both sets.
○ set1 = {1, 2, 3}
○ set2 = {3, 4, 5}
○ set1.union(set2) (returns {1, 2, 3, 4, 5})
● B. intersection(): Returns a new set containing common elements.
○ set1.intersection(set2) (returns {3})
● C. difference(): Returns a new set containing elements in the first set
but not in the second set.
○ set1.difference(set2) (returns {1, 2})
● D. isdisjoint(): Returns True if the sets have no elements in common.
○ set1.isdisjoint({4, 5}) (returns True)
○ set1.isdisjoint(set2) (returns False)
Creating:
python
my_string = "Hello, World!"
Indexing:
python
first_char = my_string[0] # 'H'
Slicing:
python
slice_example = my_string[0:5] # 'Hello'
2. String Methods
A. replace():
python
my_string = "Hello, World!"
●
B. upper():
python
my_string = "Hello, World!"
upper_string = my_string.upper()
D. find():
python
my_string = "Hello, World!"
position = my_string.find("World")
print(position) # 7
A. lower():
python
my_string = "HELLO, WORLD!"
lower_string = my_string.lower()
B. join():
python
my_list = ["Hello", "World"]
●
D. partition():
python
my_string = "Hello, World!"
Creating:
python
my_list = [1, 2, 3, 4, 5]
Indexing:
python
first_element = my_list[0] # 1
Slicing:
python
slice_example = my_list[1:4] # [2, 3, 4]
5. List Methods
A. insert():
python
my_list = [1, 2, 4, 5]
my_list.insert(2, 3)
print(my_list) # [1, 2, 3, 4, 5]
●
B. clear():
python
my_list = [1, 2, 3, 4, 5]
my_list.clear()
print(my_list) # []
C. pop():
python
my_list = [1, 2, 3, 4, 5]
popped_element = my_list.pop()
print(popped_element) # 5
D. sort():
python
my_list = [3, 1, 4, 2, 5]
my_list.sort()
print(my_list) # [1, 2, 3, 4, 5]
Creating:
python
my_tuple = (1, 2, 3, 4, 5)
Indexing:
python
first_element = my_tuple[0] # 1
●
Slicing:
python
slice_example = my_tuple[1:4] # (2, 3, 4)
● A. Tuple Properties:
○ Immutable: Once created, elements cannot be changed.
○ Ordered: Maintains the order of elements.
count_2 = my_tuple.count(2) # 3
index_2 = my_tuple.index(2) # 1
print(count_2, index_2)
● A. Set Properties:
○ Unordered: Does not maintain order of elements.
○ No duplicates: Each element is unique.
my_set.add(4)
print(my_set) # {1, 2, 3, 4}
my_set.remove(3)
print(my_set) # {1, 2, 4}
my_set.discard(2)
print(my_set) # {1, 4}
9. Set Methods
A. union():
python
set1 = {1, 2, 3}
set2 = {3, 4, 5}
union_set = set1.union(set2)
print(union_set) # {1, 2, 3, 4, 5}
B. intersection():
python
set1 = {1, 2, 3}
set2 = {3, 4, 5}
intersection_set = set1.intersection(set2)
print(intersection_set) # {3}
C. difference():
python
set1 = {1, 2, 3}
set2 = {3, 4, 5}
difference_set = set1.difference(set2)
print(difference_set) # {1, 2}
●
D. isdisjoint():
python
set1 = {1, 2, 3}
set2 = {4, 5, 6}
is_disjoint = set1.isdisjoint(set2)
print(is_disjoint) # True
Syntax [] ()
UNIT - 4
1. A. Define Dictionary. Explain about creating dictionary and accessing
elements of dictionary in Python.
Example:
Accessing Elements: You can access dictionary elements by using the keys in
square brackets [] or by using the get() method.
Example:
print(my_dict.get("age")) # Output: 25
Adding Items: You can add new key-value pairs by assigning a value to a new
key.
Example:
my_dict["profession"] = "Engineer"
print(my_dict) # Output: {'name': 'Alice', 'age': 25, 'city': 'New York', 'profession':
'Engineer'}
Removing Items: You can remove an item using del or the pop() method.
Example:
del my_dict["age"]
removed_item = my_dict.pop("city")
Updating Items: You can update an existing key's value by assigning a new value
to it.
Example:
my_dict["age"] = 30
A. keys()
The keys() method returns a view object that displays a list of all the keys in
the dictionary.
Example:
my_dict = {"name": "Alice", "age": 25}
B. values()
The values() method returns a view object that displays all the values in the
dictionary.
Example:
C. copy()
Example:
new_dict = my_dict.copy()
D. fromkeys()
The fromkeys() method creates a new dictionary with the specified keys and
sets the values to a default value (None by default).
Example:
new_dict = dict.fromkeys(keys, 0)
A. get()
The get() method returns the value for a specified key. If the key does not
exist, it returns None (or a specified default value).
Example:
B. popitem()
The popitem() method removes and returns an arbitrary (key, value) pair from
the dictionary.
Example:
item = my_dict.popitem()
C. setdefault()
The setdefault() method returns the value of a key if it exists. If the key does
not exist, it adds the key with the specified default value.
Example:
D. update()
The update() method updates the dictionary with elements from another
dictionary or iterable.
Example:
my_dict.update({"city": "New York", "age": 30}) # Updates the 'age' key and adds
a new key 'city'
Example:
def greet(name):
print(f"Hello, {name}!")
def sum_of_natural_numbers(n):
Example:
Example:
print(f"Hello {name}")
Example:
def greet(name):
print(f"Hello {name}")
func(name)
call_function(greet, "Alice")
Example:
def factorial(n):
if n == 1:
return 1
else:
return n * factorial(n - 1)
def fibonacci(n):
a, b = 0, 1
for _ in range(n):
a, b = b, a + b
fibonacci(10) # Output: 0 1 1 2 3 5 8 13 21 34
B. Using recursion:
if n > 0:
fibonacci_recursive(n -
1, b, a + b)
fibonacci_recursive(10) # Output: 0 1 1 2 3 5 8 13 21 34
---
### 10. **With an example, explain lambda with filter(), map(), and reduce()
functions.**
- **Lambda:**
**Example:**
```python
numbers = [1, 2, 3, 4, 5, 6]
1. Dictionaries:
Python
Python
print(my_dict["age"]) # Output: 30
Python
print(my_dict) #Output: {'name': 'Alice', 'age': 31, 'city': 'New York', 'country':
'USA'}
● A. keys(): Returns a view object that displays a list of all the keys in the
dictionary.
Python
● B. values(): Returns a view object that displays a list of all the values in
the dictionary.
Python
Python
new_dict = my_dict.copy()
● A. get(): Returns the value for a given key. If the key is not present, it
returns a default value (or None if no default is specified).
Python
● B. popitem(): Removes and returns a (key, value) pair. Pairs are returned
in LIFO (Last In, First Out) order.
Python
Python
Python
print(my_dict) #Output: {'name': 'Alice', 'city': 'London', 'age': 32, 'country': 'UK'}
5. Functions:
Python
print(f"Hello, {name}!")
Python
def sum_natural_numbers(n):
sum = 0
sum += i
return sum
if num < 0:
else:
result = sum_natural_numbers(num)
Python
def greet(name="Guest"):
print(f"Hello, {name}!")
Python
Python
def print_numbers(*args):
print(num)
print_numbers(1, 2, 3, 4, 5)
Python
def print_info(**kwargs):
print(f"{key}: {value}")
Python
return func(x, y)
return x + y
print(result) # Output: 8
Python
def get_double(x):
return 2 * x
value = get_double(5)
print(value) #Output: 10
def print_message(message):
print(message)
print(print_message("Hello")) #Output: Hello \n None
Python
def factorial(n):
if n == 0:
return 1
else:
return n * factorial(n - 1)
● Fibonacci Series:
○ A) Without Recursion:
Python
def fibonacci_non_recursive(n):
a, b = 0, 1
series = []
for _ in range(n):
series.append(a)
a, b = b, a + b
return series
print(fibonacci_non_recursive(10))
Python
def fibonacci_recursive(n):
if n <= 1:
return n
else:
def fibonacci_series_recursive(n):
series = []
for i in range(n):
series.append(fibonacci_recursive(i))
return series
print(fibonacci_series_recursive(10))
Lambda Functions:
Examples:
Python
add = lambda x, y: x + y
print(square(4)) # Output: 16
filter():
The filter() function filters a sequence based on a given function (which can
be a lambda function). It returns an iterator containing the elements for which
the function returns True.
filter(function, iterable)
Example:
Python
map():
The map() function applies a given function (which can be a lambda function) to
all items in an input iterable. It returns an iterator that yields the results.
Example:
Python
numbers = [1, 2, 3, 4, 5]
numbers1 = [1, 2, 3]
numbers2 = [4, 5, 6]
The reduce() function (from the functools module) applies a function of two
arguments cumulatively to the items of a sequence, from left to right, so as to
reduce the sequence to a single value.
Example:
Python
numbers = [1, 2, 3, 4, 5]
print(sum_of_numbers) #Output: 15
print(largest_number) #Output: 5
Key Differences and Use Cases:
Lambda functions are particularly useful when you need a small function for a
short period, often as an argument to higher-order functions like filter(),
map(), and reduce(). They make the code more concise and readable in these
situations.
1. Dictionary in Python
Creating a Dictionary:
python
Accessing Elements:
python
Adding:
python
my_dict["email"] = "[email protected]"
print(my_dict)
●
Removing:
python
my_dict.pop("age")
print(my_dict)
Updating:
python
my_dict["city"] = "Los Angeles"
print(my_dict)
2. Dictionary Methods
A. keys():
python
print(my_dict.keys()) # Output: dict_keys(['name', 'city', 'email'])
B. values():
python
print(my_dict.values()) # Output: dict_values(['Alice', 'Los Angeles',
'[email protected]'])
C. copy():
python
new_dict = my_dict.copy()
print(new_dict)
D. fromkeys():
python
keys = ["name", "age", "city"]
new_dict = dict.fromkeys(keys, "Unknown")
A. get():
python
name = my_dict.get("name")
B. popitem():
python
item = my_dict.popitem()
C. setdefault():
python
age = my_dict.setdefault("age", 30)
print(my_dict)
D. update():
python
my_dict.update({"name": "Bob", "country": "USA"})
print(my_dict)
4. Functions in Python
A. Definition and Creation: A function is a block of code that performs a specific
task. Functions help organize code and make it reusable.
python
def greet(name):
python
def sum_of_n_numbers(n):
return n * (n + 1) // 2
n = 10
Default Arguments:
python
Keyword Arguments:
python
6. Arguments in Python
Positional Arguments:
python
def greet(name, message):
print(f"Hello, {name}!")
print(f"{key}: {value}")
7. Function as an Argument
Example:
python
return x + y
return func(a, b)
result = apply_func(add, 5, 3)
print(result) # Output: 8
8. Recursion
python
def factorial(n):
if n == 1:
return 1
else:
return n * factorial(n - 1)
Fibonacci Series:
Without Recursion:
python
def fibonacci(n):
a, b = 0, 1
for _ in range(n):
a, b = b, a + b
fibonacci(10)
With Recursion:
python
def fibonacci(n):
if n <= 1:
return n
else:
for i in range(10):
python
numbers = [1, 2, 3, 4, 5]
python
python
print(sum_numbers) # Output: 15
UNIT - 5
1. Explain about creating class, object and accessing of class members
with example.
● Accessing Class Members: You can access class members (both attributes
and methods) using the dot (.) operator.
Example:
class Car:
self.make = make
self.model = model
def display(self):
Example:
class Person:
self.name = name
self.age = age
# Creating an object
print(person1.age) # Output: 30
3. What is inheritance? Explain different types of inheritance with
example.
● Types of Inheritance:
Example:
# Single Inheritance
class Animal:
def speak(self):
print("Animal speaks")
class Dog(Animal):
def bark(self):
print("Dog barks")
dog = Dog()
class Shape(ABC):
@abstractmethod
def area(self):
pass
class Circle(Shape):
def area(self):
return 3.14 * self.__radius * self.__radius
circle = Circle(5)
● Types of Errors:
1. Syntax Errors: Occur when the code violates Python's syntax rules.
2. Runtime Errors: Occur during the execution of the program (e.g.,
division by zero).
3. Logical Errors: Occur when the program runs but produces
incorrect results due to faulty logic.
Example:
try:
result = 10 / num
except ZeroDivisionError:
print("Cannot divide by zero!")
except ValueError:
else:
finally:
print("Execution completed.")
try:
print(f"Error: {e}")
else:
try:
except ValueError:
except ZeroDivisionError:
else:
try:
content = file.read()
except Exception as e:
try:
except ZeroDivisionError:
else:
finally:
print("Execution completed.")
9. B. Write a Python program to create a new file and add the given text
to the file.
● seek(): The seek() method is used to move the file pointer to a specific
position within the file. It takes two arguments: offset (the number of
bytes to move) and whence (where to start from, default is the beginning
of the file).
● tell(): The tell() method returns the current position of the file pointer.
Example:
10. B. Write a Python program to add the contents into an existing file
and display the contents of a file from the specified position.
file.write("\nAppended text.")
file.seek(10)
Python
class Dog:
self.name = name
self.breed = breed
def bark(self):
print("Woof!")
Python
● Accessing Class Members: Access attributes and call methods using the
dot operator (.).
Python
Python
class Car:
self.make = make
self.model = model
self.year = year
self.mileage = 0
self.mileage += miles
3. Inheritance:
Python
class Animal:
def eat(self):
print("Eating...")
def meow(self):
print("Meow!")
my_cat = Cat()
Python
class Swimmer:
def swim(self):
print("Swimming...")
class Walker:
def walk(self):
print("Walking...")
class Duck(Swimmer, Walker): #Duck inherits from both Swimmer and Walker
pass
my_duck = Duck()
Python
class Grandparent:
def grandparent_method(self):
print("Grandparent method")
class Parent(Grandparent):
def parent_method(self):
print("Parent method")
class Child(Parent):
def child_method(self):
print("Child method")
my_child = Child()
Python
class BankAccount:
self.__balance += amount
return self.__balance
my_account = BankAccount(1000)
my_account.deposit(500)
6. Exception Handling:
Python
try:
result = 10 / 0
except ZeroDivisionError:
except TypeError:
print("Type mismatch")
● A. At a Time:
Python
try:
x = int("abc")
result = 10 / 0
Python
try:
x = int("abc")
except ValueError:
try:
result = 10/0
except ZeroDivisionError:
Python
try:
Python
try:
f = open("my_file.txt", "r")
content = f.read()
except FileNotFoundError:
f.close()
try:
except Exception as e:
Python
try:
content_from_position = f.read()
print(content_from_position)
except FileNotFoundError:
print("File not found.")
except Exception as e:
python
class Dog:
self.name = name
self.age = age
def bark(self):
# Creating an object
my_dog = Dog("Buddy", 3)
● Attributes: my_dog.name
● Methods: my_dog.bark()
__init__() Method:
python
class Dog:
self.name = name
self.age = age
def bark(self):
my_dog = Dog("Buddy", 3)
3. Inheritance
Types of Inheritance:
return "Eating"
class Dog(Animal):
def bark(self):
return "Barking"
my_dog = Dog()
def eat(self):
return "Eating"
class Pet:
def play(self):
return "Playing"
pass
my_dog = Dog()
def eat(self):
return "Eating"
class Dog(Animal):
def bark(self):
return "Barking"
class Puppy(Dog):
def play(self):
return "Playing"
my_puppy = Puppy()
Encapsulation: Bundling data and methods within a class and restricting access
to some components.
Example:
python
class Person:
self.__name = name
self.__age = age
def get_name(self):
return self.__name
if age > 0:
self.__age = age
person.set_age(30)
5. Types of Errors
Types of Errors:
● Syntax Errors: Errors in the code structure.
● Runtime Errors: Errors that occur during execution.
● Logical Errors: Errors in the logic that lead to incorrect results.
python
try:
result = 10 / 0
except ZeroDivisionError:
python
try:
result = a / b
print("Error:", e)
python
try:
a = int(input("Enter a number: "))
result = a / b
except ValueError:
print("Invalid input")
except ZeroDivisionError:
python
try:
result = 10 / 0
except Exception as e:
python
try:
result = a / b
except ZeroDivisionError:
print("Cannot divide by zero")
else:
print("Result:", result)
finally:
print("Execution completed")
9. Files in Python
python
file.write("Hello, World!")
file.seek(5)
●
tell(): Returns the current position of the cursor.
python
with open("example.txt", "r") as file:
python
# Adding content
file.seek(5)
RUDRANSH