Python
Fundamentals
Introduction to Python
What Python is, why it matters, and how to write and run your very first program — no prior experience needed.
What is Python?
Imagine you want to tell a computer: "add up all the numbers in this list." In most languages, you'd write 10+ lines of setup code. In Python? One line — and it reads like plain English. That's the idea Python was built on.
Python is a general-purpose, high-level programming language. "High-level" means it reads almost like English — you don't manage memory, deal with pointers, or write assembly. "General-purpose" means you can use it for almost anything: websites, AI, automation, science.
Created in 1991 by Guido van Rossum, Python was built around one principle: code should be readable. See for yourself — here's a real Python program that filters even numbers from a list:
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
# Pick only the even numbers
evens = [n for n in numbers if n % 2 == 0]
print("Even numbers:", evens)
Even without knowing Python, you can guess what that does. That readability is Python's biggest strength.
Three things make Python stand out:
- Readable by design — Python uses indentation (whitespace) instead of curly braces
{}to define blocks of code. The structure is visible, not hidden. - Batteries included — The standard library handles file I/O, JSON, HTTP, regular expressions, dates, and more. You don't need to install anything to do common tasks.
- Enormous ecosystem — Over 500,000 packages on PyPI. Whatever you want to build, there's already a library for it — often several.
- Python is a high-level, general-purpose language — readable by design, created in 1991 by Guido van Rossum
- Interpreted: code runs line-by-line — no compile step needed, experiments are instant
- Batteries included: rich standard library + 500,000+ packages on PyPI cover almost any task
- Uses indentation (not curly braces) to structure code — forces clean, readable formatting
Python runs code line-by-line without a separate compilation step. This execution style is called ___.
Why Python?
Python is the #1 most popular programming language worldwide (Stack Overflow Developer Survey, 2024). It runs in Google, Netflix, Instagram, NASA, Spotify, and virtually every major tech company. Here is where it dominates:
The market demand is real. Python skills directly translate to high-paying careers across every major industry:
- Python is the #1 most popular programming language worldwide (Stack Overflow, 2024)
- Powers major products at Google, Netflix, Instagram, Spotify, and NASA
- Top career paths: Data Science / ML, Web Development, Automation, Cloud & DevOps
- High-earning roles in India (₹6–18 LPA) and globally ($120K+ in the US)
Which domain is Python most famous for in 2024?
Your First Program
By tradition, the first program every programmer writes displays "Hello, World!" on screen. In Python, that takes one line:
print("Hello, World!")
Click ▶ Run above. The playground opens, loads Python in your browser (~10 MB, one time), and shows the output on the right. You should see Hello, World!.
print() is a built-in function — a pre-built action Python gives you for free. Call it by writing its name with parentheses. Whatever you put inside gets displayed on screen. The text "Hello, World!" is a string — any text wrapped in quotes.
Let's push it further:
print("Hello, World!") # text string
print(42) # whole number
print(3.14) # decimal number
print(True) # boolean value
print("Python" + " is fun!") # joining two strings
print(10 + 5) # arithmetic result
print(2 ** 8) # 2 to the power of 8
print() calls to inspect values is the very first thing every programmer does — beginner and expert alike. Get comfortable with it.
print()is a built-in function — call it with parentheses to display output on screen- Text wrapped in quotes is a string — both
"double"and'single'quotes work - Python executes code top to bottom, one line at a time
- Each
print()call outputs on a new line by default +joins two strings together —"Hello" + " World"→Hello World
What does print("Python") output?
print() function displays the value inside the parentheses. The quotes in "Python" tell Python it's a string — they are not printed.Comments
A comment is a note for the human reading the code. Python completely ignores it at runtime — it has zero effect on execution. Comments start with a # symbol. Everything from the # to the end of the line is ignored.
# This whole line is a comment — Python ignores it
print("This line runs normally")
print("This runs too") # comment at end of a line
# You can disable code temporarily by commenting it out:
# print("This line is skipped")
Here is a real-world example. Notice the comments explain why values are what they are, not just what the code does:
# Calculate the total price including GST
# GST rate for most goods in India: 18%
price = 1200
gst_rate = 0.18 # 18% expressed as a decimal
gst_amount = price * gst_rate
total = price + gst_amount
print(f"Price: ₹{price}")
print(f"GST 18%: ₹{gst_amount}")
print(f"Total: ₹{total}")
# add 1 to counter above counter = counter + 1 adds noise — the code already says that. Write comments when the reasoning is non-obvious: a business rule, a workaround for a known bug, or a constraint that isn't visible in the code.
#starts a comment — everything from#to end of line is ignored by Python- Comments can appear on their own line or at the end of a code line
- Write comments that explain WHY — not what the code does (the code already says that)
- Commenting out code temporarily is a valid debugging technique
- Python has no multi-line comment syntax — use multiple
#lines or triple-quoted strings
Which of these is a valid Python comment?
# is Python's comment symbol. // is used in JavaScript/C, /* */ is C/Java style, and <!-- --> is HTML. In Python, # makes everything after it on that line invisible to the interpreter.Python Basics
Variables, data types, type conversion, output formatting, and operators — the building blocks every Python program is made from.
Variables
Picture a row of labeled boxes on a shelf. You write "name" on one box and drop "Alice" inside. Later, whenever you say name, Python opens that box and hands you back "Alice". That's all a variable is — a named box in memory.
A variable is a named container that stores a value in memory. You give it a name, put something inside, and later retrieve the contents by using that name.
Creating a variable is called assignment. Python uses the = sign, read as "is set to" (not "equals"):
name = "Alice" # stores text
age = 25 # stores a whole number
height = 5.6 # stores a decimal
is_student = True # stores True or False
# Use the variable by writing its name
print(name) # Alice
print(age) # 25
print(height) # 5.6
print(is_student) # True
Variables can be reassigned at any time — the box's label stays the same, but the contents change:
score = 0
print("Start:", score) # Start: 0
score = 10
print("After level 1:", score) # After level 1: 10
score = score + 5 # add 5 to whatever score currently is
print("After bonus:", score) # After bonus: 15
Python variable names follow these rules:
- Start with a letter or underscore —
name,_value,x - Can contain letters, digits, underscores —
user_name,score2 - Use snake_case for multi-word names (Python convention) —
first_name,total_score - Cannot start with a digit —
2nameis a syntax error - No spaces — use underscores:
my_name, notmy name - Case-sensitive —
name,Name, andNAMEare three separate variables
# Good names — descriptive and clear
user_name = "Bob"
total_score = 95
is_logged_in = True
max_retry_attempts = 3
# Case sensitivity in action
city = "Delhi"
City = "Mumbai" # completely different variable!
print(city) # Delhi
print(City) # Mumbai
- A variable is a named container — use
=to store a value (this is assignment, not equality) - Variables can be reassigned at any time — the value can change; the name stays the same
- Use snake_case:
first_name,total_score— lowercase with underscores between words - Names are case-sensitive:
name,Name, andNAMEare three different variables - Cannot start with a digit; no spaces; avoid reserved words like
print,int,True
What is the value of x after this code runs?x = 10 x = x + 5
x = x + 5 reads the current value of x (10), adds 5, then stores 15 back into x. The old value is gone — x now holds 15.Data Types
Every value in Python has a type. The type tells Python what kind of data is stored and what operations make sense. You have four core types to master first:
| Type | Full Name | Examples | Used for |
|---|---|---|---|
int | Integer | 0, 42, -7, 1000000 | Whole numbers, counts, ages, IDs |
float | Floating point | 3.14, -0.5, 99.99 | Decimals, prices, measurements |
str | String | "hello", 'Alice', "42" | Text — names, messages, paths |
bool | Boolean | True, False | Yes/No, on/off, flags, conditions |
Use the built-in type() function to inspect what type a value has:
age = 25
price = 99.99
city = "Mumbai"
is_open = False
print(type(age)) # <class 'int'>
print(type(price)) # <class 'float'>
print(type(city)) # <class 'str'>
print(type(is_open)) # <class 'bool'>
# You can also check the type of a literal value directly
print(type(3.14)) # <class 'float'>
print(type("hello")) # <class 'str'>
"42" (with quotes) is a string — a piece of text. 42 (no quotes) is an integer — a number. This distinction matters: "42" + "8" gives "428" (joins the text), while 42 + 8 gives 50 (adds the numbers).
# The + operator behaves differently per type
print(42 + 8) # 50 → addition (numbers)
print("42" + "8") # 428 → concatenation (strings)
# Confirming the types
print(type(42)) # <class 'int'>
print(type("42")) # <class 'str'>
- 4 core types:
int(whole numbers),float(decimals),str(text),bool(True/False) - Use
type(value)to inspect what type something is at any time "42"(with quotes) is a string;42(no quotes) is an integer — completely different+on strings concatenates ("42"+"8" → "428"); on numbers it adds (42+8 → 50)- Mixing incompatible types raises a TypeError — Python will not silently coerce types
What is the data type of the value 3.14?
float in Python. 3 would be an int, "3.14" (with quotes) would be a str, and True/False are bool.Type Conversion
Sometimes a value arrives in the wrong type and you need to convert it. Python provides built-in functions for common conversions: int(), float(), str(), and bool().
# String → Integer
num_str = "42"
num_int = int(num_str)
print(num_int + 8) # 50 ✓ (now it's a number)
# Integer → String
age = 25
age_text = str(age)
print("Age: " + age_text) # "Age: 25" ✓ (now it's text)
# String → Float
price_str = "99.99"
price = float(price_str)
print(price + 0.01) # 100.0
# Float → Int (decimal is TRUNCATED, not rounded)
x = int(3.9)
y = int(7.1)
print(x, y) # 3 7 (not 4 and 7!)
int(3.9) gives 3, not 4. The decimal is simply chopped off. Use round(3.9) if you need proper rounding, which gives 4.
The most common real-world scenario: user input always arrives as a string. You must convert it before doing any arithmetic:
# input() always returns a string, even if the user types a number
user_input = "50" # imagine this came from input()
# WRONG — tries to join text, not add numbers:
# print(user_input + 10) # TypeError!
# RIGHT — convert first, then calculate:
amount = int(user_input)
print(amount + 10) # 60
# One-liner version you'll see often:
# amount = int(input("Enter amount: "))
int(),float(),str()— the three conversions you'll use in almost every programint("42")→ 42; butint("hello")→ ValueError — only numeric strings can convertint(3.9)→ 3 — float-to-int truncates (chops), it does NOT round- User input from
input()is always a string — convert before any arithmetic - Use
round(3.9)for rounding; useint()only when you want to discard the decimal
What does int(7.9) return?
int(7.9) → 7 and int(7.1) → 7 as well. Use round(7.9) if you want 8.print() and f-strings
You already know the basics of print(). Let's go deeper — especially into f-strings, which are the modern, clean way to embed values inside text.
name = "Alice"
age = 25
# Multiple values: print() adds a space between them by default
print("Name:", name, "| Age:", age)
# Change the separator with sep=
print("A", "B", "C", sep=" → ") # A → B → C
# Change the ending with end= (default is a newline)
print("Loading", end="... ")
print("Done!") # Loading... Done!
f-strings (formatted string literals, Python 3.6+) let you embed variables and expressions directly inside a string. Just prefix the string with f, then use {} to insert values:
name = "Alice"
age = 25
score = 88.5
# Old way — messy, easy to forget str() conversion
print("Name: " + name + ", Age: " + str(age))
# f-string — clean, readable, handles types automatically
print(f"Name: {name}, Age: {age}")
# Any expression works inside {}
print(f"Next year you'll be {age + 1}")
print(f"Score: {score:.1f}%") # .1f = 1 decimal place → 88.5%
print(f"Uppercase name: {name.upper()}")
print(f"{'Python':>15}") # right-align in 15 chars
"Hello " + name) or .format(). They're the standard in modern Python — use them from day one.
- f-strings: prefix string with
f, embed values with{variable}— cleanest output formatting in Python - Any expression works inside
{}: math, method calls, conditions :.2fformats a float to 2 decimal places:f"{price:.2f}"sep=changes separator between print arguments (default: space);end=changes the line ending (default: newline)- Prefer f-strings over
"text " + str(var)concatenation — less error-prone, more readable
Given city = "Delhi", what does print(f"Welcome to {city}!") output?
f prefix activates f-string mode. {city} is replaced with the variable's value at runtime. The f and the quotes are not printed — only the final string value is.Operators
An operator is a symbol that performs an operation on one or more values. Python has three groups you need immediately: arithmetic, comparison, and logical.
Arithmetic Operators
a, b = 10, 3 # assign two variables at once
print(f"{a} + {b} = {a + b}") # 13
print(f"{a} - {b} = {a - b}") # 7
print(f"{a} * {b} = {a * b}") # 30
print(f"{a} / {b} = {a / b:.4f}") # 3.3333 (always a float)
print(f"{a} // {b} = {a // b}") # 3 (whole part only)
print(f"{a} % {b} = {a % b}") # 1 (remainder after dividing)
print(f"2 ** 10 = {2 ** 10}") # 1024
n % 2 == 0 checks if a number is even. n % 5 == 0 checks divisibility by 5. You'll use modulo constantly — in loops, cycling through colours, checking divisibility, and implementing clocks.
Comparison Operators
Comparison operators always return True or False. They're how your program makes decisions.
x = 10
print(x == 10) # True — equal to
print(x != 5) # True — not equal to
print(x > 5) # True — greater than
print(x < 5) # False — less than
print(x >= 10) # True — greater than or equal
print(x <= 9) # False — less than or equal
# Critical distinction:
# x = 10 means "set x to 10" (assignment)
# x == 10 means "is x equal to 10?" (comparison → True/False)
Logical Operators
Logical operators combine multiple conditions. They're the bridge between comparisons and real decisions.
# and — BOTH conditions must be True
print(True and True) # True
print(True and False) # False
print(False and False) # False
# or — AT LEAST ONE must be True
print(True or False) # True
print(False or False) # False
# not — FLIPS the value
print(not True) # False
print(not False) # True
# Real example: club entry check
age = 20
has_id = True
can_enter = age >= 18 and has_id
print(f"Can enter: {can_enter}") # True
# Another real example: discount eligibility
is_student = False
is_senior = True
gets_discount = is_student or is_senior
print(f"Gets discount: {gets_discount}") # True
total = price * 1.18 if is_taxable and price > 0 else price — arithmetic, comparison, and logical all in one expression.
- Arithmetic:
+-*/|//floor div |%remainder |**power /always returns a float;//returns the whole part only;%returns the leftover- Comparison operators always return True or False:
==!=<><=>= =assigns a value;==compares two values — never mix them up- Logical:
and(both true),or(at least one true),not(flips True/False)
What is the result of 17 % 5?
% (modulo) operator gives the remainder after division. 17 ÷ 5 = 3 remainder 2. This is incredibly useful for checking if a number is even (n % 2 == 0) or for cycling through ranges.Control Flow
Make decisions with if/elif/else, repeat actions with for and while loops, and control execution with break and continue.
if / elif / else
Every morning you make decisions: "If it's raining, take an umbrella. Else if it's cloudy, wear a jacket. Otherwise, just go." Your Python programs think the same way — if, elif, else are just code for decision-making.
A Python program doesn't always run top-to-bottom. Conditional statements let your code choose which path to take based on whether a condition is True or False.
if block. There are no curly braces like in other languages.age = 20
if age >= 18:
print("You are an adult.")
elif age >= 13:
print("You are a teenager.")
else:
print("You are a child.")
# Change age to 15 or 8 and re-run to see the difference
You can chain as many elif branches as you need. Only the first True branch runs — the rest are skipped.
score = 78
if score >= 90:
grade = "A"
elif score >= 80:
grade = "B"
elif score >= 70:
grade = "C"
elif score >= 60:
grade = "D"
else:
grade = "F"
print(f"Score: {score} → Grade: {grade}")
result = "pass" if score >= 50 else "fail"- Only the first matching branch runs; remaining branches are skipped
elifis optional;elseis optional — you can have justifalone- Indentation (4 spaces) defines what is "inside" a block — no curly braces
- Ternary form:
x if condition else y— useful for short assignments
Given score = 72, which branch runs in this code?if score >= 90: … elif score >= 70: … else: …
if first (72 >= 90 is False), then checks elif (72 >= 70 is True — runs this!), and skips else entirely. Only the first matching branch executes.Comparison & Logical Operators
Conditions are built from comparison operators that return True or False, combined with logical operators to test multiple conditions at once.
| Operator | Meaning | Example | Result |
|---|---|---|---|
== | Equal to | 5 == 5 | True |
!= | Not equal | 5 != 3 | True |
> | Greater than | 7 > 3 | True |
< | Less than | 2 < 5 | True |
>= | Greater or equal | 5 >= 5 | True |
<= | Less or equal | 3 <= 4 | True |
and | Both must be True | True and False | False |
or | At least one True | True or False | True |
not | Inverts the value | not True | False |
age = 25
has_id = True
is_vip = False
# AND — both must be True
if age >= 18 and has_id:
print("Entry allowed.")
# OR — at least one True
if age >= 18 or is_vip:
print("Can purchase ticket.")
# NOT — inverts
if not is_vip:
print("Regular pricing applies.")
# Combining operators — use parentheses for clarity
if (age >= 18 and has_id) or is_vip:
print("Full access granted.")
= assigns a value. Double == checks equality. Using = inside an if is a SyntaxError. This is one of the most common beginner mistakes.andrequires both sides to beTrue;orneeds only onenotflipsTrue→Falseand vice versa- Operator precedence:
not>and>or— use parentheses to be explicit - Python allows chained comparisons:
0 < score <= 100— very Pythonic
What does not True evaluate to?
not operator flips a boolean: not True → False, and not False → True. It always returns a proper boolean, not 0 or None.for Loops
A teacher calls out student names one by one. She doesn't call everyone at once — she goes through the list, name by name, doing the same action each time. That's exactly what a for loop does: visit each item, run the body, move to the next.
A for loop repeats a block of code for each item in a sequence — a range of numbers, a string, a list, or any other iterable.
# range(n) generates numbers 0 to n-1
for i in range(5):
print(f"Step {i}")
print("---")
# range(start, stop, step)
for i in range(1, 10, 2):
print(i, end=" ") # prints: 1 3 5 7 9
print()
# Looping over a string
for char in "Python":
print(char, end="-") # P-y-t-h-o-n-
range(start, stop, step) is the most powerful form. stop is exclusive — the loop stops before reaching it.
# Sum 1 to 100
total = 0
for n in range(1, 101):
total += n
print(f"Sum 1–100 = {total}") # 5050
# Countdown using reversed range
for i in range(5, 0, -1):
print(i, end=" ")
print("Lift off! 🚀")
# enumerate() gives index + value together
fruits = ["apple", "banana", "cherry"]
for idx, fruit in enumerate(fruits):
print(f"{idx + 1}. {fruit}")
_ as the variable name: for _ in range(3): print("hello"). This is a Python convention for "I don't need this variable".range(n)= 0 to n−1;range(a, b)= a to b−1;range(a, b, step)for custom step- A
forloop can iterate over any sequence: string, list, tuple, dict, range enumerate(seq)gives both the index and the value — avoids manual counters- Use negative step (
range(10, 0, -1)) to count down
How many times does the loop body run?for i in range(2, 8, 2): print(i)
range(2, 8, 2) generates: 2, 4, 6 — that's 3 values. It starts at 2, steps by 2, and stops before 8. So the loop prints 2, then 4, then 6.while / break / continue
A while loop runs as long as its condition remains True. Use it when you don't know how many iterations you need — for example, waiting for user input or running a game loop.
count = 1
while count <= 5:
print(f"Count: {count}")
count += 1 # always update the counter — or you get infinite loop!
print("Done!")
# Simulating a simple retry loop
attempts = 0
max_attempts = 3
while attempts < max_attempts:
print(f"Attempt {attempts + 1}: trying...")
attempts += 1
print("No more attempts.")
break exits the loop immediately. continue skips the rest of the current iteration and jumps to the next one.
# break — exit as soon as we find 5
for n in range(1, 10):
if n == 5:
print(f"Found 5, stopping!")
break
print(n)
print("---")
# continue — skip even numbers, print only odd
for n in range(1, 11):
if n % 2 == 0:
continue # skip even numbers
print(n, end=" ") # prints: 1 3 5 7 9
print()
while True: loop runs forever unless you break out of it. Always make sure the condition will eventually become False, or use break. In the playground, an infinite loop will freeze the page.- Use
whilewhen the number of iterations is unknown; useforwhen iterating a known sequence breakexits the entire loop;continuejumps to the next iteration- Always ensure a
whileloop has an exit path — update the counter or usebreak while True:+breakis a common pattern for "run until condition met" loops
What happens when Python hits a break statement inside a loop?
break stops the loop entirely — no more iterations. Compare with continue, which only skips the rest of the current iteration and moves to the next one.Nested Logic & Mini Project
Conditions and loops can be nested inside each other. This is how you build more complex decision trees — for example, a login validator that checks both username and password, or a game that tracks rounds.
# Multiplication table for 1-3
for i in range(1, 4):
for j in range(1, 6):
print(f"{i} × {j} = {i*j}")
print("---") # separator after each row
Putting it all together — here is the classic Number Guessing Game. It uses a while loop, if/elif/else, and break. Try running it and changing the secret number.
# Number Guessing Game — Module 03 Mini Project
import random
secret = random.randint(1, 20) # random number 1–20
attempts = 0
max_tries = 5
print("=== Number Guessing Game ===")
print(f"Guess a number between 1 and 20. You have {max_tries} tries.")
guesses = [7, 12, 15, secret] # simulated guesses (replace with input() in real app)
for guess in guesses:
attempts += 1
print(f"\nAttempt {attempts}: guessing {guess}")
if guess < secret:
print("Too low! Try higher.")
elif guess > secret:
print("Too high! Try lower.")
else:
print(f"🎉 Correct! You got it in {attempts} attempt(s)!")
break
if attempts == max_tries:
print(f"❌ Out of attempts! The number was {secret}.")
- Use
if/elif/elsefor decisions — only one branch executes - Use
forwhen iterating a known sequence;whilewhen the end condition is dynamic breakexits immediately;continueskips to the next iteration- Loops and conditionals can be nested — keep indentation consistent and readable
- Every real program uses control flow — it's the skeleton of logic
Data Structures
Master the four built-in data structures — lists, tuples, sets, and dictionaries. Learn when to use each and how to manipulate collections efficiently.
Lists
Imagine a shopping list on paper — you can add items, cross things out, reorder them, or check what's at position 3. Python's list works exactly like that: an ordered, changeable collection that can hold anything.
A list is created with square brackets []. Items are separated by commas and can be of any type — even mixed. Lists are ordered (items stay in position) and mutable (you can change them after creation).
# Creating lists
fruits = ["apple", "banana", "cherry"]
numbers = [10, 20, 30, 40, 50]
mixed = [1, "hello", 3.14, True]
# Indexing — starts at 0
print(fruits[0]) # apple
print(fruits[-1]) # cherry (negative = from the end)
# Slicing [start : stop] stop is exclusive
print(numbers[1:4]) # [20, 30, 40]
print(numbers[:3]) # [10, 20, 30]
print(numbers[2:]) # [30, 40, 50]
# Length
print(len(fruits)) # 3
Lists come with powerful built-in methods for adding, removing, and rearranging items.
scores = [85, 92, 78, 95, 88]
scores.append(100) # add to end
scores.insert(0, 70) # insert at index 0
scores.remove(78) # remove first occurrence of 78
popped = scores.pop() # remove and return last item
scores.sort() # sort ascending
scores.sort(reverse=True) # sort descending
print(scores)
print(sum(scores), max(scores), min(scores))
Updating an item is done by direct index assignment. You can also update a slice to replace multiple items at once.
fruits = ["apple", "banana", "cherry"]
# Update a single item by index
fruits[1] = "mango"
print(fruits) # ['apple', 'mango', 'cherry']
# Replace a slice (indices 0 and 1)
fruits[0:2] = ["kiwi", "grape"]
print(fruits) # ['kiwi', 'grape', 'cherry']
# Extend — add multiple items at the end
fruits.extend(["papaya", "guava"])
print(fruits)
Looping through a list — use a plain for loop to get values, or enumerate() when you also need the index.
scores = [85, 92, 78, 95, 88]
# Basic for loop — just values
for s in scores:
print(s)
# enumerate — index + value together
for i, s in enumerate(scores):
print(f"Rank {i+1}: {s}")
# while loop with index
i = 0
while i < len(scores):
print(scores[i])
i += 1
List comprehension is a compact way to build a new list by applying an expression to each item.
# Squares of 1 to 5
squares = [x**2 for x in range(1, 6)]
print(squares) # [1, 4, 9, 16, 25]
# Even numbers only
evens = [x for x in range(20) if x % 2 == 0]
print(evens)
# Convert all strings to uppercase
words = ["sql", "python", "pandas"]
upper = [w.upper() for w in words]
print(upper)
if "apple" in fruits:. Much cleaner than looping. Works on lists, tuples, sets, dicts, and strings.What does ["a","b","c","d"][1:3] return?
Tuples
GPS coordinates for the Taj Mahal are (27.1751, 78.0421). They never change. A tuple is Python's way of storing a fixed collection — coordinates, RGB colours, a date — where the values should not be modified.
Tuples use parentheses () and are immutable — once created, you cannot add, remove, or change items. They are faster than lists and signal "these values are constants".
# Creating tuples
point = (27.1751, 78.0421)
rgb_red = (255, 0, 0)
single = (42,) # trailing comma needed for single-item tuple
print(point[0]) # 27.1751
print(rgb_red[-1]) # 0
# Tuple unpacking
lat, lng = point
print(f"Latitude: {lat}, Longitude: {lng}")
x, y, z = rgb_red
print(f"R={x} G={y} B={z}")
# Swap two variables (uses tuple packing/unpacking)
a, b = 10, 20
a, b = b, a
print(a, b) # 20 10
point[0] = 99 raises a TypeError. Use tuples for fixed data (coordinates, status codes, days of the week) and lists for data you need to modify.Looping through a tuple works exactly like looping through a list — use for to get values, or enumerate() when you need the index.
days = ("Mon", "Tue", "Wed", "Thu", "Fri")
# Basic loop
for day in days:
print(day)
# enumerate — index + value
for i, day in enumerate(days):
print(f"Day {i+1}: {day}")
# Unpack all at once when length is known
mon, tue, wed, thu, fri = days
print(f"Weekend starts after {fri}")
Which line correctly creates a single-element tuple?
(42) as just the integer 42. The comma makes it a tuple.Sets
A whiteboard lists every technology mentioned by participants. Duplicates don't matter — you just want unique items. That's a set: an unordered collection where every item appears exactly once.
Sets use curly braces {}. They automatically remove duplicates and support mathematical operations like union, intersection, and difference. Sets are unordered — you cannot rely on item position.
# Duplicates removed automatically
tags = {"python", "sql", "python", "data", "sql"}
print(tags) # {'python', 'sql', 'data'}
tags.add("pandas")
tags.discard("sql") # no error if missing
print(tags)
# Membership — O(1), very fast
print("python" in tags) # True
# Set operations
backend = {"python", "sql", "django"}
frontend = {"javascript", "css", "python"}
print(backend | frontend) # union
print(backend & frontend) # intersection
print(backend - frontend) # difference
print(backend ^ frontend) # symmetric difference
Updating & removing — update() adds multiple items from any iterable. remove() raises an error if the item is missing; discard() does not.
skills = {"python", "sql"}
# Add one item
skills.add("pandas")
# Add many items at once
skills.update(["spark", "airflow", "dbt"])
print(skills)
# Remove — raises KeyError if missing
skills.remove("airflow")
# Discard — safe, no error if missing
skills.discard("java") # java wasn't there — no crash
print(skills)
# Clear all items
backup = skills.copy()
skills.clear()
print(skills) # set()
Looping through a set — order is not guaranteed, but you can loop or convert to a sorted list first.
techs = {"python", "sql", "pandas", "spark"}
# Loop — order varies each run
for t in techs:
print(t)
# Sorted loop — predictable order
for t in sorted(techs):
print(t)
# Set comprehension — keep long names only
long_names = {t for t in techs if len(t) > 3}
print(long_names)
unique = list(set(my_list)). Note that sets don't preserve order — sort after if order matters.What is len({1, 2, 2, 3, 3, 3})?
Dictionaries
A dictionary maps every word to its meaning. You look up a word (the key) and find its definition (the value). Python dicts work the same way — fast lookup by key, no searching required.
Dictionaries store key-value pairs inside curly braces {}. Keys must be unique and immutable. Values can be anything. Dicts are ordered in Python 3.7+.
student = {
"name": "Priya Sharma",
"age": 22,
"course": "Data Engineering",
"score": 91
}
print(student["name"]) # Priya Sharma
print(student.get("grade", "N/A")) # N/A (safe — no KeyError)
student["city"] = "Bangalore" # add new key
student["score"] = 95 # update existing key
del student["age"]
removed = student.pop("city")
print(removed)
salary = {
"Data Analyst": 65000,
"Data Engineer": 90000,
"ML Engineer": 110000,
}
# Loop through key-value pairs
for role, sal in salary.items():
print(f"{role:20} -> Rs {sal:,}")
# Dict comprehension — 10% hike
hiked = {r: int(s * 1.10) for r, s in salary.items()}
print(hiked)
- Use
dict.get(key, default)to avoidKeyErroron missing keys .items()is the go-to for looping — gives both key and value- Keys must be immutable; values can be anything including lists or nested dicts
- Dict comprehension:
{k: v for k, v in ...}
What does d.get("x", 0) return when key "x" is not in d?
.get(key, default) returns the default when the key is missing — no error. This is the safe alternative to bracket access.Nested Structures & Mini Project
Real-world data rarely fits one structure. You often have a list of dictionaries (a table of records) or a dictionary of lists. Nesting combines both naturally.
# List of dicts — like a database table
students = [
{"name": "Arjun", "score": 88, "course": "SQL"},
{"name": "Priya", "score": 95, "course": "Python"},
{"name": "Ravi", "score": 72, "course": "SQL"},
{"name": "Sneha", "score": 91, "course": "Python"},
]
for s in students:
print(s["name"], s["score"])
# Filter: Python students only
py_students = [s for s in students if s["course"] == "Python"]
print(py_students)
avg = sum(s["score"] for s in students) / len(students)
print(f"Average: {avg:.1f}")
# Grade Book — Module 04 Mini Project
gradebook = {
"Arjun": {"Math": 82, "Python": 91, "SQL": 88},
"Priya": {"Math": 95, "Python": 97, "SQL": 93},
"Ravi": {"Math": 70, "Python": 74, "SQL": 68},
}
def get_grade(avg):
if avg >= 90: return "A"
if avg >= 80: return "B"
if avg >= 70: return "C"
return "D"
print(f"{'Student':<10} {'Average':>8} {'Grade':>6}")
print("-" * 28)
for name, marks in gradebook.items():
avg = sum(marks.values()) / len(marks)
print(f"{name:<10} {avg:>8.1f} {get_grade(avg):>6}")
best = max(gradebook, key=lambda n: sum(gradebook[n].values()))
print(f"\nTop performer: {best}")
- List — ordered, mutable, allows duplicates. Use for sequences you modify.
- Tuple — ordered, immutable. Use for fixed data (coordinates, configs).
- Set — unordered, unique items. Use for membership tests and deduplication.
- Dictionary — key-value pairs, fast lookup. Use for labelled data.
- Nesting structures (list of dicts, dict of lists) models real-world data naturally.
Strings
Master Python's most-used data type. Learn indexing, slicing, built-in methods, f-strings, and how to manipulate text like a professional.
String Basics & Slicing
Think of a string as a row of letter-boxes numbered from 0. You can look into any box (indexing), or grab a range of boxes (slicing). Strings are everywhere — names, messages, file paths, API responses.
Strings are sequences of characters enclosed in single ', double ", or triple quotes """. They are immutable — operations always return a new string.
name = "Python"
# Indexing
print(name[0]) # P
print(name[-1]) # n (last character)
print(name[-2]) # o (second from end)
# Slicing [start : stop : step]
print(name[0:3]) # Pyt
print(name[2:]) # thon
print(name[:4]) # Pyth
print(name[::2]) # Pto (every other char)
print(name[::-1]) # nohtyP (reversed!)
# Concatenation and repetition
lang = "Data " + name
print(lang) # Data Python
print(len(lang)) # 11
print(name * 3) # PythonPythonPython
s[::-1]. A step of -1 walks backwards. Also check palindromes: s == s[::-1].What does "abcdef"[1:-1] return?
String Methods
A raw data file has column headers in all-caps with extra spaces: " FIRST NAME ". Before you can use it, you strip the spaces, lowercase it, and replace spaces with underscores. That's three string methods chained together — exactly what Python makes easy.
Python provides 40+ built-in string methods. Call them with dot notation: string.method(). They always return a new string — strings are immutable.
text = " Hello, World! "
print(text.upper()) # " HELLO, WORLD! "
print(text.lower()) # " hello, world! "
print(text.strip()) # "Hello, World!"
print(text.lstrip()) # "Hello, World! "
print(text.rstrip()) # " Hello, World!"
clean = text.strip()
print(clean.find("World")) # 7
print(clean.count("l")) # 3
print(clean.replace("World", "Python")) # Hello, Python!
# split() — string to list
csv_row = "Priya,91,Python,Bangalore"
parts = csv_row.split(",")
print(parts) # ['Priya', '91', 'Python', 'Bangalore']
# join() — list to string
words = ["Data", "Science", "is", "awesome"]
print(" ".join(words)) # Data Science is awesome
# Normalise user input
raw = " data ENGINEER "
print(raw.strip().lower().replace(" ", "_")) # data_engineer
# startswith / endswith
filename = "report_2024.csv"
print(filename.endswith(".csv")) # True
print(filename.startswith("rep")) # True
What does "-".join(["a","b","c"]) return?
join() glues list items together using the separator string between elements — not at the end. Result is one string.f-strings & Formatting
Imagine printing a salary slip: you need the employee's name, salary formatted with commas, and a percentage hike — all in one clean line. Before f-strings, you'd juggle str(), +, and format(). With f-strings, it's one readable line.
f-strings (formatted string literals) embed variables and expressions directly inside strings. Prefix with f and place expressions inside {}.
name = "Priya"
score = 91.5
salary = 85000
# Basic embedding
print(f"Hello, {name}!")
print(f"Score + bonus = {score + 5}")
print(f"Upper: {name.upper()}")
# Format specifiers
print(f"Salary: Rs {salary:,}") # Rs 85,000
print(f"Score: {score:.2f}") # 91.50
print(f"Score: {score:.0f}") # 92 (rounded)
# Alignment
print(f"{'Role':<15} {'Score':>6}")
print(f"{'Data Engineer':<15} {score:>6.1f}")
# Multi-line
report = (
f"Student Report\n"
f" Name : {name}\n"
f" Score : {score}\n"
)
print(report)
.format() and far more readable than concatenation. Use them everywhere. The : inside braces introduces a format spec — ,.2f means comma-separated, 2 decimal places, float.What does f"{3.14159:.2f}" output?
.2f = fixed-point with exactly 2 decimal places. 3.14159 rounded to 2 decimals is 3.14.String Operations & Patterns
A data validation script needs to check that an email contains @, ends with .com, and isn't empty. Each of those checks is one line with a string operator. Real-world code is full of these tiny but critical patterns.
Beyond methods, Python supports powerful string operations using operators and comprehensions. These patterns appear constantly in real codebases.
email = "priya@marutinovatech.com"
print("@" in email) # True
print(email.startswith("priya")) # True
print(email.endswith(".com")) # True
text = "Data Engineering is the future of tech"
print(text.count("e")) # 5
words = text.split()
print(f"Word count: {len(words)}")
# Palindrome check
def is_palindrome(s):
s = s.lower().replace(" ", "")
return s == s[::-1]
print(is_palindrome("racecar")) # True
print(is_palindrome("Madam")) # True
print(is_palindrome("Python")) # False
# Build string from list
digits = [str(x) for x in range(10)]
print("".join(digits)) # 0123456789
Which method splits "a,b,c" into ["a","b","c"]?
split(sep) breaks at every separator and returns a list. Without an argument it splits on whitespace.Text Analyser — Mini Project
Journalists, SEO writers, and data engineers all need to understand text at a glance — word count, repeated keywords, sentence structure. You're going to build that tool from scratch using nothing but the string skills you just learned.
Put everything together in a practical text analyser. It reports word count, sentence count, most common words, and character frequency — the kind of tool used in NLP preprocessing and content analytics.
# Text Analyser — Module 05 Mini Project
text = """
Python is a versatile programming language.
It is used in data science, web development, and automation.
Python is easy to learn and powerful to use.
Data engineers love Python for pipeline and ETL work.
"""
words = text.lower().split()
sentences = [s.strip() for s in text.split(".") if s.strip()]
print(f"Characters : {len(text.strip())}")
print(f"Words : {len(words)}")
print(f"Sentences : {len(sentences)}")
# Word frequency
freq = {}
for word in words:
clean = word.strip(".,!?").lower()
freq[clean] = freq.get(clean, 0) + 1
sorted_words = sorted(freq.items(), key=lambda x: x[1], reverse=True)
print("\nTop 5 words:")
for word, count in sorted_words[:5]:
print(f" {word:<15} {count} time(s)")
# Most common letter
all_chars = [c.lower() for c in text if c.isalpha()]
char_freq = {}
for c in all_chars:
char_freq[c] = char_freq.get(c, 0) + 1
top_char = max(char_freq, key=char_freq.get)
print(f"\nMost common letter: '{top_char}' ({char_freq[top_char]} times)")
- Strings are immutable sequences — all methods return a new string
- Slicing
[start:stop:step]works the same as lists;[::-1]reverses - Essential methods:
strip(),split(),join(),replace(),upper(),lower(),find() - Use f-strings for all formatting — fast and readable
- Combine
split()+join()to process words in a sentence
Functions & Modules
Write reusable code with functions, master parameters and return values, and tap into Python's rich standard library.
Defining Functions
Every time you call print() or len() you are using a function — a named, reusable block of code. Writing your own functions is how you stop copying and pasting the same logic over and over.
A function is defined with the def keyword, a name, parentheses, and a colon. The indented block that follows is the function body. Call it by writing its name followed by ().
def greet():
print("Hello, world!")
greet() # call the function
greet() # call it again — reusable!
# Function that returns a value
def square(n):
return n ** 2
result = square(7)
print(result) # 49
print(square(10)) # 100
A function without a return statement returns None automatically. Use return to send a value back to the caller — execution stops at the return line.
def classify_score(score):
if score >= 90:
return "A"
elif score >= 75:
return "B"
elif score >= 60:
return "C"
else:
return "F"
scores = [95, 82, 67, 45]
for s in scores:
print(f"{s} → Grade {classify_score(s)}")
What does a function without a return statement return?
None when no return statement is present. You can verify with print(type(greet())).Parameters & Return Values
Parameters are the variables listed in a function's definition. Arguments are the values you pass when calling it. Python supports several styles of parameters for flexibility.
# Positional — order matters
def greet(name, city):
print(f"Hi {name} from {city}!")
greet("Priya", "Bangalore")
# Default parameter — used when argument is omitted
def power(base, exp=2):
return base ** exp
print(power(5)) # 25 (exp defaults to 2)
print(power(2, 10)) # 1024
# Keyword arguments — order doesn't matter
greet(city="Mumbai", name="Arjun")
*args collects extra positional arguments as a tuple. **kwargs collects extra keyword arguments as a dictionary. Both are useful for writing flexible functions.
# *args — variable number of positional arguments
def total(*numbers):
return sum(numbers)
print(total(1, 2, 3)) # 6
print(total(10, 20, 30, 40)) # 100
# **kwargs — variable number of keyword arguments
def show_profile(**info):
for key, val in info.items():
print(f"{key}: {val}")
show_profile(name="Ravi", role="Data Engineer", city="Pune")
# Multiple return values — returns a tuple
def min_max(nums):
return min(nums), max(nums)
lo, hi = min_max([5, 1, 9, 3])
print(f"Min: {lo}, Max: {hi}")
Given def f(x, y=10): return x + y, what does f(5) return?
x=5, y uses its default of 10. 5 + 10 = 15.Lambda & Built-in Functions
A lambda is an anonymous, single-expression function. Use it when you need a throwaway function — most commonly as an argument to sorted(), map(), or filter().
# lambda syntax: lambda arguments : expression
double = lambda x: x * 2
print(double(7)) # 14
# Sort list of dicts by a field
employees = [
{"name": "Priya", "salary": 90000},
{"name": "Arjun", "salary": 75000},
{"name": "Sneha", "salary": 110000},
]
by_salary = sorted(employees, key=lambda e: e["salary"], reverse=True)
for e in by_salary:
print(f"{e['name']:10} Rs {e['salary']:,}")
map() applies a function to every item. filter() keeps only items where the function returns True. Both return iterators — wrap in list() to see results.
nums = [1, 2, 3, 4, 5, 6]
# map — square every number
squares = list(map(lambda x: x**2, nums))
print(squares) # [1, 4, 9, 16, 25, 36]
# filter — keep only even numbers
evens = list(filter(lambda x: x % 2 == 0, nums))
print(evens) # [2, 4, 6]
# Useful built-ins
data = [8, 3, 9, 1, 7]
print(sum(data), min(data), max(data))
print(sorted(data))
print(list(reversed(data)))
What does list(filter(lambda x: x > 3, [1,2,3,4,5])) return?
filter keeps only elements where the lambda returns True. Only 4 and 5 are strictly greater than 3.Modules & Import
Python ships with a "batteries included" standard library — thousands of pre-written functions you can use by just typing import. Third-party packages (NumPy, Pandas, Requests) add even more power.
Use import module to load a whole module, then call functions as module.function(). Use from module import name to bring a specific name directly into scope.
import math
import random
from datetime import date
# math module
print(math.sqrt(144)) # 12.0
print(math.pi) # 3.14159...
print(math.ceil(4.2)) # 5
print(math.floor(4.9)) # 4
# random module
print(random.randint(1, 100)) # random int 1–100
names = ["Priya", "Arjun", "Ravi"]
print(random.choice(names)) # random pick
# datetime — today's date
today = date.today()
print(today) # e.g. 2025-06-01
print(today.year, today.month)
import math as m # alias — shorter to type
print(m.sqrt(25)) # 5.0
from math import sqrt, pi # import specific names
print(sqrt(81)) # 9.0
print(pi) # 3.14159...
# Third-party — install first: pip install requests
# import requests
# resp = requests.get("https://api.example.com/data")
# List everything inside a module
print(dir(math))[:6]
Install any third-party library:
pip install pandas. In a project, save dependencies with pip freeze > requirements.txt so teammates can reproduce the environment.Which import style lets you call sqrt(16) directly without a module prefix?
from math import sqrt. This brings sqrt directly into the current namespace so you can call it without the math. prefix.Mini Project — Grade Analyser
Combine everything from this module — functions, parameters, return values, and standard-library tools — into a real program that analyses a class's exam results.
import math
# ── Helper functions ──────────────────────────
def letter_grade(score):
if score >= 90: return "A"
elif score >= 75: return "B"
elif score >= 60: return "C"
else: return "F"
def stats(*scores):
avg = sum(scores) / len(scores)
return {
"count": len(scores),
"avg": round(avg, 2),
"high": max(scores),
"low": min(scores),
"pass": sum(1 for s in scores if s >= 60),
}
def report(class_name, **students):
print(f"\n{'='*40}")
print(f" Class: {class_name}")
print(f"{'='*40}")
for name, score in sorted(students.items()):
print(f" {name:12} {score:>3} [{letter_grade(score)}]")
s = stats(*students.values())
print(f"{'─'*40}")
print(f" Average : {s['avg']}")
print(f" Highest : {s['high']}")
print(f" Lowest : {s['low']}")
print(f" Pass % : {s['pass']*100//s['count']}%")
# ── Run the report ────────────────────────────
report("Python Batch A",
Priya=92, Arjun=78, Ravi=55,
Sneha=88, Kiran=64, Meera=71)
- Use
defto define,returnto send values back — functions withoutreturngiveNone - Default parameters make arguments optional;
*args/**kwargshandle variable inputs - Lambda is a one-line anonymous function — ideal as a
key=argument tosorted() - Standard library modules (
math,random,datetime) are free — justimport - Third-party packages install with
pip install name
Practice & Quiz
Test what you've learned — 33 MCQ questions and 10 coding challenges covering Modules 01 through 06.
Multiple Choice Questions
Pick the best answer for each question. Explanations appear after you select an option.
print("Hello" + "World") output?+ operator concatenates strings — it joins them without any space. "Hello" + "World" → "HelloWorld". If you wanted a space, you'd write "Hello " + "World".x holds 5, y holds 10. The + operator performs arithmetic addition when used with integers. Result: 15.name = "Alice"?str). Numbers without quotes are int or float. True/False are bool.int("25") return?int() converts the string "25" to the integer 25. It returns a plain integer, not a float. Note: int("hello") would raise a ValueError.float(5)?float() converts the integer 5 to the floating-point number 5.0. Python shows the .0 to signal it's a float, not an int.** is the exponentiation operator. 10 ** 3 = 10 × 10 × 10 = 1000. Not to be confused with * which is multiplication (10 * 3 = 30).17 % 5 evaluate to?% is the modulo operator — it returns the remainder. 17 ÷ 5 = 3 remainder 2. Tip: n % 2 == 0 checks if n is even.{variable} with the actual value at runtime. The f prefix is essential — without it, the braces are printed literally.int(3.9) return?int() truncates (chops off) the decimal part — it does NOT round. int(3.9) → 3. Use round(3.9) to get 4.print(True and False)?and returns True only when both operands are True. Since one operand is False, the result is False.# for single-line comments. Everything from # to end of line is ignored. (// is used in JavaScript/Java; /* */ in C/Java; -- in SQL.)x = 20) overwrites the first. When printed, x holds its latest value: 20.10 // 3 evaluate to?// is floor division — it returns the whole number part of the division, discarding the remainder. 10 ÷ 3 = 3.33… → floor → 3.my_score is valid — uses letters and underscore, starts with a letter. 2score starts with a digit ❌, my score has a space ❌, my-score uses a hyphen (treated as subtraction) ❌.:.0f formats the float with 0 decimal places. 88.5 rounded to 0 decimals = 89 (banker's rounding or standard rounding applies). The output is Score: 89%."Hi" * 3?* operator on strings performs string repetition. "Hi" * 3 gives "HiHiHi" — no spaces are added.10 / 2 return in Python 3?/ is true division — it always returns a float. 10 / 2 → 5.0, not 5. Use // for integer floor division.user_age is valid — starts with a letter, uses only letters and underscores. 2nd_user starts with a digit ❌, user-age uses a hyphen (operator) ❌, user age has a space ❌.2 + 3 * 4?3 * 4 = 12 first, then 2 + 12 = 14. Use parentheses to change order: (2 + 3) * 4 = 20.not False evaluate to?not is the logical negation operator. not False → True. Similarly, not True → False."Age: " + 25?TypeError: can only concatenate str (not "int") to str. Fix: "Age: " + str(25) or use an f-string: f"Age: {25}".type(True) return?True and False are of type bool in Python. Interestingly, bool is a subclass of int (so True == 1 is True), but type(True) specifically returns <class 'bool'>.x = x + 3 reads the current value of x (5), adds 3, and stores the result (8) back into x. This is reassignment. You could also write it as x += 3.f"{3.14159:.2f}" produce?:.2f means: fixed-point notation with 2 decimal places. 3.14159 rounded to 2 decimal places → 3.14."Python"[-1] return?-1 is the last character. "Python" → P(0) y(1) t(2) h(3) o(4) n(5) → -1 = 'n'.x > 5 is True (10 > 5), so it prints "big" and skips all remaining branches — even though x > 3 is also True.range(3) generates 0, 1, 2 — three values. The loop prints 0, then 1, then 2. 3 times total. Remember: range(n) starts at 0 and goes up to (not including) n.break do inside a loop?break exits the loop entirely — execution continues with the code after the loop. continue (not break) skips the current iteration and moves to the next.continue skips the print when i == 3, but the loop continues with 4 and 5. So output is 1 2 4 5.for and while loops?for iterates over a sequence (range, list, string). while keeps running as long as a condition is True. Neither is inherently faster — the right choice depends on what you're doing.range(2, 10, 3) generate?range(start, stop, step): start at 2, step by 3, stop before 10. So: 2, 2+3=5, 5+3=8, 8+3=11 (≥10, stop). Result: 2 5 8.value_if_true if condition else value_if_false. 4 % 2 == 0 is True, so result = "even".n < 3: n=0→1, n=1→2, n=2→3. Now 3 < 3 is False, loop exits. print(n) runs after the loop and prints 3.Coding Challenges
Five hands-on problems using only what you've learned so far. Click Try in Playground to open the editor with a starter template, then write your solution.
Calculate simple interest given a principal amount, rate of interest, and time period. Print the result formatted to 2 decimal places.
Principal: ₹1000 Rate: 5% per year Time: 2 years Simple Interest: ₹100.00
principal = 1000
rate = 5 # percent per year
time = 2 # years
si = (principal * rate * time) / 100
print(f"Principal: ₹{principal}")
print(f"Rate: {rate}% per year")
print(f"Time: {time} years")
print(f"Simple Interest: ₹{si:.2f}")
Convert a temperature from Celsius to Fahrenheit. Print both values on separate lines.
25°C = 77.0°F Body temp 37°C = 98.6°F
celsius = 25
fahrenheit = (celsius * 9/5) + 32
print(f"{celsius}°C = {fahrenheit}°F")
# Bonus: body temperature
body_c = 37
body_f = (body_c * 9/5) + 32
print(f"Body temp {body_c}°C = {body_f}°F")
Swap the values of two variables and print them before and after the swap.
Before: x = 5, y = 10 After: x = 10, y = 5
x = 5
y = 10
print(f"Before: x = {x}, y = {y}")
# Python tuple unpacking — cleanest way to swap
x, y = y, x
print(f"After: x = {x}, y = {y}")
Given a circle's radius, calculate and print the area and circumference, both rounded to 2 decimal places. Use 3.14159 for π.
Radius: 5 Area: 78.54 Circumference: 31.42
pi = 3.14159
radius = 5
area = pi * radius ** 2
circumference = 2 * pi * radius
print(f"Radius: {radius}")
print(f"Area: {area:.2f}")
print(f"Circumference: {circumference:.2f}")
Given a first name and last name, print a formatted name card showing the full name in original, UPPERCASE, and lowercase, plus the initials.
Hello, Arjun Sharma! UPPERCASE: ARJUN SHARMA lowercase: arjun sharma Initials: A.S.
first_name = "Arjun"
last_name = "Sharma"
full_name = first_name + " " + last_name
print(f"Hello, {full_name}!")
print(f"UPPERCASE: {full_name.upper()}")
print(f"lowercase: {full_name.lower()}")
print(f"Initials: {first_name[0]}.{last_name[0]}.")
Given a birth year, calculate the current age and the year the person will turn 100. Use current_year = 2024 and f-strings to format the output.
You are 24 years old. You will turn 100 in the year 2100.
birth_year = 2000
current_year = 2024
age = current_year - birth_year
year_of_100 = birth_year + 100
print(f"You are {age} years old.")
print(f"You will turn 100 in the year {year_of_100}.")
Calculate a shopping bill for 3 items. Apply a 10% discount on the subtotal, then add 18% GST on the discounted amount. Print each step.
Subtotal: ₹525 Discount (10%): -₹52 After Discount: ₹473 GST (18%): +₹85.14 Final Bill: ₹558.14
item1 = 250
item2 = 180
item3 = 95
subtotal = item1 + item2 + item3
discount = subtotal * 0.10
after_discount = subtotal - discount
gst = after_discount * 0.18
final_bill = after_discount + gst
print(f"Subtotal: ₹{subtotal}")
print(f"Discount (10%): -₹{discount:.0f}")
print(f"After Discount: ₹{after_discount:.0f}")
print(f"GST (18%): +₹{gst:.2f}")
print(f"Final Bill: ₹{final_bill:.2f}")
The classic interview challenge. Print numbers 1–20, but replace multiples of 3 with "Fizz", multiples of 5 with "Buzz", and multiples of both with "FizzBuzz".
1 2 Fizz 4 Buzz Fizz
for i in range(1, 21):
if i % 3 == 0 and i % 5 == 0:
print("FizzBuzz")
elif i % 3 == 0:
print("Fizz")
elif i % 5 == 0:
print("Buzz")
else:
print(i)
Use a for loop and an if condition to find the sum of all even numbers from 1 to 50 (inclusive).
Sum of even numbers 1-50: 650
total = 0
for i in range(1, 51):
if i % 2 == 0:
total += i
print(f"Sum of even numbers 1-50: {total}")
Print the full multiplication table for the number 3 (from 1 to 10), formatted as shown below.
3 x 1 = 3 3 x 2 = 6 3 x 3 = 9 3 x 4 = 12 3 x 10 = 30
number = 3
for i in range(1, 11):
print(f"{number} x {i:<2} = {number * i}")