Unit 1: Viva Questions

Module-wise viva questions for Unit 1

Module 1: Basic Syntax and Data Types - Variables, Data types, Operators, Input and Output

Q1. What is Python? Why is it popular?

Show Answer

Answer:

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

Why it's popular:

  • Easy to learn and read - simple syntax
  • Interpreted language - no compilation needed
  • Platform-independent - write once, run anywhere
  • Large standard library and packages
  • Supports multiple programming paradigms
  • Great community support
  • Used in AI, ML, web development, data science

Q2. What are variables? How do you declare them in Python?

Show Answer

Answer:

Variables are containers for storing data values. In Python, you don't need to explicitly declare variables or their type.

# Simple variable declaration
name = "John"
age = 25
height = 5.9
is_student = True

# Multiple assignment
x, y, z = 1, 2, 3

# Dynamic typing
var = 10      # integer
var = "hello" # now it's a string

Naming conventions:

  • Use lowercase letters
  • Use underscores for multiple words
  • Start with letter or underscore
  • Cannot start with a number

Q3. What are the basic data types in Python?

Show Answer

Answer:

Python has several built-in data types:

Data Type Description Example
int Integer numbers 5, -10, 0
float Decimal numbers 3.14, -2.5
str Text/strings "hello", 'world'
bool Boolean True, False
list Ordered collection [1, 2, 3]
tuple Immutable collection (1, 2, 3)
dict Key-value pairs {"name": "John"}
set Unique items {1, 2, 3}

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

Show Answer

Answer:

Operators are symbols used to perform operations on variables and values.

Types of operators:

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

