Theory & Viva Questions

Important short-answer questions for exams and interviews

Unit I - Introduction to Python

Q1. What is Python? List its features.

Python is a high-level, interpreted, general-purpose programming language created by Guido van Rossum in 1991.

Features:

  • Easy to learn and read (simple syntax)
  • Interpreted language (no compilation needed)
  • Dynamically typed
  • Object-oriented and functional programming support
  • Extensive standard library
  • Platform independent
  • Open source and free

Q2. What are variables in Python? How are they declared?

Variables are containers that store data values. In Python, variables are created when you assign a value to them.

Declaration: No explicit declaration needed. Just assign a value:

x = 10, name = "John", pi = 3.14

Rules: Must start with letter/underscore, can contain alphanumeric characters, case-sensitive.

Q3. Explain Python data types with examples.

  • int: Integer numbers → x = 10
  • float: Decimal numbers → y = 3.14
  • str: Text/strings → name = "Python"
  • bool: True/False → is_valid = True
  • list: Ordered, mutable → [1, 2, 3]
  • tuple: Ordered, immutable → (1, 2, 3)
  • dict: Key-value pairs → {"a": 1}
  • set: Unique elements → {1, 2, 3}

Q4. What are operators in Python? List different types.

  • Arithmetic: +, -, *, /, //, %, **
  • Comparison: ==, !=, >, <, >=, <=
  • Logical: and, or, not
  • Assignment: =, +=, -=, *=, /=
  • Bitwise: &, |, ^, ~, <<, >>
  • Identity: is, is not
  • Membership: in, not in

Q5. Differentiate between compiled and interpreted languages.

CompiledInterpreted
Converts entire code at onceExecutes line by line
Faster executionSlower execution
Errors shown after compilationErrors shown at runtime
Examples: C, C++, JavaExamples: Python, JavaScript

Q6. What is type casting? Explain with examples.

Type casting is converting one data type to another.

Implicit: Python automatically converts → x = 5 + 2.0 (int to float)

Explicit: Manual conversion using functions:

  • int("10") → 10
  • float(5) → 5.0
  • str(100) → "100"
  • list("abc") → ['a', 'b', 'c']

Q7. What is the difference between print() and input()?

print(): Displays output to the console

print("Hello World")

input(): Takes input from user (always returns string)

name = input("Enter name: ")

To get numeric input: age = int(input("Enter age: "))

Q8. Explain comments in Python.

Comments are non-executable text for documentation.

Single-line: # This is a comment

Multi-line:

"""
This is a
multi-line comment
"""

Comments improve code readability and are ignored by the interpreter.

Unit II - Program Flow Control

Q1. Explain if-elif-else statement with syntax.

Conditional statements execute code based on conditions:

if condition1:
    # executes if condition1 is True
elif condition2:
    # executes if condition2 is True
else:
    # executes if all conditions are False

Conditions are evaluated top to bottom; first True condition's block executes.

Q2. Differentiate between for and while loop.

for loopwhile loop
Iterates over a sequenceRepeats while condition is True
Known number of iterationsUnknown iterations
for i in range(5):while x < 5:

Q3. What is the purpose of break and continue?

break: Exits the loop immediately

for i in range(10):
    if i == 5:
        break  # Stops at 5

continue: Skips current iteration, continues to next

for i in range(5):
    if i == 2:
        continue  # Skips 2
    print(i)

Q4. Explain range() function with examples.

range() generates a sequence of numbers.

  • range(5) → 0, 1, 2, 3, 4
  • range(2, 8) → 2, 3, 4, 5, 6, 7
  • range(0, 10, 2) → 0, 2, 4, 6, 8
  • range(5, 0, -1) → 5, 4, 3, 2, 1

Syntax: range(start, stop, step)

Q5. What is a nested loop? Give an example.

A nested loop is a loop inside another loop.

for i in range(3):
    for j in range(3):
        print(i, j)

The inner loop completes all iterations for each outer loop iteration.

Use case: Printing patterns, working with 2D arrays/matrices.

