0% found this document useful (0 votes)
3 views12 pages

Python Module1 2 Guide

This document is an exam preparation guide for the Python Programming course under the VTU 2025 scheme, covering Modules 1 and 2. It includes key topics, explanations, code examples, and previous year questions related to programming concepts such as variables, functions, strings, tuples, and lists. The guide provides a structured approach to understanding and practicing essential Python programming skills.

Uploaded by

thanvitha02.d
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views12 pages

Python Module1 2 Guide

This document is an exam preparation guide for the Python Programming course under the VTU 2025 scheme, covering Modules 1 and 2. It includes key topics, explanations, code examples, and previous year questions related to programming concepts such as variables, functions, strings, tuples, and lists. The guide provides a structured approach to understanding and practicing essential Python programming skills.

Uploaded by

thanvitha02.d
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Python Programming

VTU 2025 Scheme — Semester I/II

Course Code: 1BPLC105B / 205B | IPCC, 4 Credits

Module 1 & Module 2 — Exam Preparation Guide

Most Important Topics · Previous Year Questions · Explanations & Examples


Based on the official VTU 2025 scheme syllabus
How to Use This Guide

This guide covers Module 1 (The Way of the Program; Variables, Expressions and Statements; Iteration; Functions) and Module 2 (Strings,
Tuples, Lists) of the VTU Python Programming syllabus (2025 scheme, Course Code 1BPLC105B/205B). Each topic includes a clear explanation,
working code with sample output, and the previous-year exam questions it answers.

Question frequency legend: ★ Very Frequently Asked ★ Frequently Asked ★ Occasionally Asked

Contents

Section Topic

Module 1 The Way of the Program (debugging, errors)

Module 1 Variables, Expressions, Statements, Operators

Module 1 Iteration – for loop, while loop, break/continue, nested loops

Module 1 Functions – with arguments and return values

Module 1 Module 1 Important PYQs with Answers

Module 2 Strings – operations, slicing, methods

Module 2 Tuples – assignment, return values

Module 2 Lists – operations, mutability, nested lists

Module 2 Module 2 Important PYQs with Answers


MODULE 1: The Way of the Program, Variables, Iteration & Functions

1.1 The Way of the Program

This topic introduces what a program is and the three types of errors a programmer encounters.

Key Concepts
Program: A sequence of instructions that specifies how to perform a computation (input, output, math, conditional execution, repetition).
Syntax errors: Violations of the grammar rules of Python (e.g. missing colon, mismatched brackets). Detected before the program runs.
Runtime errors: Errors that appear only while the program is running (e.g. dividing by zero). Also called exceptions.
Semantic errors: The program runs without crashing but does not do what was intended — the logic is wrong.
Experimental debugging: The process of forming hypotheses, testing them, and refining your understanding when an error occurs.

Error Type When Detected Example

Syntax Error Before execution (parsing) if x > 5 (missing colon)

Runtime Error During execution 10 / 0

Semantic Error Never detected automatically Using + instead of * in area formula

1.2 Variables, Expressions and Statements

Values and Data Types


A value is a basic unit of data (a number, letter, or string). Python's built-in types include int , float , str , and bool . The type() function
returns the type of a value.

x = 5 # int
y = 3.14 # float
name = "VTU" # str
print(type(x), type(y), type(name))

<class 'int'> <class 'float'> <class 'str'>

Variables, Variable Names and Keywords


A variable is a name that refers to a value. Variable names can contain letters, digits, and underscores, but cannot start with a digit. Python
has 33 reserved keywords (e.g. if , for , def , class ) that cannot be used as variable names.

Statements and Expressions


An expression is a combination of values, variables, and operators that produces a value (e.g. 3 + 4 ).
A statement is an instruction that the Python interpreter can execute (e.g. an assignment or a print statement). Statements produce no
value themselves.

Operators and the Order of Operations (PEMDAS)


Python follows the same precedence rules as mathematics, remembered with PEMDAS: Parentheses, Exponentiation, Multiplication/Division,
Addition/Subtraction, evaluated left to right.