print(a + b)    # 13 (addition)
print(a - b)    # 7 (subtraction)
print(a * b)    # 30 (multiplication)
print(a / b)    # 3.33 (division)
print(a // b)   # 3 (floor division)
print(a % b)    # 1 (modulus)
print(a ** b)   # 1000 (exponentiation)

Q5. What's the difference between / and // operators?

Show Answer

Answer:

  • / (Division): Returns quotient as float
  • // (Floor Division): Returns quotient as integer (rounded down)
print(10 / 3)   # 3.333... (float)
print(10 // 3)  # 3 (integer)
print(-10 / 3)  # -3.333...
print(-10 // 3) # -4 (rounded down to nearest integer)

Q6. What is the difference between == and is?

Show Answer

Answer:

  • ==: Compares VALUES of two objects
  • is: Compares if two objects are the SAME OBJECT in memory (identity)
a = [1, 2, 3]
b = [1, 2, 3]
c = a

print(a == b)  # True (same values)
print(a is b)  # False (different objects)
print(a is c)  # True (same reference)

Q7. How do you take input from the user in Python?

Show Answer

Answer:

Use the input() function to take input from the user. It always returns a string.

# Basic input
name = input("Enter your name: ")
print(name)  # Returns string

# Converting input to other types
age = int(input("Enter your age: "))
height = float(input("Enter your height: "))

# Multiple inputs
x, y = input("Enter two values: ").split()

# Getting input with default message
city = input()  # Will wait for user input

Q8. How do you display output in Python?

Show Answer

Answer:

Use the print() function to display output.

# Basic print
print("Hello, World!")

# Print multiple values
print("Name:", "John", "Age:", 25)

# Print with separator
print("apple", "banana", "cherry", sep=", ")

# Print with end parameter
print("Hello", end=" ")
print("World")  # Output: Hello World

# F-strings (formatted strings)
name = "Alice"
age = 25
print(f"Name: {name}, Age: {age}")

# String formatting
print("I have {} apples".format(10))
print("Name: %s, Age: %d" % ("Bob", 30))

Q9. What is type conversion? Give examples.

Show Answer

Answer:

Type conversion is converting one data type to another.

# Convert to int
int("123")     # 123
int(45.67)     # 45
int(True)      # 1

# Convert to float
float("3.14")  # 3.14
float(10)      # 10.0
float(True)    # 1.0

# Convert to string
str(123)       # "123"
str(3.14)      # "3.14"
str(True)      # "True"

# Convert to boolean
bool(1)        # True
bool(0)        # False
bool("")       # False
bool("text")   # True
bool([])       # False
bool([1, 2])   # True

Q10. What happens if you try to add a string and a number?

Show Answer

Answer:

You will get a TypeError because Python cannot directly add incompatible types.

print("Hello" + 5)  # TypeError: can only concatenate str (not "int") to str

# Solution 1: Convert number to string
print("Hello" + str(5))  # Output: Hello5

# Solution 2: Use f-string
print(f"Hello {5}")  # Output: Hello 5

Module 2: Data Structures - List, Tuple, Set and Dictionary

Q1. What is a list? How do you create and access elements?

Show Answer

Answer:

A list is an ordered, mutable (changeable) collection of items enclosed in square brackets.

# Creating a list
numbers = [1, 2, 3, 4, 5]
fruits = ["apple", "banana", "cherry"]
mixed = [1, "hello", 3.14, True]
empty_list = []

# Accessing elements
print(fruits[0])      # apple (first element)
print(fruits[-1])     # cherry (last element)
print(fruits[1:3])    # ['banana', 'cherry'] (slicing)

# Modifying elements
fruits[0] = "orange"
fruits.append("date")
fruits.extend([1, 2])
fruits.insert(1, "grape")

Q2. What is the difference between list and tuple?

Show Answer

Answer:

Feature List Tuple
Mutability Mutable (can change) Immutable (fixed)
Syntax [1, 2, 3] (1, 2, 3)
Performance Slower Faster
Dict Keys Cannot be used Can be used
Methods More methods Fewer methods
# List example
list = [1, 2, 3]
list[0] = 10  # Allowed

# Tuple example
tuple = (1, 2, 3)
tuple[0] = 10  # Error: 'tuple' object does not support item assignment

Q3. What is a tuple and what are its advantages?

Show Answer

Answer:

A tuple is an ordered, immutable collection of items enclosed in parentheses.

# Creating tuples
colors = ("red", "green", "blue")
single = (1,)  # Note the comma for single element
mixed = (1, "hello", 3.14, True)

# Accessing elements
print(colors[0])  # red
print(colors[1:]) # ('green', 'blue')

Advantages:

  • Immutability ensures data integrity
  • Can be used as dictionary keys
  • Slightly faster than lists
  • Prevent accidental modifications
  • Thread-safe for concurrent access

Q4. What are sets? How are they different from lists?

Show Answer

Answer:

A set is an unordered collection of unique items enclosed in curly braces.

# Creating sets
numbers = {1, 2, 3, 2, 1}  # {1, 2, 3} - duplicates removed
colors = {"red", "green", "blue"}
empty_set = set()  # Note: {} creates empty dict, not set

# Adding elements
colors.add("yellow")

# Removing elements
colors.remove("red")      # Error if not found
colors.discard("green")   # No error if not found

Differences from lists:

  • Unordered (no indexing)
  • No duplicates allowed
  • Mutable (can add/remove elements)
  • Faster membership testing
  • Cannot contain unhashable types

Q5. What are set operations? Give examples.

Show Answer

Answer:

Sets support mathematical operations.

a = {1, 2, 3}
b = {3, 4, 5}

# Union - all elements from both sets
print(a | b)        # {1, 2, 3, 4, 5}
print(a.union(b))   # {1, 2, 3, 4, 5}

# Intersection - common elements
print(a & b)              # {3}
print(a.intersection(b))  # {3}

# Difference - elements in first set but not in second
print(a - b)         # {1, 2}
print(a.difference(b))  # {1, 2}

# Symmetric Difference - elements in either set but not both
print(a ^ b)                  # {1, 2, 4, 5}
print(a.symmetric_difference(b))  # {1, 2, 4, 5}

Q6. What is a dictionary? How do you create and access elements?

Show Answer

Answer:

A dictionary is an unordered, mutable collection of key-value pairs enclosed in curly braces.

# Creating dictionaries
student = {
    "name": "John",
    "age": 20,
    "city": "NYC",
    "marks": [90, 85, 88]
}

# Accessing values
print(student["name"])       # John
print(student.get("age"))    # 20
print(student.get("email", "Not found"))  # Not found

# Modifying values
student["age"] = 21
student["email"] = "john@example.com"

# Removing items
del student["email"]
student.pop("city")

Q7. What dictionary methods do you know?

Show Answer

Answer:

d = {"a": 1, "b": 2, "c": 3}

# Get keys, values, and items
print(d.keys())        # dict_keys(['a', 'b', 'c'])
print(d.values())      # dict_values([1, 2, 3])
print(d.items())       # dict_items([('a', 1), ('b', 2), ('c', 3)])

# Get value with default
print(d.get("a", 0))   # 1
print(d.get("x", 0))   # 0

# Update dictionary
d.update({"d": 4})     # Add new key-value
d.update({"a": 10})    # Modify existing key

# Clear and copy
d.clear()              # Remove all items
copy = d.copy()        # Create a copy

# Check if key exists
print("a" in d)        # True
print("x" in d)        # False

# Pop and popitem
d.pop("a")             # Remove and return value
d.popitem()            # Remove last item

Q8. What is list slicing? Explain with examples.

Show Answer

Answer:

Slicing extracts a portion of a sequence using [start:end:step] syntax.

list = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

# Basic slicing
print(list[0:5])       # [0, 1, 2, 3, 4] (start=0, end=5)
print(list[2:7])       # [2, 3, 4, 5, 6]

# Omit start or end
print(list[:5])        # [0, 1, 2, 3, 4] (from beginning)
print(list[5:])        # [5, 6, 7, 8, 9] (to end)

# Step parameter
print(list[::2])       # [0, 2, 4, 6, 8] (every 2nd)
print(list[1::2])      # [1, 3, 5, 7, 9]

# Negative indices
print(list[-3:])       # [7, 8, 9] (last 3)
print(list[:-2])       # [0, 1, 2, 3, 4, 5, 6, 7] (all except last 2)

# Reverse
print(list[::-1])      # [9, 8, 7, 6, 5, 4, 3, 2, 1, 0]

Q9. What is the difference between mutable and immutable data types?

Show Answer

Answer:

Mutable Immutable
Can be changed after creation Cannot be changed after creation
list, dict, set int, float, str, tuple, bool
Slower Faster
Not usable as dict keys Can be used as dict keys
# Mutable
list = [1, 2, 3]
list[0] = 10  # Allowed

# Immutable
string = "hello"
string[0] = "H"  # Error: 'str' object does not support item assignment

Q10. How do you check if an element exists in a list or dictionary?

Show Answer

Answer:

Use the in operator to check membership.

# Check in list
fruits = ["apple", "banana", "cherry"]
if "apple" in fruits:
    print("Apple is in the list")

# Check in dictionary (checks keys by default)
student = {"name": "John", "age": 20}
if "name" in student:
    print("Name key exists")

if "John" in student.values():
    print("John is a value")

# Check in tuple
colors = ("red", "green", "blue")
if "red" in colors:
    print("Red is in colors")

# Using index for list (will raise error if not found)
try:
    index = fruits.index("banana")
    print(f"Banana is at index {index}")
except ValueError:
    print("Not found")

Module 3: Understanding the Syntax Transition: From C to Python

Q1. What are the major differences between C and Python?

Show Answer

Answer:

Aspect C Python
Compilation Compiled language Interpreted language
Variable Declaration Must declare type Dynamic typing
Syntax Complex, uses {} Simple, uses indentation
Speed Faster execution Slower execution
Memory Management Manual (malloc/free) Automatic (garbage collection)
Functions void, int, char, etc. def keyword

Q2. How does variable declaration differ between C and Python?

Show Answer

Answer:

C (Static typing):

// Must declare type
int age = 25;
float height = 5.9;
char name[] = "John";
int arr[5] = {1, 2, 3, 4, 5};

Python (Dynamic typing):

# No need to declare type
age = 25              # Automatically int
height = 5.9          # Automatically float
name = "John"         # Automatically str
arr = [1, 2, 3, 4, 5] # Automatically list

# Type can change
var = 10      # int
var = "hello" # Now string

Q3. Explain indentation in Python vs braces in C.

Show Answer

Answer:

C (Uses braces {}):

if (age > 18) {
    printf("You are an adult");
} else {
    printf("You are a minor");
}

for (int i = 0; i < 5; i++) {
    printf("%d\n", i);
}

Python (Uses indentation):

if age > 18:
    print("You are an adult")
else:
    print("You are a minor")

for i in range(5):
    print(i)

Key points:

  • Python uses indentation (whitespace) to define code blocks
  • C uses curly braces {} for code blocks
  • Python indentation must be consistent
  • Python is more readable due to enforced indentation

Q4. How do you print in C vs Python?

Show Answer

Answer:

C (printf):

#include <stdio.h>

printf("Hello, World!\n");
printf("Name: %s, Age: %d\n", "John", 25);
printf("Height: %.2f\n", 5.9);

Python (print):

print("Hello, World!")
print("Name:", "John", "Age:", 25)
print(f"Name: John, Age: 25")
print("Height: {:.2f}".format(5.9))

Q5. How does input work in C vs Python?

Show Answer

Answer:

C (scanf):

#include <stdio.h>

int age;
char name[50];

scanf("%d", &age);
scanf("%s", name);
printf("Age: %d, Name: %s\n", age, name);

Python (input):

age = int(input("Enter age: "))
name = input("Enter name: ")
print(f"Age: {age}, Name: {name}")

Differences:

  • C requires format specifiers (%d, %s, etc.)
  • Python input() always returns string
  • Python simpler and more intuitive
  • C requires variable declaration before input

Q6. How do you declare and use arrays in C vs Python?

Show Answer

Answer:

C (Fixed-size arrays):

int arr[5] = {1, 2, 3, 4, 5};
printf("%d\n", arr[0]);  // Access first element

// Cannot change size after creation
char name[50];  // Fixed 50 characters

Python (Dynamic lists):

arr = [1, 2, 3, 4, 5]
print(arr[0])  # Access first element

# Can change size dynamically
arr.append(6)
arr.extend([7, 8])
arr.insert(0, 0)  # Insert at position

name = "Hello"  # String can grow

Key differences:

  • C arrays have fixed size
  • Python lists are dynamic
  • C requires contiguous memory
  • Python lists are more flexible

Q7. How do you define functions in C vs Python?

Show Answer

Answer:

C (Must specify return type):

int add(int a, int b) {
    return a + b;
}

void greet() {
    printf("Hello!\n");
}

int main() {
    int result = add(5, 3);
    greet();
    return 0;
}

Python (Dynamic return types):

def add(a, b):
    return a + b

def greet():
    print("Hello!")

# Can return different types
def get_value(choice):
    if choice == 1:
        return 10      # int
    else:
        return "text"  # string

Q8. What is the purpose of header files in C? Does Python need them?

Show Answer

Answer:

C (Header files):

#include <stdio.h>   // Standard I/O
#include <stdlib.h>  // Standard library
#include <string.h>  // String functions
#include "myheader.h" // Custom header

Purpose:

  • Declare functions before use
  • Import standard libraries
  • Avoid duplication of declarations

Python (No headers needed):

import math        # Import module
from os import path  # Import specific function
from math import sqrt, pi  # Import multiple

Key differences:

  • Python uses import instead of #include
  • Python modules are loaded at runtime
  • No separate compilation needed

Q9. How does memory management differ between C and Python?

Show Answer

Answer:

C (Manual memory management):

#include <stdlib.h>

int *ptr = (int *)malloc(sizeof(int) * 5);  // Allocate
ptr[0] = 10;
free(ptr);  // Must free memory

// Memory leaks if you forget free()

Python (Automatic garbage collection):

list = [1, 2, 3, 4, 5]
# Memory automatically freed when not needed
del list  # Optional, automatic cleanup happens

Differences:

  • C requires malloc/free
  • Python has automatic garbage collection
  • C faster but error-prone
  • Python safer but slightly slower

Q10. What are the advantages of learning Python after C?

Show Answer

Answer:

  • Better understanding of fundamentals: C teaches low-level concepts
  • Appreciation for high-level features: Python's automatic memory management feels effortless
  • Faster development: Python allows rapid prototyping
  • Reduced bugs: Python's dynamic typing catches errors early
  • Better readability: Python's syntax is more intuitive
  • Applicable to modern domains: Python is used in AI, ML, Data Science
  • Easy transition: Both are procedural, making the shift easier