Q6. Explain pass statement in Python.

pass is a null statement that does nothing. It's used as a placeholder.

if x > 0:
    pass  # TODO: implement later

def empty_function():
    pass  # Placeholder for future code

Prevents syntax errors when a statement is required but no action is needed.

Q7. What is an infinite loop? How to avoid it?

An infinite loop runs forever because the condition never becomes False.

# Infinite loop (bad)
while True:
    print("Forever")

To avoid:

  • Ensure loop variable is updated
  • Use break statement with condition
  • Set proper termination condition

Q8. What is the else clause in loops?

Python loops can have an else clause that executes when the loop completes normally (not via break).

for i in range(5):
    if i == 10:
        break
else:
    print("Loop completed!")  # This runs

If break is executed, else block is skipped.

Unit III - Data Types & Functions

Q1. Differentiate between List, Tuple, Set, and Dictionary.

FeatureListTupleSetDict
Syntax[1,2](1,2){1,2}{k:v}
MutableYesNoYesYes
OrderedYesYesNoYes*
DuplicatesYesYesNoKeys: No

Q2. What is string slicing? Explain with examples.

Slicing extracts a portion of a string using [start:end:step]

s = "Python"
s[0:3]   → "Pyt"
s[2:]    → "thon"
s[:4]    → "Pyth"
s[-1]    → "n"
s[::-1]  → "nohtyP" (reverse)

Q3. What is a function? Explain types of arguments.

Function: A reusable block of code defined with def keyword.

Types of Arguments:

  • Positional: func(1, 2)
  • Keyword: func(a=1, b=2)
  • Default: def func(a=10):
  • *args: Variable positional arguments
  • **kwargs: Variable keyword arguments

Q4. What is the difference between local and global variables?

Local: Defined inside function, accessible only within that function.

Global: Defined outside functions, accessible everywhere.

x = 10  # Global

def func():
    y = 5  # Local
    global x
    x = 20  # Modify global

Use global keyword to modify global variable inside function.

Q5. Explain list comprehension with examples.

List comprehension: Concise way to create lists.

# Syntax: [expression for item in iterable if condition]

squares = [x**2 for x in range(5)]
# [0, 1, 4, 9, 16]

evens = [x for x in range(10) if x % 2 == 0]
# [0, 2, 4, 6, 8]

Q6. What is the difference between append() and extend()?

lst = [1, 2, 3]

lst.append([4, 5])
# Result: [1, 2, 3, [4, 5]]

lst = [1, 2, 3]
lst.extend([4, 5])
# Result: [1, 2, 3, 4, 5]

append(): Adds element as single item

extend(): Adds each element individually

Q7. What is lambda function? Give examples.

Lambda: Anonymous, single-expression function.

# Syntax: lambda arguments: expression

square = lambda x: x ** 2
add = lambda a, b: a + b

# With map/filter
nums = [1, 2, 3, 4]
squared = list(map(lambda x: x**2, nums))
evens = list(filter(lambda x: x%2==0, nums))

Q8. Explain mutable vs immutable data types.

Mutable: Can be changed after creation

  • list, dict, set

Immutable: Cannot be changed after creation

  • int, float, str, tuple, frozenset
lst = [1, 2]
lst[0] = 10  # OK - mutable

s = "hello"
s[0] = "H"  # Error - immutable

Unit IV - File Operations

Q1. Explain file opening modes in Python.

ModeDescription
'r'Read (default)
'w'Write (overwrites)
'a'Append
'x'Create (fails if exists)
'b'Binary mode
'r+'Read and write

Q2. What is the 'with' statement? Why use it for files?

with statement is a context manager that ensures proper resource handling.

with open("file.txt", "r") as f:
    data = f.read()
# File automatically closed

Benefits:

  • Automatically closes file
  • Handles exceptions properly
  • Cleaner, safer code

Q3. Differentiate between read(), readline(), and readlines().

  • read(): Returns entire file as single string
  • readline(): Returns one line at a time
  • readlines(): Returns list of all lines
