CS306 – Introduction to Python: Midterm Important Subjective (30 Solved Q&As)
Virtual University of Pakistan • Read every solved subjective question with its model answer directly on this page. Free, no login required.
All 664 Midterm Packs · CS306 Course Page · CS306 MCQ Pack (92 MCQs)
-
What is Python? Write any five features of Python.
Topic: Python Basics
Python is a high-level, interpreted, general-purpose programming language developed by Guido van Rossum. It emphasizes simple, readable syntax, so programs can be written in fewer lines of code. Main features: 1. Easy to learn and use because of its simple syntax. 2. Interpreted language, so code is executed line by line and is easy to test and debug. 3. Free and open source. 4. Portable: the same program runs on Windows, Linux and macOS without changes. 5. Dynamically typed and supported by a very large standard library.
-
Differentiate between a compiler and an interpreter.
Topic: Python Basics
Compiler: translates the whole source program into machine code at once before execution; execution is fast, but errors are reported only after the complete scan of the program. Examples: C, C++. Interpreter: translates and executes the program line by line; execution is slower, but errors are detected and reported immediately at the faulty line. Python uses an interpreter, which makes it easy to test and debug small programs.
-
What is indentation in Python? Why is it important?
Topic: Python Basics
Indentation means the spaces (or tabs) used at the beginning of a line of code. In Python, indentation is not just for readability; it defines the block of code that belongs to a statement such as if, for, while or a function. All statements in one block must have the same indentation. Wrong or missing indentation causes an IndentationError, and the program does not run.
-
What is a variable? Write the rules for naming variables in Python.
Topic: Variables and Data Types
A variable is a named memory location used to store a value, for example: age = 20. Rules for naming variables: 1. A variable name can contain letters (a-z, A-Z), digits (0-9) and underscore (_). 2. It must start with a letter or underscore; it cannot start with a digit. 3. It cannot contain spaces or special symbols such as @, #, $. 4. Python keywords (if, for, class, etc.) cannot be used as variable names. 5. Variable names are case-sensitive, so Age and age are different variables.
-
Name and explain the basic data types of Python with examples.
Topic: Variables and Data Types
1. int: stores whole numbers, e.g. x = 10. 2. float: stores decimal numbers, e.g. price = 99.5. 3. str: stores text in quotes, e.g. name = "Ali". 4. bool: stores True or False, e.g. passed = True. 5. complex: stores complex numbers, e.g. c = 2 + 3j. The type of a value stored in a variable can be checked with the type() function.
-
Differentiate between mutable and immutable data types with examples.
Topic: Variables and Data Types
Mutable data types can be changed after their creation; their values can be modified in the same memory location. Examples: list, dictionary and set. For example, a list element can be replaced: a = [1, 2, 3]; a[0] = 9. Immutable data types cannot be changed after creation; any change creates a new object. Examples: int, float, str and tuple. For example, a string character cannot be replaced: s = "Ali"; s[0] = 'B' gives an error.
-
What is type conversion? Differentiate between implicit and explicit type conversion.
Topic: Variables and Data Types
Type conversion means changing a value from one data type to another. Implicit conversion is done automatically by Python, e.g. in 5 + 2.5 the integer 5 is automatically converted to float and the result is 7.5. Explicit conversion (type casting) is done by the programmer using functions such as int(), float() and str(), e.g. int("25") gives the integer 25, and int(7.9) gives 7.
-
Explain the arithmetic operators used in Python with examples.
Topic: Operators
Arithmetic operators perform mathematical operations: + Addition: 5 + 3 = 8 - Subtraction: 5 - 3 = 2 * Multiplication: 5 * 3 = 15 / Division: 5 / 2 = 2.5 (always gives a float result) // Floor division: 5 // 2 = 2 (gives the quotient without the decimal part) % Modulus: 5 % 2 = 1 (gives the remainder) ** Exponent (power): 2 ** 3 = 8
-
Differentiate between the / and // operators, and between the = and == operators.
Topic: Operators
/ is the division operator and always returns a float result, e.g. 10 / 2 = 5.0. // is the floor division operator and returns only the whole-number part of the division, e.g. 10 // 3 = 3. = is the assignment operator; it stores a value in a variable, e.g. x = 5. == is the equality (comparison) operator; it checks whether two values are equal and returns True or False, e.g. x == 5 returns True if x is 5.
-
Explain the logical operators (and, or, not) used in Python.
Topic: Operators
Logical operators combine conditions and return True or False. and: returns True only when both conditions are True. Example: (5 > 3 and 2 < 4) is True. or: returns True when at least one condition is True. Example: (5 > 9 or 2 < 4) is True. not: reverses the result of a condition. Example: not (5 > 9) is True because 5 > 9 is False.
-
What is a string? Explain string indexing with an example.
Topic: Strings
A string is a sequence of characters written in single, double or triple quotes, e.g. s = "Python". Each character has a position called an index. Positive indexing starts from 0 at the left: s[0] is 'P', s[1] is 'y'. Negative indexing starts from -1 at the right: s[-1] is 'n', s[-2] is 'o'. Strings are immutable, so a character cannot be changed in place.
-
Explain string slicing with an example.
Topic: Strings
Slicing means extracting a part (substring) of a string using the syntax s[start : stop : step]. The character at the stop index is not included. For s = "Python": s[0:3] gives 'Pyt' s[2:] gives 'thon' s[:4] gives 'Pyth' s[::2] gives 'Pto' (every second character) s[::-1] gives 'nohtyP' (the reversed string)
-
Explain any five string methods/functions with examples.
Topic: Strings
Let s = " Python Programming " and t = "python". 1. upper(): converts to uppercase: t.upper() gives 'PYTHON'. 2. lower(): converts to lowercase: "PYTHON".lower() gives 'python'. 3. strip(): removes whitespace from both ends: s.strip() gives 'Python Programming'. 4. replace(): replaces a substring: t.replace('p', 'P') gives 'Python'. 5. split(): splits a string into a list: "a,b,c".split(',') gives ['a', 'b', 'c']. The built-in function len() gives the number of characters: len(t) is 6.
-
Explain the if, if-else and if-elif-else statements with syntax.
Topic: Conditional Statements
These statements are used for decision making. if: runs a block only when the condition is True. if condition: statements if-else: runs one block when the condition is True and another block when it is False. if condition: statements else: statements if-elif-else: checks several conditions one by one; the block of the first True condition runs, and else runs when no condition is True. if condition1: statements elif condition2: statements else: statements
-
Write a Python program to check whether a number is even or odd.
Topic: Conditional Statements
n = int(input("Enter a number: ")) if n % 2 == 0: print("Even number") else: print("Odd number") Explanation: the modulus operator % gives the remainder after division by 2. If the remainder is 0, the number is even; otherwise it is odd.
-
Write a Python program to find the largest of three numbers.
Topic: Conditional Statements
a = int(input("Enter first number: ")) b = int(input("Enter second number: ")) c = int(input("Enter third number: ")) if a >= b and a >= c: print("Largest is", a) elif b >= a and b >= c: print("Largest is", b) else: print("Largest is", c)
-
Differentiate between the for loop and the while loop in Python.
Topic: Loops
for loop: used when the number of iterations is known in advance. It repeats a block for each value of a sequence (such as range or a string). Example: for i in range(5): print(i). while loop: used when the number of iterations is not known in advance. It repeats the block as long as its condition remains True, and the condition is checked before every iteration. Example: i = 1; while i <= 5: print(i); i += 1.
-
Explain the range() function with its three forms.
Topic: Loops
range() generates a sequence of numbers and is commonly used with the for loop. It has three forms: 1. range(stop): numbers from 0 to stop-1. range(5) gives 0, 1, 2, 3, 4. 2. range(start, stop): numbers from start to stop-1. range(2, 6) gives 2, 3, 4, 5. 3. range(start, stop, step): numbers from start to stop-1 with the given step. range(2, 11, 2) gives 2, 4, 6, 8, 10. A negative step counts downwards, e.g. range(5, 0, -1) gives 5, 4, 3, 2, 1.
-
Differentiate between the break and continue statements with examples.
Topic: Loops
break: immediately terminates the whole loop and control moves to the statement after the loop. Example: printing numbers but stopping at 3: for i in range(1, 10): if i == 4: break print(i) Output: 1 2 3 continue: skips the remaining part of the current iteration and moves to the next iteration. Example: printing numbers but skipping 3: for i in range(1, 6): if i == 3: continue print(i) Output: 1 2 4 5
-
Write a Python program to calculate the sum of the first 10 natural numbers.
Topic: Loops
s = 0 for i in range(1, 11): s += i print("Sum =", s) Output: Sum = 55 Explanation: range(1, 11) generates the numbers 1 to 10, and each number is added to the accumulator variable s in every iteration.
-
What is a function in Python? Write its benefits.
Topic: Functions
A function is a block of organized, reusable code that performs a specific task. It is defined once with the def keyword and can be called many times. Benefits of functions: 1. Code reusability: the same code is not written again and again. 2. Modularity: a large program is divided into small, manageable parts. 3. Easier debugging: each function can be tested and corrected separately. 4. Better readability and maintenance of the program.
-
Differentiate between parameters and arguments. Also explain default arguments with an example.
Topic: Functions
Parameters are the variables written in the function definition, while arguments are the actual values passed to the function when it is called. In def add(a, b):, a and b are parameters; in the call add(2, 3), 2 and 3 are arguments. Default arguments: a parameter can be given a default value in the definition. If the caller does not pass a value, the default value is used. def greet(name="Ali"): print("Hello", name) greet() prints "Hello Ali", while greet("Sara") prints "Hello Sara".
-
Explain the return statement. How can a function return multiple values in Python?
Topic: Functions
The return statement ends the execution of a function and sends a value back to the caller. A function without a return statement returns None by default. In Python, a function can return more than one value by separating them with commas; the values are packed into a tuple and can be unpacked at the caller side. def calc(a, b): return a + b, a - b s, d = calc(10, 4) Here s becomes 14 and d becomes 6.
-
Differentiate between local and global variables with an example.
Topic: Functions
Local variables are defined inside a function and can be used only within that function. Global variables are defined outside all functions and can be used anywhere in the program. x = 10 # global variable def show(): y = 5 # local variable print(x, y) show() prints 10 5. Here x is accessible inside the function, but y cannot be used outside show().
-
Write a function in Python to calculate the factorial of a number.
Topic: Functions
def factorial(n): fact = 1 for i in range(1, n + 1): fact *= i return fact print(factorial(5)) Output: 120 Explanation: the function multiplies all numbers from 1 to n. For n = 5: 1 x 2 x 3 x 4 x 5 = 120.
-
What is a list in Python? Explain any four list methods.
Topic: Lists and Dictionaries
A list is an ordered, mutable collection of values written in square brackets, e.g. a = [10, 20, 30]. Elements are accessed by index starting from 0. Common list methods: 1. append(x): adds x at the end: a.append(40) gives [10, 20, 30, 40]. 2. insert(i, x): inserts x at index i: a.insert(1, 15) gives [10, 15, 20, 30]. 3. remove(x): removes the first occurrence of x: a.remove(20) gives [10, 30]. 4. sort(): arranges the elements in ascending order. The function len(a) gives the number of elements in the list.
-
Differentiate between a list and a tuple in Python.
Topic: Lists and Dictionaries
List: written in square brackets [ ], it is mutable, so elements can be added, removed or changed after creation. Example: a = [1, 2, 3]. Tuple: written in parentheses ( ), it is immutable, so its elements cannot be changed after creation. Example: b = (1, 2, 3). Tuples are used for fixed data, while lists are used when the data needs to be modified.
-
What is a dictionary in Python? How are values accessed in a dictionary? Give an example.
Topic: Lists and Dictionaries
A dictionary is a collection of data stored in key-value pairs, written in curly braces. Each value is accessed through its unique key instead of an index. student = {"name": "Ali", "age": 20, "city": "Lahore"} print(student["name"]) gives Ali print(student["age"]) gives 20 New pairs can be added, e.g. student["marks"] = 85, and an existing value can be updated through its key. The keys() and values() methods return all keys and all values of the dictionary.
-
Write a Python program to reverse a string.
Topic: Programs
s = input("Enter a string: ") rev = s[::-1] print("Reversed string:", rev) Explanation: the slice s[::-1] starts from the end of the string and moves backwards with step -1, producing the reversed string. For input "Python", the output is "nohtyP". The same result can be obtained with a loop that adds each character to the front of a new string.
-
Write a Python program to print the multiplication table of a given number.
Topic: Programs
n = int(input("Enter a number: ")) for i in range(1, 11): print(n, "x", i, "=", n * i) For n = 5, the output is: 5 x 1 = 5 5 x 2 = 10 ... 5 x 10 = 50