Python Programming Important Questions & Answers
UNIT 1: Python Basics
Q1: Explain the features of Python and compare it with other programming languages.
Python is a high-level, interpreted language known for its simplicity.
Features:
- Easy to Learn and Use
- Interpreted and Dynamically Typed
- Portable and Platform Independent
- Extensive Standard Libraries
- Supports OOP and Functional Programming
Comparison:
| Feature | Python | Java | C++ |
|------------|----------|----------|---------|
| Syntax | Simple | Verbose | Complex |
| Typing | Dynamic | Static | Static |
| Usage | General-purpose | Enterprise | System/Hardware
UNIT 2: Control Structures & Functions
Q2: Write a Python program to print prime numbers from 1 to 100.
for num in range(2, 101):
is_prime = True
for i in range(2, int(num**0.5)+1):
if num % i == 0:
is_prime = False
break
if is_prime:
print(num, end=" ")
Q3: Explain functions in Python with default and keyword arguments.
Python Programming Important Questions & Answers
def greet(name="User", msg="Welcome"):
print(f"Hello {name}, {msg}!")
greet()
greet("Niraj")
greet(msg="Good Morning")
UNIT 3: Data Structures
Q4: Compare list, tuple, set, and dictionary in Python.
| Type | Ordered | Mutable | Duplicates | Syntax |
|------------|---------|---------|------------|--------------------|
| List | Yes | Yes | Yes | [1, 2, 3] |
| Tuple | Yes | No | Yes | (1, 2, 3) |
| Set | No | Yes | No | {1, 2, 3} |
| Dictionary | Yes | Yes | Keys unique| {'a':1, 'b':2} |
Q5: Write a program to count frequency of characters in a string using dictionary.
string = "pythonprogramming"
freq = {}
for char in string:
freq[char] = freq.get(char, 0) + 1
print(freq)
UNIT 4: OOP in Python
Q6: Explain class, object, and constructor with example.
class Student:
def __init__(self, name, age):
Python Programming Important Questions & Answers
self.name = name
self.age = age
def show(self):
print(f"Name: {self.name}, Age: {self.age}")
s1 = Student("Niraj", 20)
s1.show()
Q7: Explain inheritance in Python with types and example.
class Animal:
def speak(self):
print("Animal speaks")
class Dog(Animal):
def bark(self):
print("Dog barks")
d = Dog()
d.speak()
d.bark()
UNIT 5: Files & Exceptions
Q8: Write a program to read from and write to a file.
with open("demo.txt", "w") as f:
f.write("Hello Python\nWelcome!")
with open("demo.txt", "r") as f:
content = f.read()
print(content)
Python Programming Important Questions & Answers
Q9: Explain exception handling in Python with example.
try:
x = int(input("Enter a number: "))
y = 10 / x
except ZeroDivisionError:
print("Cannot divide by zero")
except ValueError:
print("Invalid input")
finally:
print("Execution completed")
Q10: Differentiate module and package with example.
- Module: A single Python file (e.g. math.py)
- Package: A directory with multiple modules and __init__.py
Example:
import math
print(math.sqrt(16))