print(2 + 3 * 4) # Multiplication before addition


print((2 + 3) * 4) # Parentheses override precedence
print(2 ** 3 ** 2) # Exponent is right-associative -> 2**(3**2)

14 20 512

Type Converter Functions


int() , float() , and str() convert values between types.

print(int("25") + 5)
print(str(25) + "5")
print(float("3.14"))

30 255 3.14

The Modulus Operator


The % operator divides one number by another and returns the remainder. It is commonly used to check divisibility (e.g. even/odd) or extract
the last digit of a number.

print(17 % 5) # remainder of 17/5


print(10 % 2) # 0 means even number

2 0
String Operations
The + operator on strings performs concatenation; * performs repetition.

print("Py" + "thon")
print("ab" * 3)

Python ababab

1.3 Iteration

Assignment and Updating Variables


An update is an assignment where the new value depends on the old one, e.g. x = x + 1 . The variable must already exist before it can be
updated.

The for Loop


Used when the number of iterations is known in advance — it traverses a sequence (string, list, range).

for i in range(1, 6):


print(i, end=' ')

1 2 3 4 5

The while Loop


Used when the number of iterations is not known in advance; it continues as long as a condition is true.

n = 5
while n > 0:
print(n)
n = n - 1
print("Blastoff!")

The Collatz 3n + 1 Sequence


A classic while-loop example: starting from any positive integer n, if n is even divide it by 2, if odd multiply by 3 and add 1; repeat until n
becomes 1.

def collatz(n):
while n != 1:
print(n, end=' ')
if n % 2 == 0:
n = n // 2
else:
n = 3 * n + 1
print(1)

collatz(6)

6 3 10 5 16 8 4 2 1

break and continue Statements


break : immediately exits the loop.
continue : skips the rest of the current iteration and moves to the next.

for i in range(1, 10):


if i == 5:
break
if i % 2 == 0:
continue
print(i, end=' ')

1 3

Nested Loops for Nested Data (Two-Dimensional Tables)


A loop placed inside another loop — commonly used to print multiplication tables or process two-dimensional/tabular data.

for row in range(1, 4):


for col in range(1, 4):
print(row * col, end='\t')
print()

1 2 3 2 4 6 3 6 9

1.4 Functions
A function is a named sequence of statements that performs a computation. Functions with arguments accept input values (parameters);
functions with a return value send a result back to the caller using the return statement.

def add_numbers(a, b): # a, b are parameters (arguments)


result = a + b
return result # sends value back to caller

total = add_numbers(7, 8) # 7, 8 are the actual arguments


print(total)

15

Exam tip: Be ready to distinguish a fruitful function (has a return statement, produces a value) from a void function (performs an action like
print() but returns None ).
Module 1 — Most Important Previous Year Questions

Q1. What is a program? Explain syntax, runtime and semantic errors with examples. ★ Very Frequent

Answer: A program is a sequence of instructions that specifies how to perform a computation. While writing programs, three types of errors
can occur:
Syntax errors – violate the grammatical rules of Python and are caught before the program runs. Example: if x > 5 (missing colon).
Runtime errors – appear only while the program is executing, often called exceptions. Example: dividing by zero, 10/0 .
Semantic errors – the program runs without error but does not do what was intended, due to a logic mistake. Example: using + instead of
* to calculate area.

Q2. Explain the order of operations (precedence of operators) in Python with examples. ★ Very Frequent

Answer: Python evaluates expressions using PEMDAS — Parentheses first, then Exponentiation, then Multiplication and Division (left to right),
then Addition and Subtraction (left to right). When operators have the same precedence, evaluation generally proceeds left to right
(exponentiation is the exception — it is right-associative).

print(2 + 3 * 4) # 14, multiplication first


print((2 + 3) * 4) # 20, parentheses override
print(2 ** 2 ** 3) # 256, right-to-left: 2**(2**3)

Q3. Develop a program to generate the Fibonacci sequence of length N (read N from console). ★ Very Frequent

n = int(input("Enter the length: "))


