Loading...
Loading...
Python interview guide
Syntax, data types, control flow, functions, strings and error handling. Every answer is short enough to say aloud, and every question links to the lesson that teaches it.
60 questionsLast updated
Python is a high-level, interpreted programming language known for clean, readable syntax. Its main strengths are developer productivity, extensive standard library packages, and huge adoption in backend engineering, data science and AI.
Lesson: What is Python?Python is dynamically typed and uses indentation instead of curly braces to define code blocks. This results in concise code that is fast to write, though statically typed languages like Java can catch type errors before execution.
Lesson: What is Python?No. Python executes statements at the top level immediately. However, scripts often use if __name__ == '__main__': so code runs only when executed directly and not when imported.
A SyntaxError occurs during compilation when the code violates Python's grammar rules (such as unclosed parentheses or mismatched quotes), preventing the program from running.
Lesson: Your first Python programIn C++ and Java, a variable declaration specifies a fixed memory address typed to a primitive or class reference. In Python, variables are untyped name tags in a namespace dictionary pointing to objects allocated in heap memory. Objects carry their own type descriptor and reference count.
Lesson: Variables and Name BindingName binding links a name to an object. An assignment such as total = 95 creates or finds the object 95 and binds total to it. A later assignment rebinds the name and leaves the old object alone. When no name refers to an object any more, Python frees it.
total and Total different variables?Python names are case-sensitive, so each spelling is its own name. PEP 8 uses lowercase snake_case for variables, which avoids accidental clashes and keeps code uniform across teams.
Lesson: Variables and Name BindingNo. Python integers have arbitrary precision, so they grow as needed until memory runs out. In Java or C a 32-bit or 64-bit int wraps around. That is why 2 ** 100 prints exactly in Python.
1e3 mean and what type is it?It is scientific notation for 1 x 10 to the power 3, which is 1000.0. It is always a float, even when the value is whole. Use it for very large or very small numbers.
Lesson: Numeric Types: int and floatIt returns the nearest whole number as an int, for example round(14.75) is 15. With a second argument, such as round(x, 2), it returns a float rounded to that many decimal places.
No. Both create the same str object. Choose the one that avoids escaping: double quotes for text with an apostrophe, single quotes for text with double quotes. Pick one style and stay consistent in a project.
Lesson: Strings and BooleansZero of any number type, the empty string, empty containers such as an empty list, dictionary or set, and None. Every other value is truthy. Custom classes are truthy unless they define a way to say otherwise.
Lesson: Strings and BooleansNone is a singleton in Python, meaning only one instance of NoneType exists throughout the runtime. The is operator tests object identity (memory address), which is faster and cannot be overridden. In contrast, == invokes the object's __eq__() method, which could be customized to return unexpected results.
int("3.14") fail while int(3.14) works?int() on a string accepts only text that looks like a whole number, so "3.14" raises ValueError. int() on a float is allowed and drops the decimal part. To parse such text, call float() first and then int().
Lesson: Type Casting and NoneImplicit conversion happens automatically in safe cases, such as 1 + 2.5 giving the float 3.5. Explicit conversion uses int(), float() or str() when you decide. Python refuses to guess between text and numbers: "5" + 5 raises a TypeError.
CPython keeps ready-made objects for small integers, from -5 to 256, and reuses them. So two names bound to 100 usually point to the same object. It is an implementation detail; never rely on it. Compare numbers with ==.
Lesson: Variables and Data Types CheckpointCall int() or float() on the text. A bad value raises ValueError, so check the text or handle the error. Remember that int("3.5") fails; use float() first if decimals are possible.
Lesson: Variables and Data Types Checkpointint, float, str, bool and NoneType. Call type(value) to see the type of the object a name points to. Remember the type belongs to the object, so the same name can point to different types over time.
// behave with negative numbers compared with C++ or Java?In C++ and Java, integer division truncates toward zero, so -7 / 2 is -3. In Python -7 // 2 rounds down toward negative infinity and gives -4. This keeps (a // b) * b + a % b == a true for every sign.
No. Python ints are arbitrary-precision, so 2 ** 100 or a 30-digit factorial is exact; only available memory limits the size. Floats are different: they have a fixed range and become inf beyond it.
// return?If both operands are ints, an int. If either operand is a float, a float (7.5 // 2 is 3.0). The value is still floored; only the type follows the operands.
++ and --?Numbers in Python are immutable objects, so an increment cannot change a number in place; it can only rebind a name to a new object. x += 1 says exactly that. Python also avoids the pre- and post-increment confusion of C and Java.
x += 1 the same as x = x + 1 for an int?Yes. Both compute a new int and rebind x to it. The short form only evaluates x once, which matters when the target is a more complex expression.
a = b = 0 and a, b = 0, 0 for ints?For ints there is no visible difference: both leave two names holding 0, and updating one later does not touch the other. The first form points both names at the same object, which only matters for changeable objects.
Lesson: Assignment and Compound Operators== and is?== compares values and can be changed by a class. is compares identity: whether two names refer to the same object. Use == for numbers and strings, and is for None.
==?Many decimals, such as 0.1, cannot be stored exactly in binary, so small errors creep in: 0.1 + 0.2 is 0.30000000000000004. Check that the difference is smaller than a tolerance, or use the decimal module for money.
5 == 5.0 true, and is 5 is 5.0 true?The first is True because the values are equal. The second is False: an int and a float are different objects of different types, and Python warns that is with a literal is a mistake.
Python stops evaluating and or or as soon as the result is known. This allows guards such as divisor != 0 and total / divisor > 2, which never divides by zero, and it avoids slow or risky work on the right side.
False, None, zero of any number type, and empty text or collections. Because of this, code can write if name: instead of if name != "":. The danger is a real zero, which is also false.
count = user_count or 10 when the user count is 0?Zero is false, so or replaces a valid 0 with the default 10. When 0 is a real answer, test for None explicitly: user_count if user_count is not None else 10 (the conditional expression comes later in the course).
2 ** 3 ** 2 evaluate to?512. The power operator groups right to left, so it is 2 ** (3 ** 2). Most other operators group left to right, so 10 - 4 - 3 is 3.
total / units > 100 safe?Writing units > 0 and total / units > 100 means that when units is 0 the left side is false and Python never runs the division, so no ZeroDivisionError happens.
sep and end arguments of print() do?sep is the text placed between the values, a space by default. end is the text written after the last value, a new line by default. Together they let you control the layout of one line without joining strings by hand.
print("Total:" + 5) fail while print("Total:", 5) works?The + operator does not join a str and an int, so it raises a TypeError. With commas, print() converts every value to text itself.
print() return?It returns None. Its job is the side effect of writing text, so assigning its result to a variable is almost always a mistake.
% formatting and .format()?They put the value next to the text it belongs to, so they are easier to read, and they run faster because Python builds the string directly. Any expression can go inside the braces.
Lesson: Formatted Output with f-stringsAt the moment the line runs. It produces a normal str, so later changes to the variables do not change the text that was already built.
Lesson: Formatted Output with f-stringsf"{x:>10,.2f}" mean?Show x right aligned in a field 10 characters wide, with thousands commas and two decimals. The order is alignment, width, comma, then precision.
input() differ between Python 2 and Python 3?In Python 2, input() evaluated what the user typed as code, which was a security risk. Python 3 removed that: its input() is the old raw_input() and always returns a string.
int("abc") raises a ValueError and the program stops. A try/except block, covered later, lets the program ask again.
A common idiom is a, b = map(int, input().split()). split() cuts the line at spaces and map(int, ...) converts each piece.
An f-string with format specifiers, such as f"{name:<12}{amount:>10,.2f}". It is short, readable and fast.
input() need a conversion for numbers?It always returns a str. Without int() or float(), + joins text and * repeats it instead of doing arithmetic.
Wrap the conversion in try/except ValueError and ask again. This is covered in the Exception Handling module.
Significant whitespace enforces visual clarity and readable code structure across all codebases. In languages with curly braces, code can be formatted deceptively where indentation does not match block structure. Python guarantees that what the human eye sees matches what the interpreter executes.
Lesson: The if and if-else StatementsEvaluating an if condition takes O(1) time if the condition itself is a primitive comparison or attribute check. If the condition calls an expensive function or scans a collection, the complexity is determined by that expression.
if x is None instead of if not x?if not x is True for every falsy value: None, 0, 0.0, an empty string or an empty list. if x is None is True only for None. Use is None when 0 or an empty string is a valid value, for example a quantity of 0 that must not be treated as missing.
Guard clauses test for invalid or edge conditions early at the top of a function and exit immediately (e.g. if not user: return False). This flattens the code, avoiding the 'pyramid of doom' anti-pattern and making the happy path clear and maintainable.
and and or?Python stops as soon as the result is known. In a and b, if a is falsy, b is never evaluated. In a or b, if a is truthy, b is never evaluated. This is why if user and user.is_active: is safe when user is None, and why the result of and/or is one of the operands, not always True or False.
Use elif when the cases exclude each other and only one result is wanted, such as grade bands. Use separate if statements when the checks are independent and more than one may apply, such as adding a member bonus and a festival bonus to the same order. With elif the second check is skipped after the first match.
Lesson: The elif Ladder and Logical ConditionsYes, ternary expressions can be chained: x if c1 else y if c2 else z. However, chaining more than two ternary expressions harms readability and violates the Zen of Python ('Readability counts'). When multiple conditions exist, standard if-elif-else statements should be used.
Join checks with and, use elif for exclusive cases, or use guard clauses that handle the invalid case first and then continue with the main path. Each of these removes one level of indentation. In a function a guard is usually if not valid: return; at module level an elif ladder gives the same flat shape.
A traditional switch statement in C/Java only inspects primitive values or strings. Python's match-case performs structural destructuring: it can match sequence shapes (e.g. case [x, y]:), mapping keys, class types (case Point(x, y):), extract variables into the scope, and enforce conditional guards. Furthermore, Python has no fallthrough bugs.
match and case reserved keywords in Python?In Python, match and case are 'soft keywords'. To preserve backward compatibility with existing codebases, they are treated as keywords only inside pattern matching syntax. You can still use match = re.search(...) or variable names named case elsewhere without syntax errors.
A bare name in a case, such as case colour:, is a capture pattern: it matches any value and binds it to that name. So RED = "red" followed by case RED: does not compare with the constant. It matches everything and overwrites RED. To compare with a named constant use a dotted name such as case Colour.RED: or a literal.
FizzBuzz tests basic control flow, modulo operations, and logical ordering. Candidates must print numbers from 1 to N, replacing multiples of 3 with 'Fizz', multiples of 5 with 'Buzz', and multiples of both with 'FizzBuzz'. It quickly reveals whether a programmer understands condition ordering and avoids code duplication.
Lesson: Conditional Statements CheckpointNot in general. CPython evaluates the cases one after another, much like an elif ladder, and does not turn them into a hash-based jump table, so a match with N literal cases is O(N) in the worst case. Choose match for readability and for matching the shape of data, and keep the most common case near the top if speed matters.
Lesson: Conditional Statements CheckpointA year is a leap year if it is divisible by 400, or divisible by 4 but not by 100. Written as (y % 4 == 0 and y % 100 != 0) or y % 400 == 0, the exceptions are handled correctly: 1900 fails, 2000 passes. In a ladder, the 400 and 100 rules must be tested before the plain 4 rule, or century years are classified wrongly.
Choose a for loop when iterating over a known sequence or collection where the number of iterations is predetermined. Choose a while loop when the number of cycles depends on runtime events, convergence thresholds, user inputs, or external stream status (e.g. reading from a network socket until EOF).
A standard while loop updating scalar counters operates in O(1) auxiliary space, as it rebinds existing references in the current stack frame.
Lesson: The while LoopEach lesson has quizzes, practice and more interview questions on the same topic.
Open the first lesson