0% found this document useful (0 votes)
8 views47 pages

Python Programming Important Questions

This document contains important questions and solutions for a Python Programming course, covering various topics such as operators, data types, functions, and control flow statements. It includes both short answer and long answer questions, along with example code snippets. The document serves as a study guide for students preparing for assessments in Python programming.

Uploaded by

dhritisingh33
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)
8 views47 pages

Python Programming Important Questions

This document contains important questions and solutions for a Python Programming course, covering various topics such as operators, data types, functions, and control flow statements. It includes both short answer and long answer questions, along with example code snippets. The document serves as a study guide for students preparing for assessments in Python programming.

Uploaded by

dhritisingh33
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

Department of Computer Science and Engineering

United College of Engineering & Research, Prayagraj


Pin - 211010 (India)

Unit wise Important Questions & Solutions


Course Name: PYTHON PROGRAMMING

AKTU Course Code: BCC402

Unit-1
Section-A
Ques. Short Answer Type Questions Marks
No.
1. Differentiate between / and // operator with an example. 2

 / is the division operator that returns a float value.

 // is the floor division operator that returns the largest integer less than or equal
to the result.

print(7 / 2) # Output: 3.5


print(7 // 2) # Output: 3
2. Illustrate unpacking tuples, mutable sequences, and string concatenation with 2
examples.

# Unpacking tuple
t = (1, 2, 3)
a, b, c = t
print(a, b, c)

# Mutable sequence (List)


lst = [1, 2, 3]
lst[0] = 10
print(lst)

# 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

4. Write a basic Python code to add 2 numbers. 2

a=5
b=3
sum = a + b
print("Sum:", sum)
5. Explain any five features of Python. 2

 Easy to Learn and Use

 Interpreted Language

 Dynamically Typed

 Extensive Libraries

 Object-Oriented

6. Describe the concept of list slicing with a suitable example. 2

lst = [10, 20, 30, 40, 50]


print(lst[1:4]) # Output: [20, 30, 40]
7. Show the way to import a module in Python. 2

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

 append(): Adds a single item to the end.

 extend(): Adds all items from another iterable.

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

 Lists: Can store mixed data types.

 Arrays: Require same data type, better for numerical tasks.

import array
arr = [Link]('i', [1, 2, 3])
11. What is a dictionary in Python? 2

A dictionary is a collection of key-value pairs.


d = {'name': 'John', 'age': 25}
print(d['name']) # Output: John
12. What is object-oriented programming (OOP) in Python? Give an example. 2

OOP is a paradigm based on objects and classes.


class Person:
def __init__(self, name):
[Link] = name

p = Person("Alice")
print([Link])
13. Difference between is and == operators. 2

 ==: Compares values.

 is: Compares memory addresses.

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:

 You don’t declare variable types explicitly.


 The type is determined at runtime.
Example:

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 + "5" # Error: cannot add int and str

 Dynamic because types are flexible and decided at runtime.


 Strongly typed because Python enforces type rules and doesn’t silently
convert.

17. Dynamic typing in Python

 In Python, variable types are determined at runtime.


 You don’t declare types explicitly.
Example:

x = 5 # integer
x = "hello" # now a string

18. Write a for loop that prints numbers from 0 to 57 using range().

for i in range(0, 58):


print(i)

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).

✅Correct way (single-element tuple):

single_tuple = (5,) # This is a tuple


print(type(single_tuple)) # <class 'tuple'>

✅Incorrect way (just an integer):

\
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

Precedence Description Associativity

() Parentheses (function call)

1 [] Array Subscript (Square Brackets) Left

. Dot Operator
-> Structure Pointer Operator

++ , — Postfix increment, decrement

++ / — Prefix increment, decrement

+/– Unary plus, minus

!,~ Logical NOT, Bitwise complement

2 (type) Cast Operator Right-to-Left

* Dereference Operator

& Addressof Operator

sizeof Determine size in bytes

3 *,/,% Multiplication, division, modulus Left-to-Right

4 +/- Addition, subtraction Left-to-Right

5 << , >> Bitwise shift left, Bitwise shift right Left-to-Right

