Start Here
About This Free Sample
This sample gives you the first 25 programs of Python Interview Prep, plus 10 of the 100 interview questions from Part B, exactly as they appear in the full book. Every program in it was run for real, and the output under each program is what the code actually prints.
Use it the way the full book is meant to be used: read the task, cover the code, try to write the program yourself, then compare and run both versions.
The full book adds Programs 26–140, all 100 Part B questions, the Predict the Output chapter, and the 7-day practice plan. Details are on the last page of this sample.
Part A · Round 1
Round 1: Warm-Ups
Thirty small programs on the basics: printing, arithmetic, conditions, loops and the classic first exercises every Python learner meets. Interviewers use these as a warm-up in the first minutes, and candidates still trip on them — a leap year rule stated wrong, a factorial that breaks at zero. Move fast, but get them exactly right.
Program 1 — Print a Greeting and a Formatted Line
Basic
That you can print text and values together without fumbling, because every other answer you give starts here.
The task is simple: store a name and a target job in variables, then print a greeting that uses both, in more than one printing style.
name = "Ayesha"
job = "Python Developer"
print("Hello, and welcome!")
print(f"My name is {name} and I am preparing for a {job} interview.")
print("Name:", name, "| Goal:", job)
Output
Hello, and welcome!
My name is Ayesha and I am preparing for a Python Developer interview.
Name: Ayesha | Goal: Python Developer
How it works: print shows whatever you give it. An f-string (the f before the quotes) lets you drop variable values straight into a sentence with curly braces. Passing several values to one print call separates them with spaces.
Program 2 — Add, Subtract, Multiply and Divide Two Numbers
Basic
Whether you know all the arithmetic operators, including the two division flavours beginners mix up.
Store two numbers, then print the result of every basic operation on them: add, subtract, multiply, divide, floor-divide and remainder.
a = 17
b = 5
print("a =", a)
print("b =", b)
print("a + b =", a + b)
print("a - b =", a - b)
print("a * b =", a * b)
print("a / b =", a / b)
print("a // b =", a // b)
print("a % b =", a % b)
Output
a = 17
b = 5
a + b = 22
a - b = 12
a * b = 85
a / b = 3.4
a // b = 3
a % b = 2
How it works: / always gives a float, even when the answer is whole. // is floor division: it divides and rounds down, so 17 // 5 is 3. % gives what is left over after division, which is how you test things like odd and even later.
Program 3 — Find the Square Root of a Number
Basic
That you know Python has a math library ready for this, so you do not try to work it out by hand.
Take a fixed number and print its square root. Use the built-in math help that Python already gives you.
import math
number = 36
root = math.sqrt(number)
print("Number:", number)
print("Square root:", root)
Output
Number: 36
Square root: 6.0
How it works: import math brings in Python's maths tools. math.sqrt(number) returns the square root of the number you pass in. For 36 the answer is 6.0, and it prints as a float because square roots are not always whole numbers.
Program 4 — Calculate the Area of a Triangle
Basic
That you can turn a simple school formula into code and show the answer neatly.
Store the base and height of a triangle, work out its area, and print the result. The formula is half times base times height.
base = 10
height = 6
area = 0.5 * base * height
print("Base:", base)
print("Height:", height)
print(f"Area of the triangle: {area:.2f}")
Output
Base: 10
Height: 6
Area of the triangle: 30.00
How it works: The area is 0.5 * base * height, so we just put that formula into a variable. The :.2f part in the f-string rounds the answer to two decimal places when we print it. That keeps the output tidy and easy to read.
Program 5 — Swap Two Variables Using a Temporary Variable
Basic
That you understand why you cannot just copy one variable over the other without losing its value.
Store two numbers, then swap them so the first holds the second's value and the second holds the first's value. Use a third variable to hold a value safely while you swap.
a = 10
b = 20
print("Before swapping: a =", a, ", b =", b)
temp = a
a = b
b = temp
print("After swapping: a =", a, ", b =", b)
Output
Before swapping: a = 10 , b = 20
After swapping: a = 20 , b = 10
How it works: First we copy a into temp, so its value is safe. Then we can safely copy b into a, because the old value of a is still in temp. Last, we copy temp into b to finish the swap.
Program 6 — Swap Two Variables Without a Temporary Variable
Basic
That you know the short Python way of swapping, which many other languages do not allow.
Store two numbers and swap their values in a single line, without making a third variable. Print the values before and after so the swap is clear.
a = 10
b = 20
print("Before swapping: a =", a, ", b =", b)
a, b = b, a
print("After swapping: a =", a, ", b =", b)
Output
Before swapping: a = 10 , b = 20
After swapping: a = 20 , b = 10
How it works: In Python, a, b = b, a builds both new values first, then assigns them together. Because the right side is fully worked out before anything changes, neither value is lost. This one line does the same job as the three lines with a temporary variable.
Program 7 — Generate a Random Number in a Range
Basic
That you can use the random library and pick a number inside clear limits.
Pick a random whole number between 1 and 100 and print it. Set a fixed starting point first, so the program gives the same number every time it runs.
import random
random.seed(42)
number = random.randint(1, 100)
print("Random number between 1 and 100:", number)
Output
Random number between 1 and 100: 82
How it works: random.seed(42) fixes the starting point for random choices, so the result stays the same on every run. random.randint(1, 100) then picks one whole number, and both 1 and 100 can be picked. Without the seed line, you would get a different number each time.
Program 8 — Convert Kilometres to Miles
Basic
That you can apply a fixed conversion factor and present a measured answer cleanly.
Store a distance in kilometres and convert it to miles. Print both values in one clear sentence.
kilometres = 10
miles = kilometres * 0.621371
print(f"{kilometres} kilometres = {miles:.2f} miles")
Output
10 kilometres = 6.21 miles
How it works: One kilometre is about 0.621371 miles, so we multiply the kilometres by that number. The :.2f in the f-string rounds the miles to two decimal places. Change the stored value and the same line works for any distance.
Program 9 — Convert Celsius to Fahrenheit
Basic
That you can write a formula with more than one step and get the order of operations right.
Store a temperature in Celsius and convert it to Fahrenheit. Print the result in one clear sentence.
celsius = 25
fahrenheit = (celsius * 9 / 5) + 32
print(f"{celsius} Celsius = {fahrenheit:.2f} Fahrenheit")
Output
25 Celsius = 77.00 Fahrenheit
How it works: The formula is Celsius times 9 divided by 5, then add 32. The brackets make sure the multiplication and division happen before we add 32. The answer is rounded to two decimal places when it prints.
Program 10 — Check Whether a Number Is Positive, Negative or Zero
Basic
That you can check three cases in the right order with if, elif and else.
Store a number and print whether it is positive, negative or zero. Only one of the three messages should print.
number = -12
if number > 0:
print(number, "is positive")
elif number < 0:
print(number, "is negative")
else:
print(number, "is zero")
Output
-12 is negative
How it works: The first check asks if the number is greater than 0. If that is false, elif checks if it is less than 0. If both are false, the number must be 0, so else handles it without needing another check.
Program 11 — Check Whether a Number Is Odd or Even
Basic
That you know how to use the remainder operator to test a number.
Store a number and print whether it is odd or even. A number is even when it divides by 2 with nothing left over.
number = 17
if number % 2 == 0:
print(number, "is even")
else:
print(number, "is odd")
Output
17 is odd
How it works: number % 2 gives the remainder after dividing by 2. Even numbers leave a remainder of 0, so we check for that. Any other remainder here means the number is odd, and the else branch prints that.
Program 12 — Find the Largest of Three Numbers
Basic
That you can compare several values and pick the biggest one without writing long chains of checks.
Store three numbers and print the largest of them. Show the three numbers as well, so the answer is easy to check.
a = 12
b = 45
c = 23
largest = max(a, b, c)
print("Numbers:", a, b, c)
print("Largest number:", largest)
Output
Numbers: 12 45 23
Largest number: 45
How it works: max(a, b, c) is a built-in Python function that returns the biggest value you give it. It saves you from writing if checks for every pair. You could also write those checks by hand, and an interviewer may ask you to show that way too.
Program 13 — Check Whether a Year Is a Leap Year
Basic
That you can combine more than one condition carefully, because the leap year rule has an exception.
Store a year and print whether it is a leap year or not. The rule is not just about dividing by 4, so read the checks closely.
year = 2024
if (year % 400 == 0) or (year % 4 == 0 and year % 100 != 0):
print(year, "is a leap year")
else:
print(year, "is not a leap year")
Output
2024 is a leap year
How it works: A year is a leap year if it divides by 400, or if it divides by 4 but not by 100. The % operator checks each division for a remainder of 0. The word or means either part being true is enough, and and means both parts must be true.
Program 14 — Calculate Simple Interest
Basic
That you can use a money formula with three inputs and show the final amount neatly.
Store the principal, the yearly rate and the time in years, then work out the simple interest. Print all the values so the calculation is easy to follow.
principal = 10000
rate = 5
time = 2
interest = (principal * rate * time) / 100
print(f"Principal: {principal}")
print(f"Rate: {rate}%")
print(f"Time: {time} years")
print(f"Simple interest: {interest:.2f}")
Output
Principal: 10000
Rate: 5%
Time: 2 years
Simple interest: 1000.00
How it works: Simple interest is principal times rate times time, divided by 100. We store each part in its own variable with a clear name, so the formula is easy to read. The interest is printed with two decimal places, as money usually is.
Program 15 — Find the ASCII Value of a Character
Basic
That you know characters have number codes behind them, and Python can show you the code.
Store a single character and print its ASCII value. ASCII is the old standard code that gives each common character its own number.
character = "A"
ascii_value = ord(character)
print(f"Character: {character}")
print(f"ASCII value of '{character}': {ascii_value}")
Output
Character: A
ASCII value of 'A': 65
How it works: ord(character) returns the number code for the character you pass in. For the letter A, that code is 65. Its partner function chr() does the reverse and turns a number code back into a character.
Program 16 — Convert Decimal to Binary, Octal and Hexadecimal
Basic
Whether you know the built-in helpers for number bases instead of writing long conversion loops by hand.
Take a decimal number and show the same value in binary, octal and hexadecimal form.
number = 42
print("Decimal:", number)
print("Binary:", bin(number))
print("Octal:", oct(number))
print("Hexadecimal:", hex(number))
Output
Decimal: 42
Binary: 0b101010
Octal: 0o52
Hexadecimal: 0x2a
How it works: bin returns the binary form as a string starting with 0b. oct does the same for octal with 0o, and hex does it for hexadecimal with 0x. The number itself does not change, only the way it is written.
Program 17 — Display a Month Calendar
Basic
Whether you can find and use a ready-made module instead of building a calendar grid yourself.
Show the calendar for one fixed month and year, laid out with weekdays and dates in the right columns.
import calendar
print(calendar.month(2026, 11))
Output
November 2026
Mo Tu We Th Fr Sa Su
1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30
How it works: The calendar module comes with Python, so you only need to import it. calendar.month takes a year and a month and returns the whole month as neat text. Printing that text gives you the finished calendar.
Program 18 — Solve a Quadratic Equation
Intermediate
Whether you can turn a maths formula into code and handle cases where the answer is not a plain real number.
Find both roots of a quadratic equation with fixed coefficients, using the standard quadratic formula.
import cmath
a = 1
b = -5
c = 6
d = b ** 2 - 4 * a * c
root1 = (-b + cmath.sqrt(d)) / (2 * a)
root2 = (-b - cmath.sqrt(d)) / (2 * a)
print(f"Equation: {a}x^2 + ({b})x + ({c}) = 0")
print("Root 1:", root1.real)
print("Root 2:", root2.real)
Output
Equation: 1x^2 + (-5)x + (6) = 0
Root 1: 3.0
Root 2: 2.0
How it works: The part under the square root, b ** 2 - 4 * a * c, is called the discriminant. cmath.sqrt works even when that value is negative, so the code does not crash. The formula is then used twice, once with a plus and once with a minus, to get both roots.
Follow-up twist: Change the coefficients so the discriminant is negative, and check that the program prints complex roots instead of failing.
Program 19 — Print the Multiplication Table of a Number
Basic
Whether you can run a loop a set number of times and build a clear line of output on each pass.
Print the multiplication table of a fixed number, from 1 times up to 10 times.
number = 7
for i in range(1, 11):
print(f"{number} x {i} = {number * i}")
Output
7 x 1 = 7
7 x 2 = 14
7 x 3 = 21
7 x 4 = 28
7 x 5 = 35
7 x 6 = 42
7 x 7 = 49
7 x 8 = 56
7 x 9 = 63
7 x 10 = 70
How it works: range(1, 11) gives the values 1 to 10, one at a time. On each pass the code multiplies the fixed number by the current value. The f-string puts the sum and its answer together in one tidy line.
Program 20 — Check Whether a Number Is Prime
Basic
Whether you understand what makes a number prime and can test for divisors in a sensible way.
Decide if a fixed number is prime or not, and print the result in a clear sentence.
number = 29
is_prime = True
if number < 2:
is_prime = False
else:
for i in range(2, int(number ** 0.5) + 1):
if number % i == 0:
is_prime = False
break
if is_prime:
print(number, "is a prime number.")
else:
print(number, "is not a prime number.")
Output
29 is a prime number.
How it works: Numbers below 2 are not prime, so they are handled first. The loop only checks divisors up to the square root, because a larger divisor would need a smaller partner that was already checked. If any divisor divides evenly, the number is not prime and the loop stops early.
Program 21 — Print All Prime Numbers in an Interval
Intermediate
Whether you can reuse a prime check inside a loop over a range without getting the edges wrong.
Find and print every prime number between a fixed start value and a fixed end value.
start = 10
end = 50
print(f"Prime numbers between {start} and {end}:")
for num in range(start, end + 1):
if num < 2:
continue
is_prime = True
for i in range(2, int(num ** 0.5) + 1):
if num % i == 0:
is_prime = False
break
if is_prime:
print(num, end=" ")
print()
Output
Prime numbers between 10 and 50:
11 13 17 19 23 29 31 37 41 43 47
How it works: The outer loop visits each number in the interval one by one. The inner loop tests that number for divisors up to its square root, just like a single prime check. Numbers that pass the test are printed on the same line, separated by spaces.
Program 22 — Find the Factorial of a Number With a Loop
Basic
Whether you can build up a running product step by step inside a loop.
Work out the factorial of a fixed number by multiplying all whole numbers from 1 up to that number.
number = 6
result = 1
for i in range(1, number + 1):
result = result * i
print(f"Factorial of {number} is {result}")
Output
Factorial of 6 is 720
How it works: The result starts at 1, which is safe because multiplying by 1 changes nothing. Each pass multiplies the result by the next number in the range. After the last pass, the result holds the full factorial.
Program 23 — Find the Factorial of a Number With Recursion
Intermediate
Whether you understand recursion well enough to give it a clear stopping point and a smaller step.
Work out the factorial of a fixed number with a function that calls itself.
def factorial(n):
if n == 0 or n == 1:
return 1
return n * factorial(n - 1)
number = 6
print(f"Factorial of {number} is {factorial(number)}")
Output
Factorial of 6 is 720
How it works: When the function gets 0 or 1, it returns 1 straight away, and that stops the chain. For any larger number, it returns that number times the factorial of one less. Those smaller calls build back up until the first call gets the final answer.
Program 24 — Print the Fibonacci Sequence With a Loop
Basic
Whether you can keep two values moving together as a sequence builds.
Print the first ten numbers of the Fibonacci sequence, where each new number is the sum of the two before it.
count = 10
a = 0
b = 1
print("Fibonacci sequence:")
for i in range(count):
print(a, end=" ")
a, b = b, a + b
print()
Output
Fibonacci sequence:
0 1 1 2 3 5 8 13 21 34
How it works: The sequence starts with 0 and 1, stored in a and b. Each pass prints a, then replaces the pair with b and a + b in one line. That swap keeps both values ready for the next step.
Program 25 — Print the Fibonacci Sequence With Recursion
Intermediate
Whether you can split a sequence problem into two base cases and one self-calling step.
Print the first ten numbers of the Fibonacci sequence by using a function that calls itself.
def fibonacci(n):
if n == 0:
return 0
if n == 1:
return 1
return fibonacci(n - 1) + fibonacci(n - 2)
count = 10
print("Fibonacci sequence:")
for i in range(count):
print(fibonacci(i), end=" ")
print()
Output
Fibonacci sequence:
0 1 1 2 3 5 8 13 21 34
How it works: The function returns 0 for position 0 and 1 for position 1, and those are the base cases. For any later position, it adds the results of the two positions before it. The loop calls the function once for each position from 0 to 9.
Part B · A Taste
A Taste of Part B
Part B of the full book holds 100 interview questions. Here are the first 10, exactly as they appear in the full book: the question, then a short plain answer. In the full book the concepts continue through strings and collections, functions, object-oriented Python and advanced topics, and finish with 20 Predict the Output questions.
Q1. What does "mutable" and "immutable" mean? Name examples of each.
Mutable means you can change the object in place after you create it, without making a new one. Immutable means you cannot change it in place. Any change makes a new object. Mutable examples: list, dict and set. Immutable examples: int, float, str and tuple.
Q2. What is the difference between is and ==?
== checks if two values are equal. is checks if two names point to the exact same object in memory.
Use == for most comparisons, and use is for checks like x is None.
a = [1, 2]; b = [1, 2]
print(a == b) # True
print(a is b) # False
Q3. What is the LEGB rule?
LEGB is the order Python uses to look up a name: Local, Enclosing, Global, then Built-in.
Local means inside the current function. Enclosing means in any outer function around it.
Global means at module level, and Built-in means names Python provides, like len. Python stops at the first match it finds.
Q4. What are Python keywords? Can you use one as a variable name?
Keywords are reserved words with a special job in the language, like if, for, while, return and class.
No, you cannot use one as a variable name. Python will raise a SyntaxError.
Pick a different name instead, like class_name instead of class.
Q5. What does it mean that Python is dynamically typed?
It means a variable does not have a fixed type. The type belongs to the value, and Python checks it while the program runs.
You do not declare a type first, and the same name can hold different types at different times.
For example, x = 5 and later x = "hi" are both allowed.
Q6. What is the difference between a list and a tuple?
Both store items in order, and you read items from both in the same way. A list is mutable: you can add, remove and change items. You write it with square brackets. A tuple is immutable: once made, it cannot be changed. You write it with round brackets, so use it for fixed data that should stay the same.
Q7. When would you use a set instead of a list?
Use a set when you need unique items and fast checks for whether an item is present. A set does not keep duplicates and does not promise a fixed order. Use a list instead when order matters, when duplicates are allowed, or when you need to pick items by index.
Q8. How do you convert between int, float and str? What can go wrong?
Use int(), float() and str() to convert. For example, int("42") gives 42 and str(42) gives "42".
int(3.9) drops the part after the point and gives 3, it does not round.
Things can go wrong when the text does not fit: int("abc") and int("3.5") both raise ValueError.
Q9. Which values count as False in Python?
These count as False: False, None, the numbers 0 and 0.0, and empty values like "", [], (), {} and set().
Almost everything else counts as True, even a string like "False" or a list with one zero in it, like [0].
Python uses this rule whenever a value is tested in an if or while.
Q10. What is the difference between None, 0 and an empty string?
None means no value or nothing here. It is its own type, and there is only one None.
0 is the integer zero, and "" is a string with length zero.
All three count as False in a test, but they are not equal to each other. For example, None == 0 is False.