Got it — you’re right. You need FULL ques on + code + output as comments.
I’ll redo properly from
the start.
1. STRING QUESTIONS
Q1. Write output for following string slicing:
c = "amazing"
print(c[:7]) # amazing
print(c[1:6:2]) # mzn
print(c[0:]) # amazing
Q2. Write a Python program to find the length of a string using len().
s = "Python"
print(len(s)) # 6
Q3. Write a Python program to check whether a string ends with a given substring using
endswith().
s = "[Link]"
print([Link](".py")) # True
Q4. Write a Python program to count the occurrences of a character in a string using count().
s = "banana"
print([Link]("a")) # 3
Q5. Write a Python program to capitalize the first le er of a string using capitalize().
s = "python"
print([Link]()) # Python
Q6. Write a Python program to find the posi on of a substring using find().
s = "hello world"
print(s.find("world")) # 6
Q7. Write a Python program to replace a word in a string using replace().
s = "I like Java"
print([Link]("Java", "Python")) # I like Python
Q8. Write a Python program to display escape sequences in a string.
print("Hello\nWorld\tPython")
# Hello
# World Python
Q9. Write a Python program to detect double spaces in a string.
s = "This is double space"
print(" " in s) # True
Q10. Write a Python program to replace double spaces with single spaces.
s = "This is double space"
print([Link](" ", " ")) # This is double space
2. CONDITIONAL / BASIC LOGIC PROGRAMS
Q11. Write a Python program to find the greatest of four numbers entered by the user.
a, b, c, d = 10, 20, 30, 40
print(max(a, b, c, d)) # 40
Q12. Write a Python program to detect spam comments containing words such as "buy now",
"click this", or "subscribe".
comment = "buy now and subscribe"
spam_words = ["buy now", "click this", "subscribe"]
print(any(word in comment for word in spam_words)) # True
Q13. Write a Python program to check whether a username contains less than 10 characters.
username = "user123"
print(len(username) < 10) # True
Q14. Write a Python program to check whether a given name exists in a list.
names = ["Aman", "Ravi", "Sita"]
print("Ravi" in names) # True
Q15. Write a Python program to check whether a number is prime or not.
n=7
for i in range(2, n):
if n % i == 0:
print("Not Prime")
break
else:
print("Prime") # Prime
Q16. Write a Python program to check whether a number is even or odd.
n = 10
print("Even" if n % 2 == 0 else "Odd") # Even
3. PATTERN PROGRAMS
Q17. Write a Python program to print a right-angle triangle star pa ern.
for i in range(1, 6):
print("*" * i)
#*
# **
# ***
# ****
# *****
Q18. Write a Python program to print an inverted star pa ern.
for i in range(5, 0, -1):
print("*" * i)
# *****
# ****
# ***
# **
#*
4. LIST QUESTIONS
Q19. Write a Python program to create a list containing different data types and display its
elements.
lst = [1, "Python", 3.5]
print(lst) # [1, 'Python', 3.5]
Q20. Write a Python program to access list elements using indexing and slicing.
lst = [10, 20, 30, 40]
print(lst[1]) # 20
print(lst[1:3]) # [20, 30]
Q21. Write a Python program to sort the elements of a list.
lst = [3, 1, 4]
[Link]()
print(lst) # [1, 3, 4]
Q22. Write a Python program to reverse a list.
lst = [1, 2, 3]
[Link]()
print(lst) # [3, 2, 1]
Q23. Write a Python program to append an element to a list.
lst = [1, 2]
[Link](3)
print(lst) # [1, 2, 3]
Q24. Write a Python program to insert an element at a specific posi on in a list.
lst = [1, 3]
[Link](1, 2)
print(lst) # [1, 2, 3]
Q25. Write a Python program to remove an element using pop().
lst = [1, 2, 3]
[Link]()
print(lst) # [1, 2]
Q26. Write a Python program to remove an element using remove().
lst = [1, 2, 3]
[Link](2)
print(lst) # [1, 3]
Q27. Write a Python program using list comprehension to generate a mul plica on table for a
given number.
n=5
table = [n*i for i in range(1, 11)]
print(table) # [5, 10, 15, 20, 25, 30, 35, 40, 45, 50]
Q28. Write a Python program to store a mul plica on table in a file named [Link].
n=5
with open("[Link]", "w") as f:
for i in range(1, 11):
[Link](f"{n} x {i} = {n*i}\n")
# File created with mul plica on table
Q29. Write a Python program to accept marks of six students and display them in sorted order.
marks = [90, 70, 80, 60, 85, 75]
[Link]()
print(marks) # [60, 70, 75, 80, 85, 90]
Q30. Write a Python program to find the sum of all numbers in a list.
lst = [1, 2, 3, 4]
print(sum(lst)) # 10
All in the same clean exam-ready format.
go
Perfect—continuing in the same clean format (full question + code + output as comments).
5. ENUMERATE QUESTIONS
Q31. Write a Python program to print elements of a list along with their index using
enumerate().
lst = ["a", "b", "c"]
for i, val in enumerate(lst):
print(i, val)
#0a
#1b
#2c
Q32. Write a Python program using enumerate() that prints "awesome" when the third
element is reached.
lst = ["a", "b", "c", "d"]
for i, val in enumerate(lst):
if i == 2:
print("awesome") # awesome
Q33. Write a Python program using enumerate() to print the 3rd, 5th, and 7th elements of a
list.
lst = [10, 20, 30, 40, 50, 60, 70]
for i, val in enumerate(lst):
if i in [2, 4, 6]:
print(val)
# 30
# 50
# 70
6. TUPLE QUESTIONS
Q34. Write a Python program to create and display tuples with different data types.
t = (1, "Python", 3.5)
print(t) # (1, 'Python', 3.5)
Q35. Write a Python program to count the occurrence of an element in a tuple.
t = (1, 2, 2, 3)
print([Link](2)) # 2
Q36. Write a Python program to find the index of an element in a tuple.
t = (1, 2, 3)
print([Link](2)) # 1
Q37. Write a Python program to count the number of zeros in a tuple.
t = (0, 1, 0, 2, 0)
print([Link](0)) # 3
7. DICTIONARY QUESTIONS
Q38. Write a Python program to create a dictionary and display its keys and values.
d = {"name": "Aman", "age": 20}
print([Link]()) # dict_keys(['name', 'age'])
print([Link]()) # dict_values(['Aman', 20])
Q39. Write a Python program to access a value from a dictionary using its key.
d = {"name": "Aman", "age": 20}
print(d["name"]) # Aman
Q40. Write a Python program to update a value in a dictionary.
d = {"name": "Aman", "age": 20}
d["age"] = 21
print(d) # {'name': 'Aman', 'age': 21}
Q41. Write a Python program to display all keys, values, and key-value pairs of a dictionary.
d = {"name": "Aman", "age": 20}
print([Link]()) # dict_keys(['name', 'age'])
print([Link]()) # dict_values(['Aman', 20])
print([Link]()) # dict_items([('name', 'Aman'), ('age', 20)])
8. SET QUESTIONS
Q42. Write a Python program to create a set and display its elements.
s = {1, 2, 3}
print(s) # {1, 2, 3}
Q43. Write a Python program to add elements into a set.
s = {1, 2, 3}
[Link](4)
print(s) # {1, 2, 3, 4}
Q44. Write a Python program to remove elements from a set.
s = {1, 2, 3}
[Link](2)
print(s) # {1, 3}
Q45. Write a Python program to perform union of two sets.
a = {1, 2}
b = {2, 3}
print(a | b) # {1, 2, 3}
Q46. Write a Python program to perform intersection of two sets.
a = {1, 2}
b = {2, 3}
print(a & b) # {2}
9. FILE HANDLING QUESTIONS
Q47. Write a Python program to open a file in read mode and display its contents.
with open("[Link]", "r") as f:
print([Link]())
# Output: (depends on file content)
Q48. Write a Python program to create a file in write mode and write text into it.
with open("[Link]", "w") as f:
[Link]("Hello")
# File created with "Hello"
Q49. Write a Python program to open a file in append mode and add new text at the end of
the file.
with open("[Link]", "a") as f:
[Link](" World")
# File now contains appended text
Q50. Write a Python program to open a file in read and write mode (r+), write data into it,
and then read the updated contents.
with open("[Link]", "r+") as f:
[Link]("Hi\n")
print([Link]())
# Output depends on file content after writing
Q51. Write a Python program to read a file named [Link] and check whether it contains
the word "twinkle".
with open("[Link]") as f:
print("twinkle" in [Link]())
# True/False depending on file
Q52. Write a Python program to display the line number where the word "twinkle" appears
in a file.
with open("[Link]") as f:
for i, line in enumerate(f):
if "twinkle" in line:
print(i)
# Outputs line number(s)
Q53. Write a Python program to create a copy of a text file.
with open("[Link]") as f, open("[Link]", "w") as c:
[Link]([Link]())
# File copied
Q54. Write a Python program to check whether a log file contains the word "PYTHON".
with open("[Link]") as f:
print("PYTHON" in [Link]())
# True/False
Q55. Write a Python program to find the line number where "PYTHON" is present in a log
file.
with open("[Link]") as f:
for i, line in enumerate(f):
if "PYTHON" in line:
print(i)
# Line numbers printed
Q56. Write a Python program to compare two files and check whether their contents are
identical.
with open("[Link]") as f1, open("[Link]") as f2:
print([Link]() == [Link]())
# True or False
Q57. Write a Python program to wipe out the contents of a file.
open("[Link]", "w").close()
# File contents deleted
Q58. Write a Python program to rename a file to [Link].
import os
[Link]("[Link]", "[Link]")
# File renamed
Q59. Write a Python program to replace the word "donkey" in a file with "######".
with open("[Link]") as f:
data = [Link]().replace("donkey", "######")
with open("[Link]", "w") as f:
[Link](data)
# Word replaced
Alright, finishing the remaining set in the same format: full question + code + output as
comments.
10. FUNCTIONS
Q60. Write a Python program to create and call a user-defined function.
def greet():
print("Hello")
greet() # Hello
Q61. Write a Python recursive function to find the factorial of a number.
def fact(n):
return 1 if n == 0 else n * fact(n-1)
print(fact(5)) # 120
Q62. Write a Python recursive function to calculate the sum of first n natural numbers.
def sum_n(n):
return 0 if n == 0 else n + sum_n(n-1)
print(sum_n(5)) # 15
11. LAMBDA FUNCTION QUESTIONS
Q63. Write a Python program using lambda function to find the square of a number.
square = lambda x: x*x
print(square(5)) # 25
Q64. Write a Python program using lambda function to calculate the average of two
numbers.
avg = lambda a, b: (a + b) / 2
print(avg(4, 6)) # 5.0
Q65. Write a Python program to pass a lambda function inside another function.
def apply(func, x):
return func(x)
print(apply(lambda x: x + 2, 5)) # 7
12. OS MODULE QUESTIONS
Q66. Write a Python program to check whether a directory exists and create it if it does not.
import os
if not [Link]("test"):
[Link]("test")
print("Done") # Done
Q67. Write a Python program to create folders named Day1 to Day100 inside a directory.
import os
for i in range(1, 101):
[Link](f"Day{i}")
print("Folders created") # Folders created
Q68. Write a Python program to list all files and folders in a directory using [Link]().
import os
print([Link]())
# Output: list of files and folders in current directory
Q69. Write a Python program to display the current working directory using [Link]().
import os
print([Link]())
# Output: current directory path
Q70. Write a Python program to change the current working directory using [Link]().
import os
[Link]("test")
print([Link]())
# Output: path changed to /test
13. LOCAL AND GLOBAL VARIABLES
Q71. Write a Python program to demonstrate the difference between local and global
variables.
x = 10
def func():
x=5
print(x) # 5 (local)
func()
print(x) # 10 (global)
Q72. Write a Python program to modify a global variable inside a function using the global
keyword.
x = 10
def change():
global x
x = 20
change()
print(x) # 20
14. MODULES
Q73. Write a Python program to import a custom module and call a function from it.
import mymodule
[Link]()
# Output depends on module function
Q74. Write a Python program to use the math module for square root calculation.
import math
print([Link](16)) # 4.0
Q75. Write a Python program to import only the sqrt() function from the math module.
from math import sqrt
print(sqrt(25)) # 5.0
Q76. Write a Python program to display all functions available inside the math module using
dir().
import math
print(dir(math))
# Output: list of math module functions
15. NUMPY / PANDAS
Q77. Write a Python program to display the installed version of Pandas.
import pandas as pd
print(pd.__version__)
# Output: pandas version (e.g., 2.x.x)
Q78. Write a Python program to display the installed version of NumPy.
import numpy as np
print(np.__version__)
# Output: numpy version (e.g., 1.x.x)
16. ERROR HANDLING QUESTIONS
Q79. Write a Python program to accept a number from the user and print its multiplication
table using exception handling.
try:
n = int(input("Enter number: "))
for i in range(1, 11):
print(n * i)
except:
print("Invalid input")
# Example Output (input=2):
#2
#4
# ...
# 20
Q80. Write a Python program to handle invalid input using a generic exception object.
try:
x = int("abc")
except Exception as e:
print(e) # invalid literal for int()
Q81. Write a Python program to handle invalid input using a simple except block.
try:
x = int("abc")
except:
print("Error") # Error
Q82. Write a Python program to handle ValueError for non-numeric input.
try:
x = int("abc")
except ValueError:
print("Invalid number") # Invalid number
Q83. Write a Python program to handle both IndexError and ValueError.
try:
lst = [1, 2]
print(lst[5])
except (IndexError, ValueError):
print("Error") # Error
Q84. Write a Python program using try, except, and finally.
try:
print(10 / 2)
except:
print("Error")
finally:
print("Done")
# 5.0
# Done
Q85. Write a Python program to raise a ValueError if a number is outside the range 5 to 9.
n=3
if n < 5 or n > 9:
raise ValueError("Out of range")
# ValueError: Out of range
Q86. Write a Python program to raise a ZeroDivisionError when the divisor is less than or
equal to zero.
d=0
if d <= 0:
raise ZeroDivisionError
# ZeroDivisionError
17. CONDA / PIP COMMANDS
Q87. Write the command to check the installed version of Conda.
conda --version
Q88. Write the command to search all available Python versions in Conda.
conda search python
Q89. Write the command to create a new Conda environment named myenv with Python
3.9.
conda create -n myenv python=3.9
Q90. Write the command to remove an existing Conda environment.
conda remove -n myenv --all
Q91. Write the command to display all available Conda environments.
conda env list
Q92. Write the command to activate a Conda environment.
conda activate myenv
Q93. Write the command to install NumPy using Conda.
conda install numpy
Q94. Write the command to install Pandas using Conda.
conda install pandas
Q95. Write the command to list installed packages in the current Conda environment.
conda list
Q96. Write the command to deactivate the current Conda environment.
conda deactivate
Q97. Write the command to rename a Conda environment.
conda create -n newenv --clone oldenv
conda remove -n oldenv --all
Q98. Write the command to install the dateutil package using pip.
pip install python-dateutil
Q99. Write the command to install the openpyxl package using pip.
pip install openpyxl
Q100. Write the command to display all installed pip packages.
pip list
Q101. Write the command to save installed pip packages into [Link].
pip freeze > [Link]
Done — all 100+ lab questions properly formatted.
If you want next:
I can convert this into a clean handwritten-style PDF
Or add user input versions (for viva/exam)
Or short theory answers for each (very useful for practical exams)
OOPS IN PYTHON
#1
"""
class person:
name="harry"
def abc(self):
print(f"{[Link]} is present.")
a=person() # instance created
x=[Link]() # method called
print(x)
a=person()
print([Link])
[Link]="ron"
print([Link]) """
""" #2
class person:
def __init__(self,name,occupa on):
[Link]=name
[Link] on=occupa on
a=person("harry","teacher")
print([Link])
print([Link] on)
# write a class calculator capable finding square, cube and square root of a number
class calculator:
def __init__(self,num):
[Link]=num
def square(self):
return [Link]**2
def cube(self):
return [Link]**3
def square_root(self):
return [Link]**0.5
a=calculator(4)
print([Link]())
print([Link]())
print(a.square_root()) """
# CREATE A CLASS PROGRAMMER FOR STORING INFORMATION OF FEW PROGRAMMERS AND PRINT
THEIR DETAILS
""" class programmer:
def __init__(self, name, language):
[Link] = name
[Link] = language
def print_details(self):
print(f"Name: {[Link]}, Language: {[Link]}")
# Crea ng instances of the programmer class
p1 = programmer("Alice", "Python")
p2 = programmer("Bob", "Java")
# Prin ng their details
p1.print_details()
p2.print_details() """
#encapsula on : binds methods and objects together and keeps both safe from outside
interference and misuse.
""" class Calculator:
def __init__(self, a, b):
self._a = a # internal variables (use _ to indicate private)
self._b = b
# Ge er for a
@property
def a(self):
return self._a
# Se er for a
@[Link] er
def a(self, value):
if value < 0:
raise ValueError("a must be non-nega ve")
self._a = value
# Ge er for b
@property
def b(self):
return self._b
@[Link] er
def b(self, value):
self._b = value
# Method: sum
def sum(self):
return self._a + self._b
# Property: square (computed value)
@property
def square(self):
return (self._a ** 2, self._b ** 2)
# Using it
calc = Calculator(3, 4)
print("Sum:", [Link]()) # normal method
print("Square:", [Link]) # property (no brackets!)
calc.a = 10 # uses se er
print("Updated Sum:", [Link]())
"""
#inheritance : allows a new class to inherit proper es and methods from an exis ng class.
""" class Animal:
def __init__(self, name):
[Link] = name
def speak(self):
return "Some sound"
class Dog(Animal):
def speak(self):
return "Woof!"
class Cat(Animal):
def speak(self):
return "Meow!"
dog = Dog("Buddy")
cat = Cat("Whiskers")
print(f"{[Link]} says: {[Link]()}")
print(f"{[Link]} says: {[Link]()}") """
In Python, overloading and overriding are very different ideas:
Overloading → same method name, different arguments (simulated in Python)
Overriding → child class changes parent class method (fully supported)
Let’s see both with clear examples
1. Method Overloading (Simulated)
Python doesn’t support true overloading, so we simulate it.
Example: Calculator (sum)
class Calculator:
def sum(self, *args):
total = 0
for num in args:
total += num
return total
calc = Calculator()
print([Link](2, 3)) #5
print([Link](2, 3, 4)) # 9
print([Link](1, 2, 3, 4)) # 10
What’s happening?
One method handles mul ple argument cases
This mimics overloading
2. Method Overriding (Real OOP Feature)
This uses inheritance.
Example: Calculator (square)
class Calculator:
def square(self, x):
return x * x
class AdvancedCalculator(Calculator):
def square(self, x):
return f"Square is: {x * x}"
calc1 = Calculator()
calc2 = AdvancedCalculator()
print([Link](4)) # 16 (parent)
print([Link](4)) # Square is: 16 (overridden)
Key Difference
Feature Overloading (Python) Overriding (Python)
Support Not direct Fully supported
Concept Same method, diff args Same method, diff behavior
Requires class Not necessary Yes (inheritance)
Example tool *args, defaults Child class
Simple Way to Remember
Overloading → same name, different inputs
Overriding → same name, different behavior
@decorator used to update a pre-exis ng func on
A func on is passed into another func on to update the parent func on.
In Python, magic methods (also called dunder methods, short for double underscore) are special
methods with names like:
__init__ __str__ __add__ __len__
They let you define how your objects behave with built-in opera ons.
Why “dunder”?
Because they have double underscores before and a er:
__init__
__str__
“dunder” = double underscore
Simple Idea
Magic methods allow your object to work with:
+ → __add__
print() → __str__
len() → __len__
== → __eq__
Example: Calculator with Magic Methods
class Calculator:
def __init__(self, value):
[Link] = value
def __str__(self):
return f"Calculator value: {[Link]}"
def __add__(self, other):
return Calculator([Link] + [Link])
def __len__(self):
return [Link]
c1 = Calculator(5)
c2 = Calculator(3)
print(c1) # uses __str__
c3 = c1 + c2 # uses __add__
print(c3) # Calculator value: 8
print(len(c1)) # uses __len__
What’s happening?
Opera on Magic Method
print(obj) __str__
obj1 + obj2 __add__
len(obj) __len__
object crea on __init__
Common Magic Methods
__init__ → constructor
__str__ → string representa on
__repr__ → developer-friendly output
__add__ → + operator
__sub__ → - operator
__eq__ → == comparison
Important
You don’t call them directly:
c1.__add__(c2) # not recommended
Instead:
c1 + c2 # Python calls it internally
Real Meaning
Magic methods let your custom objects behave like built-in types (int, list, etc.)
One-line takeaway
Dunder methods = special hooks that connect your class to Python’s built-in opera ons.
If you want, I can show:
real-life examples (bank account, vector math)
or a full list of most-used dunder methods for exams