< , <= Relational less than, less than or equal to


6 Left-to-Right
Relational greater than, greater than or
> , >=
equal to

7 == , != Relational is equal to, is not equal to Left-to-Right

8 & Bitwise AND Left-to-Right

9 ^ Bitwise exclusive OR Left-to-Right

10 | Bitwise inclusive OR Left-to-Right

11 && Logical AND Left-to-Right

12 || Logical OR Left-to-Right
13 ?: Ternary conditional Right-to-Left

= Assignment

+= , -= Addition, subtraction assignment

*= , /= Multiplication, division assignment


14 Right-to-Left
%= , &= Modulus, bitwise AND assignment

Bitwise exclusive, inclusive OR


^= , |=
assignment

<<=, >>= Bitwise shift left, right assignment

15 , comma (expression separator) Left-to-Right


2. 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.
3. Explain the following loops with a flow diagram, syntax, and suitable examples. 7
I) For II) while (7 marks)

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 (+, -, *, /): ")

result = calculator(num1, num2, op)


print("Result:", result)

6. 7
Write short notes

(a) Operator Precedence

 Operator precedence determines the order in which operations are


evaluated.
 For example:
o * and / have higher precedence than + and -.
 Example:

result = 2 + 3 * 4 # Evaluates as 2 + (3*4) = 14

 You can use parentheses () to change the precedence:

result = (2 + 3) * 4 # Evaluates as 5 * 4 = 20
(b) Python Indentation

 Indentation is mandatory in Python and defines code blocks.


 Unlike other languages (like C, Java) that use { }, Python uses whitespace.
 Example:

if True:
print("Indented block") # This line is part of the if
block
print("Outside block") # No indentation

(c) Type Conversion

 Type conversion means changing one data type into another.


 Implicit conversion: Python automatically converts types.

x = 5
y = 2.0
result = x + y # result is 7.0 (int converted to float)

 Explicit conversion (casting):

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))

8. Determine a python function removenth(s,n) that takes an input a string and 7


an
integer n>=0 and removes a character at index n. If n is beyond the length of
s,
then whole s is returned. For example:
removenth(“MANGO”,1) returns MNGO
removenth(“MANGO”,3) returns MANO

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

items = input("Enter words separated by commas:\n")


