Here are 20 long questions with detailed answers based on your syllabus:
SECTION A: Introduction to Python
1. What is Python, and why is it widely used in programming?
Python is a high-level, interpreted programming language known for its simplicity and readability. It was created by Guido van Rossum and first released in 1991. Python is widely used because:
- Ease of Learning: Its syntax is clean and similar to English.
- Versatility: Supports multiple programming paradigms (procedural, object-oriented, functional).
- Extensive Libraries: Has built-in libraries for tasks like web development, data analysis, AI, and automation.
- Community Support: A vast and active user base contributes to its rapid evolution.
- Cross-Platform Compatibility: Can run on Windows, Mac, and Linux.
2. What are the strengths and weaknesses of Python?
Strengths:
- Readability and maintainability
- Large standard library
- Extensive third-party modules
- Portable and cross-platform
- Supports automation and scripting
Weaknesses:
- Slower than compiled languages like C or Java
- Higher memory consumption
- Limited mobile computing support
Python Syntax
3. What are Python identifiers, and what are the rules for naming them?
Identifiers are the names used to identify variables, functions, and objects in Python. Naming rules:
- Must start with a letter (A-Z or a-z) or an underscore (_) but not a number.
- Can contain letters, digits (0-9), and underscores.
- Cannot use Python’s reserved keywords.
- Case-sensitive (e.g.,
Variable
andvariable
are different).
4. Explain the different types of operators in Python with examples.
Python provides various operators:
- Arithmetic Operators:
+
,-
,*
,/
,%
,**
,//
a, b = 10, 3 print(a / b) # 3.3333 print(a // b) # 3 (Floor division)
- Comparison Operators:
==
,!=
,<
,>
,<=
,>=
- Assignment Operators:
=
,+=
,-=
,*=
- Bitwise Operators:
&
,|
,^
,~
,<<
,>>
- Logical Operators:
and
,or
,not
- Membership Operators:
in
,not in
- Identity Operators:
is
,is not
5. How does Python handle data type conversion?
Python allows implicit and explicit type conversion.
- Implicit Conversion (done automatically):
x = 5 # int y = 2.5 # float z = x + y # Python automatically converts int to float print(type(z)) # <class 'float'>
- Explicit Conversion (type casting):
x = 10 y = str(x) # Converts int to string
6. Explain Python’s decision-making structures with examples.
Python supports conditional statements:
- if statement:
x = 10 if x > 5: print("X is greater than 5")
- if-else statement:
if x > 10: print("Greater") else: print("Smaller")
- if-elif-else statement:
if x > 10: print("Greater") elif x == 10: print("Equal") else: print("Smaller")
7. What are Python loops, and how do they work?
Python has two main loops:
- for loop: Iterates over sequences (lists, tuples, dictionaries, etc.).
for i in range(5): print(i) # Prints numbers from 0 to 4
- while loop: Runs as long as a condition is true.
x = 0 while x < 5: print(x) x += 1
8. How do break and continue statements work in Python loops?
- break: Exits the loop prematurely.
for i in range(10): if i == 5: break print(i) # Stops at 4
- continue: Skips the current iteration and proceeds to the next.
for i in range(5): if i == 3: continue print(i) # Skips printing 3
Python Collections
9. What are Python sequences, and what types exist?
Python sequences store collections of data:
- Lists: Ordered, mutable.
- Tuples: Ordered, immutable.
- Strings: Immutable character sequences.
- Dictionaries: Key-value pairs.
- Sets: Unordered, unique items.
10. How do Python lists and tuples differ?
Feature | List | Tuple |
---|---|---|
Mutability | Mutable | Immutable |
Syntax | [] |
() |
Performance | Slower | Faster |
Use case | Dynamic data | Fixed data |
11. How does a dictionary work in Python?
A dictionary stores key-value pairs.
student = {"name": "Alice", "age": 20}
print(student["name"]) # Alice
12. How do you use sets in Python?
A set is a collection of unique elements.
s = {1, 2, 3, 3}
print(s) # {1, 2, 3}
Python Functions
13. What is the difference between global and local variables in Python?
- Local variables exist only within functions.
- Global variables are defined outside functions and accessible inside functions using
global
.
14. How does Python’s lambda function work?
A lambda function is an anonymous function defined using lambda
:
square = lambda x: x*x
print(square(4)) # 16
SECTION B: Python Modules
15. What are Python modules, and how do you use them?
A module is a file containing Python code.
import math
print(math.sqrt(16)) # 4.0
16. What are Python’s built-in modules?
Examples:
sys
(System-specific functions)math
(Mathematical functions)time
(Time-related functions)
17. What is the difference between import and from-import?
import module_name
: Imports the whole module.from module_name import function_name
: Imports specific functions.
Python File Handling
18. How do you read and write files in Python?
# Writing
with open("test.txt", "w") as f:
f.write("Hello, world!")
# Reading
with open("test.txt", "r") as f:
print(f.read())
19. What are the different file access modes in Python?
"r"
: Read"w"
: Write (overwrites existing content)"a"
: Append"r+"
: Read and write
20. How does the OS module help in file handling?
The os
module interacts with the operating system:
import os
print(os.getcwd()) # Prints current directory
os.remove("test.txt") # Deletes a file
Here are another 20 long questions with detailed answers based on your Python syllabus.
SECTION A: Introduction to Python
1. What are the different versions of Python, and how have they evolved?
Python has gone through several versions:
- Python 1.x (1991-2000): First version with basic features.
- Python 2.x (2000-2010): Introduced list comprehensions, garbage collection, etc. (Now deprecated)
- Python 3.x (2008-Present): Major improvements in syntax, Unicode handling, and standard libraries.
2. How do you install Python on a local environment?
- Download Python from python.org.
- Run the installer and check “Add Python to PATH”.
- Verify installation:
python --version
3. How does the Python interactive mode differ from executing scripts?
- Interactive mode: Run Python commands one by one in a REPL (Read-Eval-Print Loop).
python >>> print("Hello")
- Executing from a file: Save the code in a
.py
file and run it.python script.py
Python Syntax
4. What are reserved keywords in Python, and why are they important?
Reserved keywords are words that have special meanings and cannot be used as identifiers:
import keyword
print(keyword.kwlist)
Examples: if
, else
, while
, import
, def
, lambda
.
5. How do you check and modify variable types dynamically in Python?
- Use
type()
to check type. - Use
isinstance()
for type checking.
x = 5
print(type(x)) # <class 'int'>
print(isinstance(x, int)) # True
Python Operators and Control Flow
6. How does operator precedence work in Python?
Operators follow a precedence order:
**
(Exponentiation)* / % //
(Multiplication, Division, Modulus, Floor Division)+ -
(Addition, Subtraction)== != > < >= <=
(Comparison)and
,or
,not
(Logical)
7. How do nested if-else statements work?
x = 10
if x > 5:
if x > 8:
print("Greater than 8")
else:
print("Between 5 and 8")
8. What are ternary operators in Python?
Python supports a one-line if-else
:
x = 10
result = "Even" if x % 2 == 0 else "Odd"
print(result)
9. How do nested loops work, and when are they useful?
Nested loops allow iteration inside another loop:
for i in range(3):
for j in range(2):
print(i, j)
Used for working with matrices, patterns, etc.
Python Collections
10. What are the different ways to initialize lists in Python?
# Empty list
lst1 = []
# List with elements
lst2 = [1, 2, 3]
# List comprehension
lst3 = [x for x in range(5)]
11. What are the common list methods in Python?
lst = [3, 1, 4]
lst.append(5) # Adds element
lst.sort() # Sorts list
lst.remove(1) # Removes element
print(lst)
12. How do you iterate over dictionary keys and values?
student = {"name": "Alice", "age": 22}
for key, value in student.items():
print(key, value)
13. What are set operations in Python?
A = {1, 2, 3}
B = {3, 4, 5}
print(A | B) # Union
print(A & B) # Intersection
Python Functions
14. How do default and keyword arguments work in functions?
def greet(name="User"):
print("Hello,", name)
greet() # Hello, User
greet("Alice") # Hello, Alice
15. What is recursion, and how does it work in Python?
A function calling itself.
def factorial(n):
if n == 1:
return 1
return n * factorial(n-1)
print(factorial(5)) # 120
16. How do list comprehensions work, and when should they be used?
squares = [x**2 for x in range(5)]
print(squares) # [0, 1, 4, 9, 16]
Used for concise and readable list creation.
SECTION B: Python Modules
17. How do you create and use a custom module in Python?
- Create a Python file
mymodule.py
:def greet(): return "Hello!"
- Import in another script:
import mymodule print(mymodule.greet())
18. How do you use the math
module for mathematical calculations?
import math
print(math.sqrt(16)) # 4.0
print(math.pi) # 3.141592653589793
19. What are the functions of the sys
module in Python?
sys.argv
(Command-line arguments)sys.exit()
(Exit script)sys.path
(Module search path)
Python File Handling
20. How do you check if a file exists and delete it?
import os
if os.path.exists("test.txt"):
os.remove("test.txt")
else:
print("File not found")
These 20 additional questions cover more advanced Python concepts, ensuring a strong understanding of the language. Let me know if you need more explanations! 🚀
This covers all major topics from your syllabus with detailed explanations. Let me know if you need more! 🚀
Leave a Reply