f.read()       → "line1\nline2\nline3"
f.readline()   → "line1\n"
f.readlines()  → ["line1\n", "line2\n", "line3"]

Q4. What is the difference between write() and writelines()?

write(): Writes a single string

f.write("Hello World")

writelines(): Writes a list of strings (no newlines added)

f.writelines(["Line1\n", "Line2\n"])

Q5. Explain seek() and tell() methods.

tell(): Returns current file position (in bytes)

seek(offset, whence): Moves to a specific position

f.tell()      → 0 (at start)
f.seek(0)     → Go to beginning
f.seek(5)     → Go to 5th byte
f.seek(0, 2)  → Go to end

whence: 0=start, 1=current, 2=end

Q6. What is exception handling in file operations?

try:
    with open("file.txt", "r") as f:
        data = f.read()
except FileNotFoundError:
    print("File not found!")
except PermissionError:
    print("No permission!")
except Exception as e:
    print(f"Error: {e}")
finally:
    print("Cleanup done")

Q7. How to work with CSV files in Python?

import csv

# Reading CSV
with open("data.csv", "r") as f:
    reader = csv.reader(f)
    for row in reader:
        print(row)

# Writing CSV
with open("data.csv", "w", newline="") as f:
    writer = csv.writer(f)
    writer.writerow(["Name", "Age"])
    writer.writerow(["John", 25])

Q8. What is JSON? How to read/write JSON in Python?

JSON: JavaScript Object Notation - lightweight data format.

import json

# Write JSON
data = {"name": "John", "age": 25}
with open("data.json", "w") as f:
    json.dump(data, f)

# Read JSON
with open("data.json", "r") as f:
    data = json.load(f)

Unit V - Packages & GUI

Q1. What is NumPy? List its advantages.

NumPy: Numerical Python - library for scientific computing.

Advantages:

  • Fast array operations (C-based)
  • Memory efficient
  • Broadcasting capabilities
  • Mathematical functions
  • Linear algebra operations
import numpy as np
arr = np.array([1, 2, 3])

Q2. What is Pandas? Explain DataFrame and Series.

Pandas: Data manipulation and analysis library.

Series: 1D labeled array

s = pd.Series([1, 2, 3])

DataFrame: 2D labeled table (rows & columns)

df = pd.DataFrame({
    "Name": ["A", "B"],
    "Age": [20, 25]
})

Q3. What is Matplotlib? List types of plots.

Matplotlib: Data visualization library for creating static, animated, and interactive plots.

Plot Types:

  • Line plot: plt.plot()
  • Bar chart: plt.bar()
  • Histogram: plt.hist()
  • Scatter plot: plt.scatter()
  • Pie chart: plt.pie()
  • Box plot: plt.boxplot()

Q4. What is Tkinter? Explain basic widgets.

Tkinter: Standard GUI library for Python.

Common Widgets:

  • Label: Display text
  • Button: Clickable button
  • Entry: Single-line text input
  • Text: Multi-line text
  • Frame: Container widget
  • Canvas: Drawing area

Q5. Explain geometry managers in Tkinter.

pack(): Packs widgets in order

label.pack(side="top")

grid(): Places widgets in grid

label.grid(row=0, column=1)

place(): Absolute positioning

label.place(x=50, y=100)

Q6. How to handle events in Tkinter?

Events are handled using command parameter or bind() method.

# Using command
btn = Button(root, text="Click", command=my_func)

# Using bind
widget.bind("<Button-1>", handler)  # Left click
widget.bind("<Return>", handler)   # Enter key

Q7. What is the difference between NumPy array and Python list?

NumPy ArrayPython List
Homogeneous (same type)Heterogeneous
Faster operationsSlower
Less memoryMore memory
Element-wise operationsNeed loops

Q8. How to read CSV files using Pandas?

import pandas as pd

# Read CSV
df = pd.read_csv("data.csv")

# Basic operations
df.head()       # First 5 rows
df.describe()   # Statistics
df.columns      # Column names
df["column"]    # Select column

# Write to CSV
df.to_csv("output.csv", index=False)