words = [[Link]() for x in [Link](",")]
[Link]()
print(",".join(words))
10. A website requires the users to input username and password to register. 7
Construct
a program to check the validity of password input by users.
Following are the criteria for checking the password:
1. At least 1 letter between [a-z]
2. At least 1 number between [0-9]
3. At least 1 letter between [A-Z]
4. At least 1 character from [$#@]
5. Minimum length of transaction password: 6
6. Maximum length of transaction password: 12
Your program should accept a sequence of comma separated passwords
and will
check them according to the above criteria. Passwords that match the
criteria are
to be printed, each separated by a comma

import re

passwords = input("Enter comma-separated passwords:\n").split(",")

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.

def compute_lcm(x, y):


# Choose the greater number
if x > y:
greater = x
else:
greater = y

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: "))

print("The LCM of", num1, "and", num2, "is", compute_lcm(num1,


num2))
12. 7

Implement the Binary Search Technique

Binary Search requires a sorted list. It works by repeatedly dividing the search
interval in half.

def binary_search(arr, target):


low = 0
high = len(arr) - 1

while low <= high:


mid = (low + high) // 2
if arr[mid] == target:
return mid
elif arr[mid] < target:
low = mid + 1
else:
high = mid - 1

return -1 # Not found

# 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

i. The Programming Cycle for Python

 Editing: Write Python code in a .py file.


 Saving: Save your script.
 Running/Interpreting: Use the Python interpreter (python [Link]) to
execute.
 Testing/Debugging: Check output and fix errors.
 Refining: Improve and optimize code.

This cycle repeats until the program works as intended.

ii. Type Conversion in Python

Type conversion is converting data from one type to another.

✅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

Leap year rules:

 Divisible by 4
 Not divisible by 100, unless divisible by 400

year = int(input("Enter a 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")

15. 7
Discuss Exceptions and Assertions in Python

Exceptions:

 Errors that occur during execution.


 Can be caught with try...except.

Example:

try:
x = 10 / 0
except ZeroDivisionError:
print("Cannot divide by zero.")

Assertions:

 Used for debugging.


 Check if a condition is True. If not, raises AssertionError.

Example:

x = 5
assert x > 0, "x must be positive"
✅Two built-in exceptions:

1. ZeroDivisionError: Raised when dividing by zero.

1 / 0 # Raises ZeroDivisionError

2. ValueError: Raised when a function gets an argument of the right type but
inappropriate value.

int("abc") # Raises ValueError

16. 7
Implement Selection Sort in Python

Selection Sort:

 Repeatedly find the minimum element and place it at the beginning.

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

Python supports 5 types of inheritance:

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

The range() function generates a sequence of numbers from start (inclusive) to


stop (exclusive).

for i in range(2, 6):


print(i)
# Output: 2 3 4 5
21. Explain the role of precedence with an example. 2

Operator precedence determines the order of operations in expressions.


x = 3 + 2 * 4 # Multiplication has higher precedence than addition
print(x) # Output: 11
22. Describe the concept of list comprehension with a suitable example. 2
List comprehension is a concise way to create lists by specifying an expression
followed by a loop.
✅Example:

squares = [x**2 for x in range(1,6)]


print(squares) # Output: [1, 4, 9, 16, 25]

23. Compute the output of the given code. 2

def count(s):
for str in [Link]():
s = "&".join(str)
return s

print(count("Python is fun to learn."))

24. Describe the difference between linspace and arange. 2

 linspace(start, stop, num) generates num equally spaced samples


between start and stop.
 arange(start, stop, step) generates values using a step size.
✅Example:

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]

25. Explain why the program generates an error. 2

x = ['12', 'hello', 456]


x[0] *=3
x[1][1]='bye'

1. x[0] *=3 is OK: '12'*3 results in '121212'.


2. x[1][1]='bye' causes an error because strings are immutable. You cannot
assign to a character in a string.

26. How to print the character of a given ASCII value in Python? 2

Use chr() function:

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")

28. What will be the output? 2

l= [1, 0, 0, 2, ' hi', ' ', []]


print(list(filter(bool, l)))

29. Purpose of split() in string manipulation 2


It splits a string into a list of substrings based on a delimiter.
Example:

s = "apple,banana,orange"
print([Link](",")) # ['apple','banana','orange']

30. How is pass different from a comment? 2

pass statement:

 It is a no-operation statement—does nothing but is a real Python


statement.
 Used as a placeholder inside blocks (e.g., functions, loops) where code is
syntactically required.

Example:

def my_function():
pass # Placeholder, function does nothing

Comment:

 Starts with # and is ignored by the interpreter.


 Used only for code documentation.

Example:

# This is a comment

Difference:

 pass executes (does nothing), while comments are completely ignored.


Section-B
Ques. Long Answer Type Questions Marks
No.
18. Explain the following loops with a flow diagram, syntax, and suitable examples. 7
I) For II) while (7 marks)

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.

22. Describe Recursion. Write a program to generate Fibonacci [Link] and 7


recursion are two different approaches to solvingproblems in computer
programming.(7 marks)

Iterators refer to a programming construct that allows aprogrammer to traverse


through a collection of data, such as anarray or a linked list, in a sequential manner.
The iterator provides away to access each element of the collection one at a time,
withoutneeding to know the details of how the collection is [Link]
can be used to perform a variety of tasks, such as searchingfor an element in the
collection, performing a calculation on element, or simply printing out the
elements in [Link], on the other hand, is a programming technique
thatinvolves a function calling itself repeatedly until a certain conditionis met. The
function breaks down a larger problem into smaller subproblems

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

sub-problems that can be solved recursively.

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

for loop: Iterates over a sequence (like list, range, string).


for i in range(1, 4):
print(i)
# Output: 1 2 3

while loop: Repeats as long as the condition is True.

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

while num > 0:


digit = num % 10
rev = rev * 10 + digit
num = num // 10

print("Reversed number:", rev)