a, b = 0, 1
for i in range(n):
print(a, end=' ')
a, b = b, a + b

Enter the length: 7 0 1 1 2 3 5 8

Explanation: a and b hold the current and next Fibonacci numbers. In each iteration, a is printed, then both variables are updated
simultaneously using tuple assignment so the next pair is computed correctly.

Q4. Explain the Collatz 3n+1 sequence and write a program for it. ★ Frequent

Answer: Starting from any positive integer n, the Collatz rule is: if n is even, divide it by 2; if n is odd, multiply it by 3 and add 1. Repeating
this eventually reaches 1 for all tested starting values (this is the famous unproven Collatz conjecture).

n = int(input("Enter n: "))
while n != 1:
print(n, end=' ')
n = n // 2 if n % 2 == 0 else 3 * n + 1
print(1)

Q5. Differentiate between the for loop and while loop in Python. ★ Frequent

for loop while loop

Used when number of iterations is known/fixed Used when number of iterations depends on a condition

Iterates over a sequence (range, string, list) Repeats as long as a condition evaluates True

Example: for i in range(5): Example: while x > 0:

Q6. What is the role of break and continue statements? Illustrate with an example. ★ Frequent

Answer: break terminates the nearest enclosing loop immediately, skipping any remaining iterations. continue skips the remaining
statements in the current iteration only, and proceeds to the next iteration of the loop.

for i in range(1, 6):


if i == 3:
continue # skip 3
if i == 5:
break # stop at 5
print(i)

1 2 4

Q7. Explain functions with arguments and return values. Write a function to find the maximum of two numbers.
★ Very Frequent

def maximum(a, b):


if a > b:
return a
else:
return b

print(maximum(10, 25))

25

Explanation: Arguments ( a , b ) are the input values passed when the function is called. The return statement ends the function and sends
the result back, which can then be stored, printed, or used in further expressions.

Q8. What is the modulus operator? Write a program to check whether a number is even or odd. ★ Frequent

Answer: The modulus operator % returns the remainder of integer division. It is useful for checking divisibility.

num = int(input("Enter a number: "))


if num % 2 == 0:
print("Even")
else:
print("Odd")

Q9. Write a program to print a 2D (two-dimensional) multiplication table using nested loops. ★ Occasional

for i in range(1, 6):


for j in range(1, 6):
print(i * j, end='\t')
print()

Q10. Explain local and global scope with suitable examples. ★ Frequent

Answer: A variable defined inside a function has local scope — it exists only within that function and is destroyed once the function returns. A
variable defined outside all functions has global scope and can be read (but not directly modified, unless declared with global ) from inside
functions.

x = 10 # global variable

def show():
x = 5 # local variable, separate from global x
print("Local:", x)

show()
print("Global:", x)

Local: 5 Global: 10
MODULE 2: Strings, Tuples and Lists

2.1 Strings

A string is a sequence of characters. Strings support indexing, slicing, comparison, and a large set of built-in methods.

Length, Traversal and the for Loop

s = "Python"
print(len(s))
for ch in s:
print(ch, end='-')

6 P-y-t-h-o-n-

Slices
A slice s[start:end] extracts a substring from index start up to (not including) end .

s = "Programming"
print(s[0:6]) # Progra
print(s[6:]) # mming
print(s[:4]) # Prog
print(s[-3:]) # ing

String Comparison and Immutability


Strings can be compared using relational operators ( == , < , > ), which compare them lexicographically (alphabetically, by character codes).
Strings are immutable — once created, individual characters cannot be changed; any "modification" creates a new string object.

s = "hello"
# s[0] = 'H' # This would raise a TypeError

The in and not in Operators

s = "Python Programming"
print("Pro" in s)
print("Java" not in s)

True True

A find Function / The Built-in find() Method

s = "Python Programming"
print([Link]("Pro")) # returns starting index, or -1 if not found
print([Link]("Java"))

7 -1

Looping and Counting

def count_letter(word, letter):


count = 0
for ch in word:
if ch == letter:
count += 1
return count

