Python Programming Important Questions
Python Programming Important Questions
Unit-1
Section-A
Ques. Short Answer Type Questions Marks
No.
1. Differentiate between / and // operator with an example. 2
// is the floor division operator that returns the largest integer less than or equal
to the result.
# Unpacking tuple
t = (1, 2, 3)
a, b, c = t
print(a, b, c)
# String concatenation
s1 = "Hello"
s2 = "World"
print(s1 + " " + s2)
3. Define operators in Python. 2
Operators are special symbols that perform operations on variables and values.
Example categories:
Arithmetic: +, -, *, /
Relational: ==, !=, >, <
Logical: and, or, not
a=5
b=3
sum = a + b
print("Sum:", sum)
5. Explain any five features of Python. 2
Interpreted Language
Dynamically Typed
Extensive Libraries
Object-Oriented
import math
print([Link](16)) # Output: 4.0
8. Define floor division with an example. 2
print(9 // 2) # Output: 4
9. Explain the difference between append and extend in Python. 2
lst = [1, 2]
[Link]([3, 4]) # [1, 2, [3, 4]]
[Link]([5, 6]) # [1, 2, [3, 4], 5, 6]
10. Differentiate between Python arrays and lists. 2
import array
arr = [Link]('i', [1, 2, 3])
11. What is a dictionary in Python? 2
p = Person("Alice")
print([Link])
13. Difference between is and == operators. 2
a = [1, 2]
b = [1, 2]
print(a == b) # True
print(a is b) # False
14. Convert character to ASCII and vice versa. 2
ch = 'A'
print(ord(ch)) # Output: 65
code = 65
print(chr(code)) # Output: A
15. Explain split() and join() with example. 2
s = "a,b,c"
lst = [Link](",") # ['a', 'b', 'c']
new_s = ",".join(lst) # 'a,b,c'
16. Why is Python called a dynamic and strongly typed language?
Dynamic typing:
x = 5 # x is an integer
x = "Hi" # Now x is a string
Strong typing:
Even though types are dynamic, Python does not implicitly convert
incompatible types.
If you try to mix incompatible types, you get an error.
Example:
x = 5 # integer
x = "hello" # now a string
18. Write a for loop that prints numbers from 0 to 57 using range().
19.
Demonstrate how to assign a single value to a tuple
When creating a tuple with only one element, you must add a comma; otherwise,
Python treats it as the value itself in parentheses (not a tuple).
\
not_a_tuple = (5)
print(type(not_a_tuple)) # <class 'int'>
Explanation:
The comma tells Python: this is a tuple, even if it has only one element.
Section-B
Ques. Long Answer Type Questions Marks
No.
1. Explain the role of precedence with an example. (7 marks) 7
Solution
The concept of operator precedence and associativity in C helps in determining
which operators will be given priority when there are multiple operators in the
expression. It is very common to have multiple operators in python Language and
the compiler first evaluates the operator with higher precedence. It helps to
maintain the ambiguity of the expression and helps us in avoiding unnecessary use
of parenthesis.
In this article, we will discuss operator precedence, operator associativity, and
precedence table according to which the priority of the operators in expression is
decided in Python language.
Operator Precedence and Associativity Table
The following tables list the C operator precedence from highest to lowest and the
associativity for each of the operators:
Operator
. Dot Operator
-> Structure Pointer Operator
* Dereference Operator
12 || Logical OR Left-to-Right
13 ?: Ternary conditional Right-to-Left
= Assignment
Ans- A loop is a control flow statement in Python that allows you to execute a piece
of code repeatedly until a specific condition is met. Loops are necessary for
operations that require repetitive execution, such as iterating through a Python list
of items or doing calculations many times.
For loop
A for loop is a control flow statement in Python that allows you to iterate over a
sequence of elements such as a list, tuple, or string.
On each iteration, the loop variable in Python will take on the value of the next
item in the sequence.
Syntax of Python for loop
for iterating_var in sequence:
statements(s)
Program of for loop
for i in range(0,10):
print(i,end='\t')
While loop
A while loop is a control flow statement that allows you to execute a block of code
repeatedly while a given condition is true.
The condition is evaluated at the start of each loop iteration, and if it is true, the loop
body is
4. Demonstrate five different built in functions used in the string. Write a program 7
to check whether a string is a palindrome or not. (7 marks)
Ans- 1. Capitalize Function: [Link]()
The capitalize() function returns the first character of a string as an uppercase
letter and the rest of the characters as lowercase letters.
Program
mystatement = "welcome to hubspot"
myvalue = [Link]()
print(myvalue)
2. Split Function: split()
The split() function breaks bigger strings into smaller strings by splitting a string
into a list.
Program
statement = "python is fun and easy"
myvalue = [Link]()
print(myvalue)
3. Strip Function: strip()
The strip() function or method removes all of the leading and trailing characters
from a string.
Program
mystatement = ' Removes all the unnecessary spaces '
print([Link]())
4. Uppercase Function: upper()
The uppercase or upper() function converts all of the letters in a string to
uppercase.
Program
mystatement = 'welcome to hubspot'
print([Link]())
5. Join Function: join()
The join() function returns a string by joining all items in an iterable together.
5. 7
Design a basic calculator in Python that supports addition,
subtraction, multiplication, and division
def calculator(a, b, operation):
if operation == '+':
return a + b
elif operation == '-':
return a - b
elif operation == '*':
return a * b
elif operation == '/':
if b != 0:
return a / b
else:
return "Error: Division by zero!"
else:
return "Invalid operation."
# Example usage
num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))
op = input("Enter operation (+, -, *, /): ")
6. 7
Write short notes
result = (2 + 3) * 4 # Evaluates as 5 * 4 = 20
(b) Python Indentation
if True:
print("Indented block") # This line is part of the if
block
print("Outside block") # No indentation
x = 5
y = 2.0
result = x + y # result is 7.0 (int converted to float)
s = "123"
num = int(s) # Converts string to integer
f = float("3.14") # Converts string to float
7. 7
Write a program to validate an email address using regular
expressions
Requirements:
Must contain @
Must have domain name
Should not have spaces
import re
def validate_email(email):
pattern = r'^[^\s@]+@[^\s@]+\.[^\s@]+$'
if [Link](pattern, email):
return "Valid email address."
else:
return "Invalid email address."
# Example usage
email_input = input("Enter email address: ")
print(validate_email(email_input))
def removenth(s,n):
if n>=0 and n<len(s):
return s[:n]+s[n+1:]
return s
print(removenth("MANGO",1)) # MNGO
print(removenth("MANGO",3)) # MANO
9. Construct a program that accepts a comma separated sequence of words as 7
input
and prints the words in a comma-separated sequence after sorting them
alphabetically.
Suppose the following input is supplied to the program:
without, hello, bag, world
Then, the output should be:
bag, hello, without, world
import re
valid = []
for pwd in passwords:
pwd = [Link]()
if (6 <= len(pwd) <= 12 and
[Link]("[a-z]", pwd) and
[Link]("[A-Z]", pwd) and
[Link]("[0-9]", pwd) and
[Link]("[$#@]", pwd)):
[Link](pwd)
print(",".join(valid))
11. Write a Python Program to find the LCM of two numbers.
while True:
if (greater % x == 0) and (greater % y == 0):
lcm = greater
break
greater += 1
return lcm
# Example usage
num1 = int(input("Enter first number: "))
num2 = int(input("Enter second number: "))
Binary Search requires a sorted list. It works by repeatedly dividing the search
interval in half.
# Example usage
numbers = [1, 3, 5, 7, 9, 11]
result = binary_search(numbers, 7)
if result != -1:
print("Element found at index:", result)
else:
print("Element not found")
13. 7
Write short notes
✅Implicit Conversion:
Python automatically converts types where safe.
x = 5
y = 2.0
result = x + y # 7.0 (int converted to float)
✅Explicit Conversion:
You manually convert types using functions.
s = "123"
num = int(s)
f = float("3.14")
14. 7
Program to Check if a Year is a Leap Year
Divisible by 4
Not divisible by 100, unless divisible by 400
15. 7
Discuss Exceptions and Assertions in Python
Exceptions:
Example:
try:
x = 10 / 0
except ZeroDivisionError:
print("Cannot divide by zero.")
Assertions:
Example:
x = 5
assert x > 0, "x must be positive"
✅Two built-in exceptions:
1 / 0 # Raises ZeroDivisionError
2. ValueError: Raised when a function gets an argument of the right type but
inappropriate value.
16. 7
Implement Selection Sort in Python
Selection Sort:
def selection_sort(arr):
n = len(arr)
for i in range(n):
min_idx = i
for j in range(i+1, n):
if arr[j] < arr[min_idx]:
min_idx = j
arr[i], arr[min_idx] = arr[min_idx], arr[i]
# Example usage
data = [64, 25, 12, 22, 11]
selection_sort(data)
print("Sorted array:", data)
17. 7
Different Types of Inheritance in Python
1. Single Inheritance
o One child class inherits from one parent class.
class Parent:
pass
class Child(Parent):
pass
2. Multiple Inheritance
o Child class inherits from multiple parent classes.
python
CopyEdit
class Parent1:
pass
class Parent2:
pass
class Child(Parent1, Parent2):
pass
3. Multilevel Inheritance
o Inheritance chain.
class Grandparent:
pass
class Parent(Grandparent):
pass
class Child(Parent):
pass
4. Hierarchical Inheritance
o Multiple child classes inherit from the same parent.
class Parent:
pass
class Child1(Parent):
pass
class Child2(Parent):
pass
5. Hybrid Inheritance
o Combination of multiple types.
Unit-2
Section-A
Ques. Short Answer Type Questions Marks
No.
20. Describe the behavior of range(start, stop) in Python. 2
def count(s):
for str in [Link]():
s = "&".join(str)
return s
import numpy as np
print([Link](0,1,5)) # [0. 0.25 0.5 0.75 1. ]
print([Link](0,1,0.2)) # [0. 0.2 0.4 0.6 0.8]
print(chr(65)) # Output: A
27. Can you use else with a for loop? If so, when is it executed? 2
Yes, the else block executes if the loop completes normally without a break.
Example:
for i in range(3):
print(i)
else:
print("Loop completed")
s = "apple,banana,orange"
print([Link](",")) # ['apple','banana','orange']
pass statement:
Example:
def my_function():
pass # Placeholder, function does nothing
Comment:
Example:
# This is a comment
Difference:
Ans- A loop is a control flow statement in Python that allows you to execute a piece
of code repeatedly until a specific condition is met. Loops are necessary for
operations that require repetitive execution, such as iterating through a Python list
of items or doing calculations many times.
For loop
A for loop is a control flow statement in Python that allows you to iterate over a
sequence of elements such as a list, tuple, or string.
On each iteration, the loop variable in Python will take on the value of the next
item in the sequence.
Syntax of Python for loop
for iterating_var in sequence:
statements(s)
Program of for loop
for i in range(0,10):
print(i,end='\t')
While loop
A while loop is a control flow statement that allows you to execute a block of code
repeatedly while a given condition is true.
The condition is evaluated at the start of each loop iteration, and if it is true, the loop body
is
19. Explain the continue, break, and pass statements with a suitable example. (7 7
marks)
Ans- Loops iterate over a block of code until the test expression is false, but
sometimes it need to terminate the current iteration or even the whole loop
without checking the test expression.
This can be achieved using a few keywords that can alter the flow or execution of
the loops. In Python those keywords are — break, continue and pass.
Continue
The continue statement is used to skip the remaining code inside a loop for the
current iteration only.
Program
for num in range(0,10):
if num == 5:
continue
print('Iteration',num)
Break
The break statement in Python terminates the loop containing it.
Program
for num in range(0,10):
if num == 5:
break
print('Iteration',num)
20. Develop a program to calculate the reverse of any entered number. 7
Ans-
num = 1234
reversed_num = 0
while num != 0:
digit = num % 10
reversed_num = reversed_num * 10 + digit
num=num//10
print("Reversed Number: " + str(reversed_num))
21. Write structure of if else statement in python.(7 marks) 7
Ans -Python Conditions and If statements
Python supports the usual logical conditions from mathematics:
1. Equals: a == b
2. Not Equals: a != b
3. Less than: a < b
4. Less than or equal to: a <= b
5. Greater than: a > b
6. Greater than or equal to: a >= b
These conditions can be used in several ways, most commonly in "if statements"
and loops.
An "if statement" is written by using the if keyword.
Indentation
Python relies on indentation (whitespace at the beginning of a line) to define
scope in the code. Other programming languages often use
curly-brackets for this purpose.
If statement, without indentation (will raise an error):
a = 33 b = 200 if b > a: print("b is greater than a") # you will get an error
Elif
The elif keyword is Python's way of saying "if the previous conditions were not
true, then try this condition".
Example
a = 33 b = 33 if b > a: print("b is greater than a") elif a == b: print("a and b are
equal")
In this example a is equal to b, so the first condition is not true, but the elif
condition is true, so we print to screen that "a and b are equal".
Else
The else keyword catches anything which isn't caught by the preceding conditions.
Example
a = 200 b = 33
if b > a: print("b is greater than a")
elif a == b: print("a and b are equal")
else: print("a is greater than b")
In this example a is greater than b, so the first condition is not
true, also the elif condition is not true, so we go to the else
condition and print to screen that "a is greater than b".
You can also have an else without the elif:
Example
a = 200 b = 33 if b > a: print("b is greater than a") else: print("b
is not greater than a")
Short Hand If
If you have only one statement to execute, you can put it on the
same line as the if statement.
Example
One line if statement:
if a > b: print("a is greater than b")
Short Hand If ... Else
If you have only one statement to execute, one for if, and one for
else, you can put it all on the same line:
Example
One line if else statement:
a = 2 b = 330 print("A") if a > b else print("B")
This technique is known as Ternary Operators, or Conditional
Expressions.
that can be solved recursively, until the base case isreached and the function
returns a value. Recursion can be used tosolve a wide variety of problems,
including searching and sortingalgorithms, data structure traversal and
mathematical [Link] both iterators and recursion can be used to solve
many of thesame problems, they are fundamentally different in their
[Link] focus on sequentially processing a collection of data,
whilerecursion focuses on breaking down a larger problem into smaller
def Fibonacci(n):
if n < 0:
print("Incorrect input")
elif n == 0:
return 0
elif n == 1 or n == 2:
return 1
else:
return Fibonacci(n-1) + Fibonacci(n-2)
for i in range(9):
print(Fibonacci(i),end=" ")
23. Explore the working of while and for loops with examples. 7
i = 1
while i < 4:
print(i)
i += 1
# Output: 1 2 3
24. Demonstrate five built-in string functions and check palindrome. 7
s = "Level"
# 5 string functions
print([Link]()) # level
print([Link]()) # LEVEL
print([Link]("Le")) # True
print([Link]("l")) # True
print([Link]("v")) # 2
# Palindrome check
if [Link]() == [Link]()[::-1]:
print("Palindrome")
else:
print("Not Palindrome")
25. Program to calculate the reverse of an entered number. 7
num = 1234
rev = 0
n = 5
fact = 1
i = 1
while i <= n:
fact *= i
i += 1
print("Factorial:", fact)
n = 5
fact = 1
for i in range(1, n+1):
fact *= i
print("Factorial:", fact)
s = "madam"
i=0
j = len(s) - 1
is_palindrome = True
while i < j:
if s[i] != s[j]:
is_palindrome = False
break
i += 1
j -= 1
for i in range(5):
if i == 3:
pass # Placeholder for future code
else:
print(i)
30. Print pattern using nested for loops: 7
1
22
333
4444
n = 10
i=1
total = 0
while i <= n:
if i % 2 != 0:
total += i
i += 1
while True:
num = int(input("Enter a positive number: "))
if num > 0:
break
33. Nested if-else to find largest of 3 numbers. 7
a, b, c = 10, 25, 15
if a > b:
if a > c:
largest = a
else:
largest = c
else:
if b > c:
largest = b
else:
largest = c
print("Largest:", largest)
34. Count vowels and consonants in a string using for and if-else. 7
s = "Hello World"
vowels = "aeiouAEIOU"
v=c=0
for ch in s:
if [Link]():
if ch in vowels:
v += 1
else:
c += 1
print("Vowels:", v)
print("Consonants:", c)
35. Merge two dictionaries into one. 7
d1 = {'a': 1, 'b': 2}
d2 = {'c': 3}
merged = {**d1, **d2}
print(merged)
36. 7
Write a program to split a sentence into words, and then join
them back using a hyphen -.
Program:
# Input sentence
sentence = "Python is an amazing language"
Output:
37. 7
Unit-3
Section-A
Ques. Short Answer Type Questions Marks
No.
31. Show an example where both keyword and default arguments are used. 2
square = lambda x: x * x
print(square(5)) # Output: 25
Positional Arguments
Keyword Arguments
Default Arguments
Variable-length Arguments: Use *args or **kwargs.
def total(*nums):
return sum(nums)
x = 10 # Global
def test():
x = 5 # Local
print("Inside:", x)
test()
print("Outside:", x)
s = "hello"
freq = {}
for ch in s:
freq[ch] = [Link](ch, 0) + 1
lst = [1, 2, 3]
lst[0] = 10 # Valid
tup = (1, 2, 3)
# tup[0] = 10 # Error: Tuple is immutable
Defining a list:
my_list = [1,2,2,3,4,4,5]
unique = []
for item in my_list:
if item not in unique:
[Link](item)
print(unique) # [1,2,3,4,5]
print("Lines:",lines)
print("Words:",words)
print("Characters:",chars)
Section-B
Ques. Long Answer Type Questions Marks
No.
38. Describe the differences between linear search and binary search. 7
Linear Search:
o Scans every element.
o Works on unsorted or sorted lists.
o Time complexity: O(n)
Binary Search:
o Only works on sorted lists.
o Repeatedly divides the list in half.
o Time complexity: O(log n)
39. Write a Python program triangle(N) that prints a right triangle pattern using 7
*
*
**
***
****
def triangle(N):
for i in range(1, N + 1):
print("*" * i)
triangle(4)
40. Recursive program to compute factorial. 7
def factorial(n):
if n == 0:
return 1
return n * factorial(n - 1)
num = 153
sum = 0
temp = num
while temp > 0:
digit = temp % 10
sum += digit ** 3
temp //= 10
42. Program to remove all duplicates from a list without using set(). 7
lst = [1, 2, 2, 3, 4, 4, 5]
unique = []
for item in lst:
if item not in unique:
[Link](item)
print("Original:", lst)
print("Without duplicates:", unique)
43. Function to return max and min without using max() or min(). 7
def find_max_min(lst):
max_val = min_val = lst[0]
for num in lst:
if num > max_val:
max_val = num
if num < min_val:
min_val = num
return max_val, min_val
def filter_even(t):
return tuple(i for i in t if i % 2 == 0)
print("Union:", a | b) # {1, 2, 3, 4, 5}
print("Intersection:", a & b) # {3}
print("Difference:", a - b) # {1, 2}
# Unpacking tuple
t = (1,2,3)
a,b,c = t
print(a,b,c)
# Mutable sequence
lst = [10,20,30]
lst[1] = 99
print(lst)
# String concatenation
s1 = "Hello"
s2 = "World"
result = s1 + " " + s2
print(result)
49. Illustrate different list slicing constructs for the following operations on the 7
following list:
L = [1, 2, 3, 4, 5, 6, 7, 8, 9]
1. Return a list of numbers starting from the last to second item of the list
2. Return a list that start from 3rd item to second last item.
3. Return a list that has only even position elements of list L to list M.
4. Return a list that starts from the middle of the list L.
5. Return a list that reverses all the elements starting from element at index
0 to middle index only and return the entire list.
Divide each element of the list by 2 and replace it with the remainder.
Unpacking tuples, mutable sequences, string concatenation
Example:
# Unpacking tuple
t = (1,2,3)
a,b,c = t
print(a,b,c)
# Mutable sequence
lst = [10,20,30]
lst[1] = 99
print(lst)
# String concatenation
s1 = "Hello"
s2 = "World"
result = s1 + " " + s2
print(result)
b. List slicing on L
Given:
L = [1,2,3,4,5,6,7,8,9]
print(L[-1:-len(L):-1]) # [9,8,7,6,5,4,3,2]
print(L[2:-1]) # [3,4,5,6,7,8]
M = L[1::2]
print(M) # [2,4,6,8]
mid = len(L)//2
print(L[mid:]) # [5,6,7,8,9]
mid = len(L)//2
L[:mid+1] = L[:mid+1][::-1]
print(L) # [5,4,3,2,1,6,7,8,9]
✅Divide by 2, store remainders:
L = [x%2 for x in L]
print(L)
50. Construct a program to change the contents of the file by reversing each 7
character
separated by comma:
Hello!!
Output
H,e,l,l,o,!,!
with open("[Link]","r") as f:
content = [Link]().strip()
reversed_chars = ",".join(content[::-1])
with open("[Link]","w") as f:
[Link](reversed_chars)
51. 7
52. Construct following filters: 7
1. Filter all the numbers
2. Filter all the strings starting with a vowel
3. Filter all the strings that contains any of the following noun: Agra,
Ramesh, Tomato, Patna.
Create a program that implements these filters to clean the text.
import re
original_list = [1, 2, 2, 3, 4, 4, 5, 5, 5]
unique_list = []
for item in original_list:
if item not in unique_list:
unique_list.append(item)
# Example dictionary
d = {'A': 100, 'B': 540, 'C': 239}
Example:
# Display results
print("Celsius temperatures:", celsius_temps)
print("Fahrenheit temperatures:", fahrenheit_temps)
56. 7
What is the significance of modules in Python? How to import?
Modules:
1. import module
import math
print([Link](16))
import math as m
print([Link])
57. 7
Unit-4
Section-A
Ques. Short Answer Type Questions Marks
No.
40. Open file in write mode, write multiple lines, read contents. 2
# Write
with open("[Link]", "w") as f:
[Link]("Line 1\nLine 2\nLine 3")
# Read
with open("[Link]", "r") as f:
print([Link]())
print("Lines:", num_lines)
print("Words:", num_words)
print("Characters:", num_chars)
42. Explain seek() and tell() with examples. 2
43. Read file and print each line after stripping newline (\n). 2
try:
with open("[Link]", "r") as f:
print([Link]())
except FileNotFoundError:
print("File not found!")
import csv
read_last_n_lines('[Link]', 3)
1. In [Link]:
def greet(name):
return f"Hello, {name}!"
2. In [Link]:
import library
print([Link]("Alice"))
# [Link]
def greet():
print("Hello!")
if __name__ == "__main__":
greet() # Executes only when run directly
# [Link]
def hello():
print("Hi")
# Usage
import library
[Link]()
try:
x = 10 / 0
except ZeroDivisionError:
print("Cannot divide by zero")
finally:
print("Cleanup actions")
67. Open file in write mode, write multiple lines, read contents. 7
# Write
with open("[Link]", "w") as f:
[Link]("Line 1\nLine 2\nLine 3")
# Read
with open("[Link]", "r") as f:
print([Link]())
68. Difference between file modes 'r', 'w', 'a', and 'r+' with examples.
Mode Description
'r' Read-only (error if file not found)
'w' Write-only (creates file if not exists, overwrites)
'a' Append mode (adds to end, preserves data)
'r+' Read & write (file must exist)
python
CopyEdit
# 'r'
with open("[Link]", "r") as f:
print([Link]())
# 'w'
with open("[Link]", "w") as f:
[Link]("Hello")
# 'a'
with open("[Link]", "a") as f:
[Link]("\nAppended line")
# 'r+'
with open("[Link]", "r+") as f:
content = [Link]()
[Link]("\nExtra content")
python
CopyEdit
with open("[Link]", "w") as f:
[Link]("Hello World")
python
CopyEdit
with open("[Link]", "wb") as f:
[Link](b'ABC123')
70. Write a Python program to read a file named “[Link]” and count the 7
number
of lines, words, and characters in the file.
# Initialize counters
line_count = len(lines)
word_count = 0
char_count = 0
Function Description
arange(start, stop, step) Uses step size, may not include stop.
linspace(start, stop, num) Divides range into num equally spaced values.
python
CopyEdit
import numpy as np
print([Link](1, 5, 1)) # [1 2 3 4]
print([Link](1, 5, 4)) # [1. 2.333 3.666 5.]
Matplotlib (Visualization):
51. GUI Program to create a label and change font using Tkinter. 2
import tkinter as tk
root = [Link]()
label = [Link](root, text="Hello", font=("Arial", 16))
[Link]()
[Link]()
import numpy as np
import numpy as np
identity = [Link](3)
print(identity)
import numpy as np
arr = [Link](5, 51, size=10)
print(arr)
import numpy as np
arr = [Link](6)
reshaped = [Link](2, 3)
print(reshaped)
import pandas as pd
data = {
'Name': ['Alice', 'Bob'],
'Age': [24, 27]
}
df = [Link](data)
print(df)
✅Pandas functions:
import numpy as np
print([Link](3))
Section-B
Ques. Long Answer Type Questions Marks
No.
71. Perform element-wise addition, subtraction, multiplication, division. 7
import numpy as np
print("Add:", a + b)
print("Sub:", a - b)
print("Mul:", a * b)
print("Div:", a / b)
72. Read a CSV file into Pandas DataFrame and display first 5 rows. 7
import pandas as pd
df = pd.read_csv("[Link]")
print([Link]()) # Displays first 5 rows
74. Filter rows in DataFrame where column value > specified number. 7
import pandas as pd
import pandas as pd
grouped = [Link]('Dept').mean()
print(grouped)
[Link](subjects, marks)
[Link]("Student Marks")
[Link]("Subjects")
[Link]("Marks")
[Link]()
import tkinter as tk
def calculate(op):
a = int([Link]())
b = int([Link]())
if op == '+':
[Link](a + b)
elif op == '-':
[Link](a - b)
root = [Link]()
entry1 = [Link](root)
entry2 = [Link](root)
result = [Link]()
[Link]()
[Link]()
[Link]()
Widget Purpose
Label Display text
Button Execute a function
Entry Input text
Text Multiline text input
Checkbutton Toggle option on/off
81. Tkinter login form with Username, Password, and Submit.
import tkinter as tk
def submit():
user = [Link]()
pwd = [Link]()
[Link](f"Username: {user}, Password: {pwd}")
root = [Link]()
username = [Link]()
password = [Link]()
output = [Link]()
[Link](root, text="Username").pack()
[Link](root, textvariable=username).pack()
[Link](root, text="Password").pack()
[Link](root, textvariable=password, show="*").pack()
[Link](root, text="Submit", command=submit).pack()
[Link](root, textvariable=output).pack()
[Link]()
82. Construct a program to read [Link] dataset, remove last column and save 7
it in
an array. Save the last column to another array. Plot the first two columns.
import pandas as pd
import [Link] as plt
df = pd.read_csv("[Link]")
data = [Link]
X = data[:,:-1]
Y = data[:,-1]
[Link](X[:,0],X[:,1],'o')
[Link]("Column1")
[Link]("Column2")
[Link]()
83. Design a calculator with the following buttons and functionalities like 7
addition,
subtraction, multiplication, division and clear.
import tkinter as tk
def click(op):
a = float([Link]())
b = float([Link]())
if op=='+':
[Link](a+b)
elif op=='-':
[Link](a-b)
elif op=='*':
[Link](a*b)
elif op=='/':
[Link](a/b)
root = [Link]()
entry1 = [Link](root)
entry2 = [Link](root)
[Link]()
[Link]()
result = [Link]()
[Link](root, textvariable=result).pack()
for op in ['+','-','*','/']:
[Link](root,text=op,command=lambda o=op:click(o)).pack()
[Link](root,text="Clear",command=lambda: [Link]("")).pack()
[Link]()
84. Construct a plot for following dataset using matplotlib : 7
import [Link] as plt
import pandas as pd
data = {
'Food':['Meat','Banana','Avocados','Sweet
Potatoes','Spinach','Watermelon','Coconut
water','Beans','Legumes','Tomato'],
'Calories':[250,130,140,120,20,20,10,50,40,19],
'Potassium':[40,55,20,30,40,32,10,26,25,20],
'Fat':[8,5,3,6,1,1.5,0,2,1.5,2.5]
}
df = [Link](data)
[Link](kind='bar',x='Food',y=['Calories','Potassium','Fat'])
[Link]('Food Nutritional Values')
[Link]('Values')
[Link]()