26. Program to print multiplication table using for loop. 7
n = 5
for i in range(1, 11):
print(f"{n} x {i} = {n * i}")
27. Calculate factorial using both while and for loops. 7
Using while loop:

n = 5
fact = 1
i = 1
while i <= n:
fact *= i
i += 1
print("Factorial:", fact)

Using for loop:

n = 5
fact = 1
for i in range(1, n+1):
fact *= i
print("Factorial:", fact)

28. . Check if string is palindrome using while loop (no slicing).

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

print("Palindrome" if is_palindrome else "Not Palindrome")


29. Explain pass in loops. Code with empty if and pass. 7

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

for i in range(1, 5):


for j in range(i):
print(i, end=' ')
print()
31. Sum of all odd numbers between 1 and N using while. 7

n = 10
i=1
total = 0

while i <= n:
if i % 2 != 0:
total += i
i += 1

print("Sum of odd numbers:", total)


32. Difference between while and do-while loop. 7

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"

# Split into words


words = [Link]()
print("Split words:", words)

# Join with hyphen


joined = "-".join(words)
print("Joined with hyphen:", joined)

Output:

Split words: ['Python', 'is', 'an', 'amazing', 'language']


Joined with hyphen: Python-is-an-amazing-language

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

def greet(name, msg="Hello"):


print(msg, name)

greet("Alice") # Uses default msg


greet("Bob", msg="Hi") # Uses keyword argument
32. Explain the lambda function. 2
 A lambda function is a small anonymous function.
 Syntax: lambda arguments: expression

square = lambda x: x * x
print(square(5)) # Output: 25

33. Types of argument-passing methods. Explain variable-length 2


arguments.

 Positional Arguments
 Keyword Arguments
 Default Arguments
 Variable-length Arguments: Use *args or **kwargs.

def total(*nums):
return sum(nums)

print(total(1, 2, 3, 4)) # Output: 10

34. Differentiate between global and local variables. 2

 Local variable: Declared inside function, accessible only there.


 Global variable: Declared outside all functions.

x = 10 # Global

def test():
x = 5 # Local
print("Inside:", x)

test()
print("Outside:", x)

35. What is a list? Explain with example. 2

A list is a mutable, ordered collection.

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


my_list.append(4)
print(my_list)

36. Create a dictionary and count character frequency in a string. 2

s = "hello"
freq = {}

for ch in s:
freq[ch] = [Link](ch, 0) + 1

print(freq) # Output: {'h': 1, 'e': 1, 'l': 2, 'o': 1}

37. Difference between mutable and immutable data types. 2


 Mutable: Can be changed after creation (e.g., list, dict)
 Immutable: Cannot be changed (e.g., tuple, string)

lst = [1, 2, 3]
lst[0] = 10 # Valid

tup = (1, 2, 3)
# tup[0] = 10 # Error: Tuple is immutable

38. Define a list & remove duplicates 2

Defining a list:

my_list = [1,2,2,3,4,4,5]

Program to remove duplicates:

unique = []
for item in my_list:
if item not in unique:
[Link](item)
print(unique) # [1,2,3,4,5]

39. Read a file and count lines, words, characters 2

lines = words = chars =0


with open("[Link]","r") as f:
for line in f:
lines+=1
words+=len([Link]())
chars+=len(line)

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)

def linear_search(arr, x):


for i in range(len(arr)):
if arr[i] == x:
return i
return -1

 Binary Search:
o Only works on sorted lists.
o Repeatedly divides the list in half.
o Time complexity: O(log n)

def binary_search(arr, x):


low = 0
high = len(arr) - 1
while low <= high:
mid = (low + high) // 2
if arr[mid] == x:
return mid
elif arr[mid] < x:
low = mid + 1
else:
high = mid - 1
return -1

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)

print(factorial(5)) # Output: 120

41. Program to check if a 3-digit number is an Armstrong number. 7

num = 153
sum = 0
temp = num
while temp > 0:
digit = temp % 10
sum += digit ** 3
temp //= 10

print("Armstrong" if sum == num else "Not Armstrong")

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

print(find_max_min([3, 5, 1, 8, 2])) # Output: (8, 1)