print(count_letter("mississippi", "s"))

The split() Method and Cleaning Up Strings

line = " Python is fun "


print([Link]()) # removes leading/trailing whitespace
words = "one,two,three".split(",")
print(words)

Python is fun ['one', 'two', 'three']

The String format() Method

name, score = "Anu", 92


print("{} scored {} marks".format(name, score))
Anu scored 92 marks

2.2 Tuples

A tuple is an immutable, ordered sequence of values, written with comma-separated values usually inside parentheses. Tuples are used to
group related data together.

Tuple Assignment
Python allows a tuple of variables on the left of an assignment to be matched with a tuple of values on the right — useful for swapping values
without a temporary variable.

a, b = 5, 10
a, b = b, a # swap without a temp variable
print(a, b)

10 5

Tuples as Return Values


A function can return multiple values packed together as a tuple.

def min_max(values):
return min(values), max(values)

low, high = min_max([4, 9, 1, 7])


print(low, high)

1 9

2.3 Lists

A list is an ordered, mutable collection of values, written inside square brackets.

Accessing Elements, List Length, Membership

nums = [10, 20, 30, 40]


print(nums[1])
print(len(nums))
print(30 in nums)

20 4 True

List Operations and Slices

a = [1, 2, 3]
b = [4, 5]
print(a + b) # concatenation
print(a * 2) # repetition
print(a[1:3]) # slicing

[1, 2, 3, 4, 5] [1, 2, 3, 1, 2, 3] [2, 3]

Lists Are Mutable; Aliasing and Cloning


Unlike strings, list elements can be changed directly. When two variables refer to the same list object, this is called aliasing — changes
through one variable are visible through the other. To avoid this, a list can be cloned (copied) using a full slice [:] or the list() function.

a = [1, 2, 3]
b = a # aliasing: b refers to same list as a
b[0] = 99
print(a) # a is also affected!

c = a[:] # cloning: c is an independent copy


c[0] = 1
print(a, c)

[99, 2, 3] [99, 2, 3] [1, 2, 3]

List Methods (append, insert, remove, pop, clear, sort)

lst = [3, 1, 4]
[Link](1) # add to end
[Link](0, 9) # insert at index
[Link](1) # remove first matching value
print([Link]()) # remove & return last item
[Link]()
print(lst)
1 [3, 4, 9]

Pure Functions vs. Modifiers


A pure function does not change its arguments; it computes and returns a new value (e.g. sorted(lst) ).
A modifier changes the object passed to it in place and usually returns None (e.g. [Link]() ).

Nested Lists and Matrices

matrix = [[1, 2, 3], [4, 5, 6]]


print(matrix[1][2]) # row 1, column 2
for row in matrix:
print(row)

6 [1, 2, 3] [4, 5, 6]
Module 2 — Most Important Previous Year Questions

Q1. Explain different list operations with examples (insert, remove, append, length, pop, clear). ★ Very Frequent

Answer: This is a fixed lab/theory question across many VTU papers. Key operations:
append(x) – adds x to the end of the list
insert(i, x) – inserts x at index i
remove(x) – removes the first occurrence of value x
pop(i) – removes and returns the item at index i (last item if no index given)
len(list) – returns number of elements
clear() – removes all elements

fruits = ["apple", "banana"]


[Link](1, "mango")
[Link]("grape")
print("Length:", len(fruits))
[Link]("banana")
print("Popped:", [Link]())
print(fruits)
[Link]()
print(fruits)

Length: 3 Popped: grape ['apple', 'mango'] []

Q2. What is slicing? Explain string slices and list slices with examples. ★ Very Frequent

Answer: Slicing extracts a portion of a sequence (string, list, or tuple) using the syntax sequence[start:end:step] . The slice includes the start
index but excludes the end index. Omitting start defaults to the beginning; omitting end defaults to the end.

s = "Programming"
print(s[2:7]) # ogram

lst = [10, 20, 30, 40, 50]


print(lst[1:4]) # [20, 30, 40]
print(lst[::2]) # [10, 30, 50] (every 2nd element)
print(lst[::-1]) # [50, 40, 30, 20, 10] (reversed)

