Introduc on to Python Programming (BPLCK105B/205B)
Passing + Scoring Package
1. Demonstrate with example print(), input() and string
replica on. (6 Marks)
1. print( ) → outputs to console.
2. sep argument changes separator.
3. end argument changes line ending.
4. Can print variables, expressions, strings.
5. input( ) → reads input from user.
6. Always returns string.
7. Needs type conversion for numbers.
8. String replica on uses *.
9. "hi"*3 → hihihi.
10.Useful for forma ng and pa erns.
Example 1
name = input("Enter your name: ")
print("Hello,", name)
Example 2
print("*" * 10) # **********
2. Explain elif, for, while, break and con nue statements in
Python with examples. (8 Marks)
1. elif → else-if branch.
2. Used in mul -way decision.
3. for → iterates sequences.
4. while → runs ll condi on false.
5. break → exits loop.
6. con nue → skips itera on.
7. Loops avoid repe on.
8. for uses iterators internally.
9. while uses condi on checking.
10.Both loops + condi ons provide flow control.
Example 1
for i in range(5):
if i == 3:
break
print(i)
Example 2
n=5
while n > 0:
n -= 1
if n % 2 == 0:
con nue
print(n)
3. What are user-defined func ons? How can we pass
parameters in user-defined func ons? Explain with example. (5
Marks)
1. Func on = reusable block of code.
2. Defined with def.
3. Parameters allow input.
4. Posi onal arguments supported.
5. Default arguments possible.
6. Keyword arguments improve clarity.
7. *args for variable arguments.
8. **kwargs for key-value arguments.
9. return used for output.
10.Improves modularity and reuse.
Example 1
def greet(name="Guest"):
return f"Hello {name}"
print(greet("Ananya"))
Example 2
def add(*nums):
return sum(nums)
print(add(2, 3, 4)) # 9
4. Explain Local and Global scope with variables for each. (8
Marks)
1. Local variables exist inside func on.
2. Destroyed when func on ends.
3. Global variables exist outside func on.
4. Accessible anywhere.
5. Local shadows global.
6. global keyword modifies global.
7. Overuse of global = bad design.
8. Local improves modularity.
9. Scoping prevents conflicts.
10.Helps memory management.
Example 1
x = 10 # global
def func():
x = 5 # local
print("Local:", x)
func()
print("Global:", x)
Example 2
count = 0
def increment( ):
global count
count += 1
increment()
print(count)
5. What is a List? Explain append(), insert(), and remove()
methods with examples. (8 Marks)
1. List = mutable collec on.
2. Ordered and indexed.
3. Can store mixed types.
4. append(x) → add at end.
5. insert(i, x) → add at posi on.
6. remove(x) → delete first match.
7. Error if element not found.
8. Supports slicing.
9. Dynamic resizing.
10.Core DS in Python.
Example 1
lst = [1, 2, 3]
lst.append(4)
print(lst) # [1, 2, 3, 4]
Example 2
lst = ["a", "b", "c"]
lst.insert(1, "z")
lst.remove("c")
print(lst) # ['a', 'z', 'b']
6. Explain keys(), values(), items() methods in a dic onary with
example. (12 Marks)
1. Dict stores key-value pairs.
2. Keys must be unique.
3. Values can repeat.
4. keys() → returns list of keys.
5. values() → returns values.
6. items() → returns pairs.
7. Iterables can be looped.
8. Efficient lookup using hash.
9. Mutable in nature.
10.Widely used for mapping.
Example 1
d = {"a": 1, "b": 2}
print(d.keys()) # dict_keys(['a','b'])
Example 2
for k, v in {"x": 10, "y": 20}.items():
print(k, v)
7. How is a tuple different from a list? Which func on is used to
convert list to tuple? (6 Marks)
1. List mutable, tuple immutable.
2. Tuples faster than lists.
3. Lists = [], tuples = ().
4. Lists allow modifica on.
5. Tuples fixed data storage.
6. Tuples hashable, lists not.
7. Lists grow/shrink dynamically.
8. Tuples use less memory.
9. Both allow mixed data.
10.Conversion: tuple(list).
Example 1
lst = [1,2,3]
tpl = tuple(lst)
print(tpl)
Example 2
t = (10, 20, 30)
# t[0] = 50 # Error → immutable
8. Explain upper(), lower(), isupper(), islower() with example. (8
Marks)
1. String methods for case.
2. upper() → all caps.
3. lower() → all small.
4. isupper() → check uppercase.
5. islower() → check lowercase.
6. Returns new string, unchanged original.
7. isupper/islower → Boolean.
8. Used for valida on.
9. Unicode support.
10.Normalizes user input.
Example 1
s = "Hello"
print(s.upper()) # HELLO
Example 2
x = "python"
print(x.islower()) # True
9. Illustrate file opening with open(), reading with read() and
wri ng with write(). (12 Marks)
1. File opened with open().
2. Modes: r, w, a.
3. read() → full content.
4. readline() → line by line.
5. write() → writes string.
6. with open() auto closes file.
7. w overwrites.
8. a appends.
9. Binary files need b mode.
10.File I/O essen al for persistence.
Example 1
with open("data.txt","w") as f:
f.write("Hello File")
Example 2
with open("data.txt","r") as f:
print(f.read())
10. Explain steps involved in adding bullets to Wiki-Markup. (10
Marks)
1. Wiki markup → lightweight forma ng.
2. * → bullet list.
3. # → numbered list.
4. Used in wikis/docs.
5. Each line begins with symbol.
6. Supports nes ng.
7. Easy syntax.
8. Can be generated with Python.
9. Converts to HTML later.
10.Helps in collabora ve edi ng.
Example 1
lines = ["* Apple", "* Banana", "* Mango"]
print("\n".join(lines))
Example 2
for item in ["One","Two","Three"]:
print("*", item)
11. How do you copy files and folders using shu l module? (6
Marks)
1. shu l → shell u li es module.
2. copy() copies file.
3. copy2() preserves metadata.
4. copytree() copies directory.
5. move() moves file/folder.
6. rmtree() deletes folder.
7. Supports both files & dirs.
8. Must import shu l.
9. Raises error if path invalid.
10.Useful in file automa on.
Example 1
import shu l
shu l.copy("a.txt", "b.txt")
Example 2
import shu l
shu l.copytree("src_folder", "backup_folder")
12. What are Asser ons? Explain with examples. (8 Marks)
1. Asser on = sanity check.
2. Uses assert keyword.
3. Syntax: assert condi on, message.
4. Stops program if false.
5. Used in debugging.
6. Helps catch logical errors.
7. Disabled with -O flag.
8. Should not replace excep ons.
9. Used in development, not produc on.
10.Improves program reliability.
Example 1
x = 10
assert x > 0, "x must be posi ve"
Example 2
def div(a, b):
assert b != 0, "Denominator cannot be zero"
return a/b
print(div(10, 2))
13. Illustrate logging levels in Python. (6 Marks)
1. Logging = tracking events.
2. Levels: DEBUG, INFO, WARNING, ERROR, CRITICAL.
3. DEBUG → lowest, for dev.
4. INFO → general messages.
5. WARNING → non-cri cal issues.
6. ERROR → serious issue.
7. CRITICAL → very serious.
8. Configurable with basicConfig().
9. Be er than print() debugging.
10.Output goes to file/console.
Example 1
import logging
logging.basicConfig(level=logging.INFO)
logging.info("Program started")
Example 2
import logging
logging.error("File not found!")
14. What is a Class? How to define class in Python? How to
ini ate and access members? (8 Marks)
1. Class = blueprint of object.
2. Defined with class.
3. Objects = instances of class.
4. A ributes = variables inside class.
5. Methods = func ons inside class.
6. Constructor = __init__().
7. Object crea on: obj = Class().
8. Access members via . operator.
9. Encapsula on of data + methods.
10.Supports OOP concepts.
Example 1
class Student:
def __init__(self, name):
self.name = name
s = Student("Ananya")
print(s.name)
Example 2
class Car:
def drive(self):
print("Car is moving")
c = Car()
c.drive()
15. Define Pure func on with example. (8 Marks)
1. Pure func on → no side effects.
2. Always returns same output for same input.
3. Doesn’t modify global variables.
4. No I/O opera ons.
5. Doesn’t depend on external state.
6. Determinis c in behavior.
7. Helps in tes ng.
8. Improves reliability.
9. Example: mathema cal func ons.
10.Opposite = impure func on.
Example 1
def square(x):
return x * x
print(square(5))
Example 2
def add(a, b):
return a+b
print(add(2,3))
16. Explain Prin ng Objects. (4 Marks)
1. By default, prin ng object shows memory address.
2. Can override with __str__().
3. __str__ returns string representa on.
4. Used for user-friendly output.
5. Useful in debugging.
6. Example: prin ng Student object.
7. __repr__ gives developer representa on.
8. Both can be defined in class.
9. Improves readability.
10.Good prac ce in OOP.
Example 1
class Student:
def __str__(self):
return "Student object"
s = Student()
print(s)
Example 2
class Book:
def __init__(self, tle):
self. tle = tle
def __str__(self):
return f"Book: {self. tle}"
print(Book("Python"))
17. What is Polymorphism? Demonstrate with func ons. (10
Marks)
1. Polymorphism = many forms.
2. Same func on behaves differently.
3. In Python achieved via overriding.
4. Func ons can accept any type.
5. Operator overloading is polymorphism.
6. Method overloading simulated with default args.
7. Improves flexibility.
8. Code reuse.
9. Example: + works for int and str.
10.Dynamic typing helps polymorphism.
Example 1
print(5+10)
print("Hello " + "World")
Example 2
def add(a, b, c=0):
return a+b+c
print(add(2,3))
print(add(2,3,4))
18. Explain Deck methods to add, remove, shuffle and sort
cards. (10 Marks)
1. Deck = collec on of cards.
2. append() adds card.
3. remove() deletes card.
4. shuffle() randomizes.
5. sort() orders deck.
6. Implemented using lists.
7. random.shuffle() used.
8. Useful in games.
9. Example: 52-card deck.
10.Python OOP makes simula on easy.
Example 1
import random
deck = [1,2,3,4,5]
random.shuffle(deck)
print(deck)
Example 2
deck = [10, 5, 7, 2]
deck.sort()
print(deck)
19. Explain __init__() and __str__() methods with examples. (6
Marks)
1. __init__() → constructor.
2. Called at object crea on.
3. Ini alizes a ributes.
4. __str__() → returns string rep.
5. Called when prin ng object.
6. Provides readability.
7. __repr__() is similar.
8. Both are magic methods.
9. Improves usability.
10.Common in OOP.
Example 1
class Student:
def __init__(self, name):
self.name = name
s = Student("Ananya")
print(s.name)
Example 2
class Car:
def __str__(self):
return "Car object"
print(Car())
20. What is JSON? Compare with Dic onary and explain with
example. (8 Marks)
1. JSON = JavaScript Object Nota on.
2. Lightweight data format.
3. Key-value pairs.
4. Similar to Python dict.
5. Keys must be strings.
6. Values: string, number, list, object.
7. Used in APIs, web.
8. Conversion: json.dumps(), json.loads().
9. Human-readable.
10.Dict is Python-specific, JSON is universal.
Example 1
import json
d = {"name":"Ananya","age":20}
print(json.dumps(d))
Example 2
s = '{"name":"Ananya","age":20}'
print(json.loads(s))