44. Function to return a tuple of even numbers from given tuple. 7

def filter_even(t):
return tuple(i for i in t if i % 2 == 0)

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


45. 7
Explain Python set. Perform union, intersection, and difference.
a = {1, 2, 3}
b = {3, 4, 5}

print("Union:", a | b) # {1, 2, 3, 4, 5}
print("Intersection:", a & b) # {3}
print("Difference:", a - b) # {1, 2}

46. Lambda function to filter numbers > 10. 7

nums = [5, 12, 7, 20, 3]


filtered = list(filter(lambda x: x > 10, nums))
print(filtered) # [12, 20]

47. Function with any number of positional arguments to return their 7


sum.
def add_all(*args):
return sum(args)

print(add_all(3, 5, 10, 15)) # Output: 33

48. Illustrate Unpacking tuples, mutable sequences, and string concatenation


with examples

# 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]

✅1. Last to second item:

print(L[-1:-len(L):-1]) # [9,8,7,6,5,4,3,2]

✅2. 3rd to second last:

print(L[2:-1]) # [3,4,5,6,7,8]

✅3. Even positions:

M = L[1::2]
print(M) # [2,4,6,8]

✅4. Start from middle:

mid = len(L)//2
print(L[mid:]) # [5,6,7,8,9]

✅5. Reverse up to middle index:

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

text = ["Agra is a city","Ramesh went there","I like Tomato","apple","Egg","ice"]


# Filter numbers
numbers = [w for w in text if [Link]()]
print("Numbers:",numbers)

# Filter starting with vowels


vowel_words = [w for w in text if [Link](r"(?i)^[aeiou]",w)]
print("Starts with vowel:",vowel_words)

# Filter contains nouns


nouns = ["Agra","Ramesh","Tomato","Patna"]
noun_words = [w for w in text if any(n in w for n in nouns)]
print("Contains nouns:",noun_words)
53. Explain how to define a list in Python. Write a Python program to remove 7
duplicates from a list and print the resulting list.

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)

print("Original list:", original_list)


print("List after removing duplicates:", unique_list)
54. Write a Python Program to find the sum all the items in a dictionary. 7
For example if d={'A':100,'B':540,'C':239}then output should be 879.

# Example dictionary
d = {'A': 100, 'B': 540, 'C': 239}

# Calculate the sum of values


total = sum([Link]())

# Print the result


print("The sum of all items in the dictionary is:", total)
55. Explain how lambda functions can be used within a list comprehension. 7
Write a
Python program that uses a lambda function within a list comprehension to
convert a list of temperatures in Celsius to Fahrenheit.

 A lambda function is a small, anonymous function defined using the


lambda keyword.
 In a list comprehension, you can call a lambda function for each element
in a list to transform or filter the data.

Example:

squared = [(lambda x: x**2)(n) for n in range(5)]


print(squared) # [0, 1, 4, 9, 16]

# List of Celsius temperatures


celsius_temps = [0, 10, 20, 37, 100]

# List comprehension applying lambda to convert to Fahrenheit


fahrenheit_temps = [(lambda c: (c * 9/5) + 32)(c) for c in celsius_temps]

# 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:

 Files containing Python definitions and statements.


 Help organize code and promote reusability.

✅Methods of importing modules:

1. import module

import math
print([Link](16))

2. from module import function

from math import sqrt


print(sqrt(25))

3. import module as alias

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]())

41. Count total number of words, characters, and lines in [Link]. 2

with open("[Link]", "r") as f:


lines = [Link]()
num_lines = len(lines)
num_words = sum(len([Link]()) for line in lines)
num_chars = sum(len(line) for line in lines)

print("Lines:", num_lines)
print("Words:", num_words)
print("Characters:", num_chars)
42. Explain seek() and tell() with examples. 2

 seek(offset): Move the file cursor.


 tell(): Get current position.

with open("[Link]", "r") as f:


print([Link]()) # 0
[Link](5)
print([Link]()) # 5
[Link](0)
print([Link](5)) # Reads again from start

43. Read file and print each line after stripping newline (\n). 2

with open("[Link]", "r") as f:


for line in f:
print([Link]())

44. Exception handling when file does not exist. 2

try:
with open("[Link]", "r") as f:
print([Link]())
except FileNotFoundError:
print("File not found!")

45. Copy contents of one file to another. 2

with open("[Link]", "r") as src, open("[Link]", "w") as dst:


for line in src:
[Link](line)

46. Significance of with statement in file handling. 2

 Ensures file is automatically closed, even if errors occur.

with open("[Link]", "r") as f:


content = [Link]()
# File is closed here automatically

47. Read a CSV file and display contents line by line. 2

import csv

with open("[Link]", "r") as f:


reader = [Link](f)
for row in reader:
print(row)

48. What does readline() return at end of file? 2


It returns an empty string ("") when no more lines are left.
Section-B
Ques. Long Answer Type Questions Marks
No.
58. Program to read the last n lines of a file. 7

def read_last_n_lines(filename, n):


with open(filename, 'r') as file:
lines = [Link]()
for line in lines[-n:]:
print([Link]())

read_last_n_lines('[Link]', 3)

59. How to use functions from [Link] inside [Link]? 7

1. In [Link]:

def greet(name):
return f"Hello, {name}!"

2. In [Link]:

import library

print([Link]("Alice"))

60. Find the largest word in a file using file handling. 7

with open("[Link]", "r") as f:


words = [Link]().split()
largest = max(words, key=len)
print("Largest word:", largest)

61. Change file contents by separating characters with commas. 7

with open("[Link]", "r") as f:


content = [Link]()
with open("[Link]", "w") as f:
[Link](",".join(content))

62. xplain use of with in Python. 7

 Ensures proper resource management (auto-close files).

with open("[Link]", "r") as f:


data = [Link]()
print(data)

63. Create a Python file usable as library and standalone script. 7

# [Link]
def greet():
print("Hello!")

if __name__ == "__main__":
greet() # Executes only when run directly

64. Difference between import library and from library import *. 7

 import library: Access using [Link]()


 from library import *: Access functions directly (not recommended due
to name conflicts)

# [Link]
def hello():
print("Hi")

# Usage
import library
[Link]()

from library import *


hello()

65. Importance of Exception Handling. Explain try-except-finally. 7

 Prevents program from crashing due to unexpected errors.

try:
x = 10 / 0
except ZeroDivisionError:
print("Cannot divide by zero")
finally:
print("Cleanup actions")

66. Explain File Input and Output operations. 7

 Reading: read(), readline(), readlines()


 Writing: write(), writelines()
 Opening Modes: 'r', 'w', 'a', 'r+'

with open("[Link]", "w") as f:


[Link]("Hello\nWorld")

with open("[Link]", "r") as f:


print([Link]())

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")

69. Difference between text and binary files + code examples. 7

 Text File: Stores human-readable text.


 Binary File: Stores data in byte format.

Write/Read text file:

python
CopyEdit
with open("[Link]", "w") as f:
[Link]("Hello World")

with open("[Link]", "r") as f:


print([Link]())

Write/Read binary file:

python
CopyEdit
with open("[Link]", "wb") as f:
[Link](b'ABC123')

with open("[Link]", "rb") as f:


print([Link]()) # Output: 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.

# Open the file in read mode


with open("[Link]", "r") as file:
lines = [Link]()

# Initialize counters
line_count = len(lines)
word_count = 0
char_count = 0

# Loop through each line


for line in lines:
words_in_line = [Link]()
word_count += len(words_in_line)
char_count += len(line)

# Print the results


print("Number of lines:", line_count)
print("Number of words:", word_count)
print("Number of characters:", char_count)
Unit-5
Section-A
Ques. Short Answer Type Questions Marks
No.
49. Difference between linspace and arange in NumPy. 2

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.]

50. Describe different functions of Matplotlib and Pandas. 2

Matplotlib (Visualization):

 plot(): Line plot


 bar(): Bar chart
 hist(): Histogram
 scatter(): Scatter plot
 title(), xlabel(), ylabel(): Labeling

Pandas (Data handling):

 read_csv(), head(), tail()


 DataFrame, Series
 groupby(), filter(), sort_values()

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]()