Q3. Explain how strings are immutable with an example. How is this different from lists? ★ Frequent

Answer: Strings cannot be changed after creation — any attempt to assign to an index raises a TypeError . Lists, by contrast, are mutable, so
individual elements can be reassigned directly.

s = "cat"
# s[0] = 'b' # TypeError: 'str' object does not support item assignment
s = "b" + s[1:] # correct way: build a new string
print(s)

lst = ["c", "a", "t"]


lst[0] = "b" # allowed, list is mutable
print(lst)

bat ['b', 'a', 't']

Q4. Explain aliasing and cloning of lists with an example. Why is cloning needed? ★ Very Frequent

Answer: When a list is assigned to another variable using b = a , both names refer to the same underlying list object — this is aliasing, and a
change through either name affects both. Cloning creates an independent copy (using a[:] , list(a) , or [Link]() for nested lists) so
the original is unaffected by later changes.

original = [1, 2, 3]
alias = original
clone = original[:]

[Link](4)
[Link](99)

print("original:", original)
print("alias:", alias)
print("clone:", clone)

original: [1, 2, 3, 4] alias: [1, 2, 3, 4] clone: [1, 2, 3, 99]

Q5. Write a program to read N numbers from console, create a list, and find mean, variance, and standard deviation.
★ Very Frequent (Lab PYQ)

n = int(input("How many numbers? "))


nums = [float(input(f"Enter number {i+1}: ")) for i in range(n)]
mean = sum(nums) / n
variance = sum((x - mean) ** 2 for x in nums) / n
std_dev = variance ** 0.5

print("Mean:", mean)
print("Variance:", variance)
print("Standard Deviation:", std_dev)

Explanation: Mean is the average; variance measures the average squared distance from the mean; standard deviation is the square root of
variance, used to express the spread in the same unit as the data.

Q6. What are tuples? How do they differ from lists? Explain tuple assignment with an example. ★ Frequent

Tuple List

Immutable (cannot change after creation) Mutable (can change elements)

Written using () Written using []

Slightly faster, used for fixed collections Used for collections that change over time

point = (3, 4)
x, y = point # tuple assignment / unpacking
print(x, y)

3 4

Q7. Explain the built-in find() and split() string methods with examples. ★ Frequent

text = "VTU Python Programming"


print([Link]("Python")) # returns index 4
print([Link]("Java")) # returns -1, not found

csv_line = "10,20,30,40"
values = csv_line.split(",")
print(values)

4 -1 ['10', '20', '30', '40']

Q8. Write a Python program to create a list and perform insert, remove, append, length, pop, and clear operations (Lab
Question 2b). ★ Very Frequent (Lab PYQ)

See Q1 above for the full worked solution — this is the exact wording used in the official VTU lab manual (Program 2b) and appears almost
every semester.

Q9. Explain nested lists with an example. How do you access elements of a 2D list (matrix)? ★ Occasional

matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
print(matrix[2][1]) # row index 2, column index 1 -> 8
for row in matrix:
for val in row:
print(val, end=' ')
print()

8 1 2 3 4 5 6 7 8 9

Q10. Differentiate between pure functions and modifier functions with respect to lists. ★ Occasional

Answer: A pure function takes a list, does not alter it, and returns a new result (e.g. sorted(lst) returns a new sorted list, leaving the
original unchanged). A modifier changes the list it is given in place and typically returns None (e.g. [Link]() sorts the original list directly).

original = [3, 1, 2]
new_list = sorted(original) # pure function
print(original, new_list)

[Link]() # modifier
print(original)

[3, 1, 2] [1, 2, 3] [1, 2, 3]

Prepared from the official VTU 2025 scheme syllabus (Course Code 1BPLC105B/205B, Python Programming, IPCC, 4 Credits) and patterns observed across previous-
year VTU question papers for Modules 1 & 2. Use alongside your official textbook (How to Think Like a Computer Scientist – Learning with Python 3) for full coverage.

You might also like