Skip to content

🐍 Python Programming (100218)

⬅️ Back to Semester-2 | 🏠 Home

💡 Why this subject? Python is the easiest language to think in — perfect for quickly turning logic into working code before you tackle Java/DSA in Semester 3.


📌 Module 1: Input and Output

  • Identifiers: names for variables/functions (can't start with a digit).
  • Dynamically typed: you don't declare a type — Python figures it out (x = 5 then x = "hello" is valid).
  • Strongly typed: but it won't silently convert types in operations ("5" + 5 → error).
name = input("Enter your name: ")   # reading input (always returns string)
age = int(input("Enter your age: ")) # type conversion
print(f"Hello {name}, you are {age} years old")

print(type(age), isinstance(age, int))  # type() function & is/isinstance check

📌 Module 2: Control Flow, Functions & Loops

# if-elif-else
marks = 75
if marks >= 90:
    grade = "A"
elif marks >= 60:
    grade = "B"
else:
    grade = "C"
print(grade)   # B

# Function with default parameter
def greet(name="Student"):
    return f"Hello, {name}!"
print(greet())          # Hello, Student!
print(greet("Pratap"))  # Hello, Pratap!

# Loops
for i in range(5):
    if i == 3:
        break        # stop loop entirely
    print(i)         # 0 1 2

i = 0
while i < 5:
    i += 1
    if i == 2:
        continue     # skip this iteration
    print(i)         # 1 3 4 5

🧠 Quick Recall: break exits the loop completely; continue skips just the current iteration.


📌 Module 3: Strings

s = "Hello World"
print(s[0])        # 'H'  — indexing
print(s[0:5])       # 'Hello' — slicing
print(s[::-1])      # 'dlroW olleH' — reverse using slicing!
print(s.upper())    # 'HELLO WORLD'
print(s.replace("World", "Python"))  # 'Hello Python'
print("Name: {}, Age: {}".format("Pratap", 20))  # formatting
print(f"Name: {'Pratap'}, Age: {20}")             # f-string (modern way)

📌 Module 4: Lists

fruits = ["apple", "banana", "mango"]
fruits.append("grape")        # add to end
fruits.insert(1, "kiwi")      # insert at index
print(fruits[1:3])            # slicing
fruits.remove("banana")
del fruits[0]
print(len(fruits))

# List comprehension (very Pythonic!)
squares = [x*x for x in range(1, 6)]
print(squares)   # [1, 4, 9, 16, 25]

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

📌 Module 5: Dictionaries, Tuples & Sets

# Dictionary — key:value pairs
student = {"name": "Pratap", "age": 20, "branch": "CSE"}
print(student["name"])
student["year"] = 2          # add new key
print(student.get("cgpa", "Not Available"))  # safe access with default

# Tuple — immutable list
point = (3, 4)
x, y = point   # unpacking
print(x, y)

# Set — unordered, unique elements
a = {1, 2, 3}
b = {2, 3, 4}
print(a & b)    # intersection {2, 3}
print(a | b)    # union {1, 2, 3, 4}
print(a - b)    # difference {1}

🧠 Quick Recall: List = ordered & mutable. Tuple = ordered & immutable. Set = unordered & unique. Dict = key-value pairs.


📌 Module 6: Files

# Writing to a file
with open("notes.txt", "w") as f:
    f.write("Studying Python today!\n")

# Reading a file
with open("notes.txt", "r") as f:
    content = f.read()
    print(content)

# Reading line by line
with open("notes.txt", "r") as f:
    for line in f:
        print(line.strip())

📝 Why with? It auto-closes the file even if an error happens midway — safer than manually calling f.close().


🔬 Key Lab Concepts (from the official lab list)

# Factorial using recursion
def factorial(n):
    return 1 if n == 0 else n * factorial(n - 1)
print(factorial(5))   # 120

# Check Palindrome
def is_palindrome(s):
    return s == s[::-1]
print(is_palindrome("madam"))   # True

# Round robin generator (advanced lab question)
def round_robin(*iterables):
    iterators = [iter(it) for it in iterables]
    while iterators:
        for it in iterators[:]:
            try:
                yield next(it)
            except StopIteration:
                iterators.remove(it)

print(list(round_robin([1,2,3], [4,5])))  # [1, 4, 2, 5, 3]

✅ Quick Revision Table

Topic One-line memory hook
Dynamic typing No need to declare type, Python infers it
List comprehension [expr for item in iterable if cond]
Tuple Immutable — can't change after creation
Set Unique elements, supports & \| -
with open() Auto-closes file safely
Generator (yield) Produces values lazily, one at a time