52. Calculate sum of diagonal elements of a NumPy array. 2

import numpy as np

arr = [Link]([[1, 2, 3],


[4, 5, 6],
[7, 8, 9]])
print("Diagonal Sum:", [Link](arr)) # Output: 15

53. Create a 3x3 identity matrix using NumPy. 2

import numpy as np
identity = [Link](3)
print(identity)

54. Difference between NumPy array and Python list. 2

Feature NumPy Array Python List


Speed Faster Slower
Type Homogeneous Heterogeneous
Functions Many mathematical ops Fewer built-ins
import numpy as np

arr = [Link]([1, 2, 3])


lst = [1, 2, 3]
print(arr * 2) # [2 4 6]
print(lst * 2) # [1, 2, 3, 1, 2, 3]

55. Generate array of 10 random integers between 5 and 50. 2

import numpy as np
arr = [Link](5, 51, size=10)
print(arr)

56. Describe reshape() in NumPy. Convert 1D to 2D. 2

import numpy as np

arr = [Link](6)
reshaped = [Link](2, 3)
print(reshaped)

57. Create DataFrame from dictionary and display it. 2

import pandas as pd

data = {
'Name': ['Alice', 'Bob'],
'Age': [24, 27]
}
df = [Link](data)
print(df)

58. Describe different functions of matplotlib and pandas. 2


✅Matplotlib functions:

 plot(): Line plot


 bar(): Bar chart
 scatter(): Scatter plot
 hist(): Histogram
 xlabel(), ylabel(), title(): Labels

✅Pandas functions:

 read_csv(): Load CSV file


 DataFrame(): Create DataFrame
 groupby(): Group data
 sort_values(): Sort by column
 dropna(): Remove missing data

59. Which function creates identity matrix in NumPy? 2


[Link]()
Example:

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

a = [Link]([10, 20, 30])


b = [Link]([1, 2, 3])

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

73. Differentiate between Series and DataFrame in Pandas. 7

Feature Series DataFrame


Structure 1D 2D (rows & columns)
Example Column of data Table of data
import pandas as pd

s = [Link]([1, 2, 3]) # Series


df = [Link]({'A': [1, 2], 'B': [3, 4]}) # DataFrame

74. Filter rows in DataFrame where column value > specified number. 7

import pandas as pd

data = {'Name': ['Alice', 'Bob'], 'Marks': [85, 60]}


df = [Link](data)
filtered = df[df['Marks'] > 70]
print(filtered)

75. Use groupby() in Pandas with example. 7

import pandas as pd

data = {'Dept': ['IT', 'HR', 'IT', 'HR'], 'Salary': [40000, 30000,


45000, 35000]}
df = [Link](data)

grouped = [Link]('Dept').mean()
print(grouped)

76. Plot a bar chart using Matplotlib with sample data. 7

import [Link] as plt

subjects = ['Math', 'Science', 'English']


marks = [90, 85, 88]

[Link](subjects, marks)
[Link]("Student Marks")
[Link]("Subjects")
[Link]("Marks")
[Link]()

77. Role of labels, title, and legend in Matplotlib plot. 7

 xlabel() and ylabel() add axis labels


 title() sets chart title
 legend() adds label guide for multiple data

import [Link] as plt


[Link]([1, 2, 3], [10, 20, 30], label="Growth")
[Link]("Time")
[Link]("Value")
[Link]("Line Graph")
[Link]()
[Link]()

78. Plot a pie chart showing marks distribution. 7

import [Link] as plt

subjects = ['Math', 'Science', 'English', 'History', 'Art']


marks = [80, 90, 85, 70, 75]

[Link](marks, labels=subjects, autopct="%1.1f%%")


[Link]("Marks Distribution")
[Link]()

79. GUI Calculator in Tkinter (Add & Subtract). 7

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](root, text="Add", command=lambda: calculate('+')).pack()


[Link](root, text="Subtract", command=lambda: calculate('-
')).pack()
[Link](root, textvariable=result).pack()

[Link]()

80. List and explain any 5 commonly used Tkinter widgets. 7

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]()

You might also like