These are the notes for Python Coding Questions, episode 1, interview and placement practice for people who finished the SyntaxPilot Python course. Three number questions that look easy: reverse a number, palindrome number and sum of digits. Almost everyone gets 123 right. The traps are in negative numbers, in Python's two kinds of division (/ and //) and in input that arrives as a string.
Each question follows the same steps: read the problem, think out loud, the obvious attempt, a real failure, why, the fix, every test case, and the complexity.
Every program was run with Python 3.13 (python3 main.py), the SyntaxPilot compiler's Python command. Programs that read standard input were run with the input piped in, for example printf '123\n9045\n-123\n0\n' | python3 main.py. Every output below is real.
The one trick: % 10 and // 10
A cashier has a stack of notes with the digits of 1234 written on them, the last digit, 4, on top.
| At the counter | In Python | For 1234 |
|---|---|---|
| a stack of notes: 1 2 3 4 | n = 1234 |
a number, digit by digit |
| look at the top note | n % 10 (the remainder after dividing by 10) |
4 |
| take it off the stack | n // 10 (floor division: divide and drop the decimals) |
123 |
% is the remainder operator (people also call it modulo): a % b is what is left after dividing a by b. // is floor division: it divides and rounds the result down to a whole number. divmod(a, b) gives both at once: divmod(1234, 10) is (123, 4).
Why not just n / 10? Because in Python 3, / always gives a float (a number with a decimal point): 1234 / 10 is 123.4. Q1 shows what happens if you forget this.
The digit loop, used by all three questions:
while n > 0:
d = n % 10 # last digit
# ... use d ...
n = n // 10 # drop it
n |
d = n % 10 |
n // 10 |
|---|---|---|
| 1234 | 4 | 123 |
| 123 | 3 | 12 |
| 12 | 2 | 1 |
| 1 | 1 | 0 → stop |
Q1: Reverse a number
Problem. Given an integer n, return its digits reversed, keeping the sign.
| Input | Output |
|---|---|
123 |
321 |
1200 |
21 (leading zeros vanish) |
7 |
7 |
0 |
0 |
-123 |
-321 |
Think out loud
Input: one integer. Output: an integer (not a string), same sign. Build the answer rev from 0: for each digit, shift rev one place left (× 10) and add the digit: 0 → 3 → 32 → 321. Say the edge cases to the interviewer before you write any code: 0, a single digit, a number ending in zeros, and a negative number.
The obvious attempt: the string trick
Turn the number into a string, reverse it with the slice [::-1], and turn it back with int:
def reverse(n):
return int(str(n)[::-1])
for n in [123, 1200, 7, -123]:
print(n, "->", reverse(n))
Output:
123 -> 321
1200 -> 21
7 -> 7
Traceback (most recent call last):
File "main.py", line 5, in <module>
print(n, "->", reverse(n))
~~~~~~~^^^
File "main.py", line 2, in reverse
return int(str(n)[::-1])
ValueError: invalid literal for int() with base 10: '321-'
Why: the minus sign is a character too
str(-123) is "-123". Reversed, it is "321-", and int() can't read a minus sign at the end. (int("0021") is fine, which is why 1200 worked.) Many interviewers also say "no string tricks, do it with maths".
The second attempt: the math way, with plain /
def reverse(n):
rev = 0
while n > 0:
rev = rev * 10 + n % 10
n = n / 10
return rev
print(reverse(123))
Output:
inf
Why: / always gives a float
n / 10 gives 12.3, then 1.23, then 0.123, ... n gets tiny but stays above 0 for about 325 rounds, until it is too small to store and becomes 0.0. Every round multiplies rev by 10, and a float can't hold more than about 1.8 × 10³⁰⁸, so rev becomes inf (infinity). No error, just a nonsense answer.
The third attempt: //, and the negative-number surprise
def reverse(n):
rev = 0
while n > 0:
rev = rev * 10 + n % 10
n = n // 10
return rev
for n in [123, 1200, 7, -123]:
print(n, "->", reverse(n))
Output:
123 -> 321
1200 -> 21
7 -> 7
-123 -> 0
while n > 0 is false at once for a negative number, so the answer is 0: wrong, and silent. Changing the loop to while n != 0 doesn't help, because // and % behave differently for negatives:
print(123 // 10, 123 % 10)
print(-123 // 10, -123 % 10)
Output:
12 3
-13 7
Floor division rounds down, towards minus infinity: −12.3 becomes −13 (not −12). Python then makes the remainder fit: −13 × 10 + 7 = −123. So the "last digit" of −123 comes out as 7, and -1 // 10 is -1 again, so while n != 0 never ends.
The fix
Remember the sign, reverse the positive part abs(n), put the sign back:
def reverse(n):
sign = -1 if n < 0 else 1
n = abs(n)
rev = 0
while n > 0:
rev = rev * 10 + n % 10
n = n // 10
return sign * rev
for n in [123, 1200, 7, 0, -123]:
print(n, "->", reverse(n))
print(reverse(12345678901234567890123456789))
Output:
123 -> 321
1200 -> 21
7 -> 7
0 -> 0
-123 -> -321
98765432109876543210987654321
Python integers have no size limit: the 29-digit number reversed exactly. In C, Java or JavaScript the same code overflows or loses digits; there, interviewers ask "what if the reverse doesn't fit in 32 bits?" In Python, say: "Python ints are arbitrary precision, so no overflow, but if the problem says 32-bit, I'll return 0 when the result is outside −2³¹ … 2³¹ − 1."
Complexity
The loop runs once per digit. A number with d digits takes d steps: O(d) time, and d ≈ log₁₀ n, so people also write O(log n). O(1) space: a few variables.
Q2: Palindrome number
Problem. A palindrome reads the same forwards and backwards (madam, 121). Given an integer n, return True if it is a palindrome number.
| Input | Output |
|---|---|
121 |
True |
123 |
False |
7 |
True |
10 |
False (reversed: 01) |
-121 |
False (backwards: 121-) |
Think out loud
Reverse it with the digit loop and compare with n. Negative numbers can never be palindromes, because the minus sign is only at the front.
The obvious attempt
def is_palindrome(n):
rev = 0
while n > 0:
rev = rev * 10 + n % 10
n = n // 10
return rev == n
for n in [121, 123, 7]:
print(n, is_palindrome(n))
Output:
121 False
123 False
7 False
Why: the loop destroyed n
The loop keeps doing n = n // 10 until n is 0, so return rev == n compares the reverse with 0. It's like doing rough work on the only copy of a form: the original is gone.
The fix
def is_palindrome(n):
if n < 0:
return False
original = n
rev = 0
while n > 0:
rev = rev * 10 + n % 10
n = n // 10
return rev == original
for n in [121, 123, 7, 0, 1221, -121, 10]:
print(n, is_palindrome(n))
Output:
121 True
123 False
7 True
0 True
1221 True
-121 False
10 False
The string way (fine here)
def is_pal(n):
return str(n) == str(n)[::-1]
for n in [121, 123, -121, 10]:
print(n, is_pal(n))
Output:
121 True
123 False
-121 False
10 False
There is no int() at the end, so "-121" vs "121-" is simply not equal. Trade-off: both ways take O(d) time; the loop uses O(1) extra space, the string way O(d). Say that out loud.
Q3: Sum of digits (from standard input)
Problem. Read integers from standard input (stdin), one per line, and print the sum of the digits of each.
| Input line | Output |
|---|---|
123 |
123 -> 6 |
9045 |
9045 -> 18 |
-123 |
-123 -> 6 (the sign isn't a digit) |
0 |
0 -> 0 |
Think out loud
for line in sys.stdin reads one line at a time; line.strip() removes the newline at the end. Then sum the digits.
The obvious attempt: add the characters
import sys
for line in sys.stdin:
s = line.strip()
total = 0
for ch in s:
total += ch
print(s, "->", total)
Output:
Traceback (most recent call last):
File "main.py", line 7, in <module>
total += ch
TypeError: unsupported operand type(s) for +=: 'int' and 'str'
Why: input is always a string
Every line from input is a str, and so is each character. Python refuses to add the number 0 and the string "1" (JavaScript would glue them into "01"; Python raises a TypeError instead of guessing).
The second attempt: int(ch)
import sys
for line in sys.stdin:
s = line.strip()
total = 0
for ch in s:
total += int(ch)
print(s, "->", total)
Output:
123 -> 6
9045 -> 18
Traceback (most recent call last):
File "main.py", line 7, in <module>
total += int(ch)
~~~^^^^
ValueError: invalid literal for int() with base 10: '-'
The minus sign is a character too, and int("-") is not a number.
The fix
import sys
def digit_sum(n):
n = abs(n)
total = 0
while n > 0:
total += n % 10
n = n // 10
return total
for line in sys.stdin:
s = line.strip()
print(s, "->", digit_sum(int(s)))
Output:
123 -> 6
9045 -> 18
-123 -> 6
0 -> 0
The Pythonic one-liner: sum(int(ch) for ch in s.lstrip("-")) gives the same answers. Know both: the loop shows you understand digits; the one-liner shows you know Python.
Complexity summary
| Question | Loop turns | Time | Extra space |
|---|---|---|---|
| Reverse a number | one per digit | O(d) = O(log n) | O(1) |
| Palindrome number | one per digit | O(d) | O(1) (string way: O(d)) |
| Sum of digits | one per digit, per line | O(d) per number | O(1) |
Common mistakes (and what you really see)
| Mistake | What you see | Why | Fix |
|---|---|---|---|
int(str(-123)[::-1]) |
ValueError: invalid literal for int() with base 10: '321-' |
the - is reversed too |
sign + abs(n), or the digit loop |
n = n / 10 in the digit loop |
inf |
/ always gives a float: 12.3, 1.23, ... |
n = n // 10 |
while n > 0 on a negative n |
-123 -> 0 (silent) |
the loop never runs | work on abs(n) |
while n != 0 on a negative n |
never ends: −123 → −13 → −2 → −1 → −1 ... | // rounds down: -1 // 10 is -1 |
work on abs(n) |
return rev == n after the loop |
False for 121 and even 7 |
the loop turned n into 0 |
original = n first |
total += ch on input characters |
TypeError: unsupported operand type(s) for +=: 'int' and 'str' |
input is a string | int(...) first |
int(ch) for every character of "-123" |
ValueError: invalid literal for int() with base 10: '-' |
- is not a digit |
abs(int(s)), or s.lstrip("-") |
while n > 0: count += 1 to count digits |
0 -> 0 |
the loop never runs for 0 | start at 1 and loop while n >= 10 |
Mini project: a digit report
Read integers from stdin, one per line, and print a report for each: digit count, reverse, palindrome, digit sum. Lines that aren't integers are skipped with a message (int("12.5") raises ValueError).
import sys
def reverse(n):
sign = -1 if n < 0 else 1
n = abs(n)
rev = 0
while n > 0:
rev = rev * 10 + n % 10
n //= 10
return sign * rev
def digit_count(n):
n = abs(n)
count = 1
while n >= 10:
n //= 10
count += 1
return count
def digit_sum(n):
n = abs(n)
total = 0
while n > 0:
total += n % 10
n //= 10
return total
for line in sys.stdin:
s = line.strip()
try:
n = int(s)
except ValueError:
print(f"{s!r}: not an integer, skipped")
continue
print(f"{n}: digits={digit_count(n)} reverse={reverse(n)} "
f"palindrome={n >= 0 and reverse(n) == n} sum={digit_sum(n)}")
Input 1221, -907, 0, 12.5, abc, 1200. Output:
1221: digits=4 reverse=1221 palindrome=True sum=6
-907: digits=3 reverse=-709 palindrome=False sum=16
0: digits=1 reverse=0 palindrome=True sum=0
'12.5': not an integer, skipped
'abc': not an integer, skipped
1200: digits=4 reverse=21 palindrome=False sum=3
n //= 10 is short for n = n // 10 (an augmented assignment).
Your turn: count the digits (solution)
Question. Count how many digits n has with the digit loop. 12345 → 5, -907 → 3, 0 → 1.
Solution
The trap: while n > 0: count += 1; n //= 10 gives 0 for n = 0, because the loop never runs. Every number has at least one digit, so start the count at 1 and keep going while there is more than one digit left:
def digit_count(n):
n = abs(n)
count = 1
while n >= 10:
n //= 10
count += 1
return count
for n in [12345, -907, 0, 7, 10, 99999999999999999999]:
print(n, "->", digit_count(n))
Output:
12345 -> 5
-907 -> 3
0 -> 1
7 -> 1
10 -> 2
99999999999999999999 -> 20
Time O(d), space O(1). (The string way: len(str(abs(n))).)
Practice questions (with solutions)
1. Product of the digits of n. 12345 → 120, -907 → 0, 0 → 0.
Solution
Start the product at 1 (not 0), and make sure 0 still gives 0 by looking at the first digit before checking the loop condition:
def digit_product(n):
n = abs(n)
product = 1
while True:
product *= n % 10
n //= 10
if n == 0:
return product
for n in [12345, -907, 0, 7, 999]:
print(n, "->", digit_product(n))
Output:
12345 -> 120
-907 -> 0
0 -> 0
7 -> 7
999 -> 729
Time O(d), space O(1).
2. Reverse with divmod. Rewrite reverse so that one call gives both the quotient and the remainder.
Solution
def reverse(n):
sign = -1 if n < 0 else 1
n, rev = abs(n), 0
while n:
n, d = divmod(n, 10)
rev = rev * 10 + d
return sign * rev
print([reverse(n) for n in [123, 1200, 7, 0, -123]])
Output:
[321, 21, 7, 0, -321]
while n: means "while n is not 0" (0 is falsy).
3. Reverse a 32-bit integer (LeetCode style). Return 0 if the reversed number is outside −2³¹ … 2³¹ − 1.
Solution
def reverse32(n):
sign = -1 if n < 0 else 1
rev = int(str(abs(n))[::-1]) * sign
return rev if -2**31 <= rev <= 2**31 - 1 else 0
for n in [123, -123, 1534236469, 2147483647]:
print(n, "->", reverse32(n))
Output:
123 -> 321
-123 -> -321
1534236469 -> 0
2147483647 -> 0
Python ints never overflow, so the check is explicit. str(abs(n)) has no minus sign, so int() is safe here.
4. Is n a palindrome in binary? 9 is 1001 → True, 10 is 1010 → False.
Solution
def binary_palindrome(n):
b = bin(n)[2:] # bin(9) is '0b1001'
return b == b[::-1]
for n in [9, 10, 5, 0]:
print(n, bin(n), binary_palindrome(n))
Output:
9 0b1001 True
10 0b1010 False
5 0b101 True
0 0b0 True
5. Digital root. Keep summing the digits until one digit is left: 9875 → 29 → 11 → 2.
Solution
def digit_sum(n):
total = 0
while n > 0:
total += n % 10
n //= 10
return total
def digital_root(n):
n = abs(n)
while n >= 10:
n = digit_sum(n)
return n
print([digital_root(n) for n in [9875, 0, 7, 99, 123456789]])
print([(n - 1) % 9 + 1 if n else 0 for n in [9875, 0, 7, 99, 123456789]])
Output:
[2, 0, 7, 9, 9]
[2, 0, 7, 9, 9]
The second line is the O(1) formula: the digital root of a positive n is (n - 1) % 9 + 1.
Quick quiz
What does this print?
n, s = 47, 0
while n > 0:
s = s * 10 + n % 10
n = n // 10
print(s, -47 // 10)
(A) 74 -4 (B) 74 -5 (C) 47 -4 (D) 74.0 -5
Answer
(B) 74 -5. The loop reverses 47 into 74. And -47 // 10 is −4.7 rounded down (towards minus infinity): −5. Real output:
74 -5
Bonus quiz. What are -7 // 2, -7 % 2 and int(-7 / 2)?
Answer
-4, 1 and -3. // rounds down (−3.5 → −4) and % follows it (−4 × 2 + 1 = −7). int() cuts towards 0 (−3.5 → −3).
print(-7 // 2, -7 % 2, int(-7 / 2))
-4 1 -3
Interview questions
- How do you get the last digit of a number in Python, and remove it?
n % 10gives it;n // 10removes it. Plainn / 10gives a float. - What is the difference between
/and//?/is true division and always returns a float (7 / 2is3.5,6 / 2is3.0);//is floor division (7 // 2is3). - What is
-7 // 2in Python?-4: floor division rounds down, towards minus infinity, not towards 0. - What is
-123 % 10in Python?7: the result of%has the sign of the right operand, so that(a // b) * b + a % b == aalways holds. - Why does
int(str(-123)[::-1])crash? The reversed string is"321-", andint()can't parse it. - Can reversing a number overflow in Python? No: Python ints have arbitrary precision. In C/Java/JS it can, so state the limit if the problem gives one.
- Is -121 a palindrome number? No: reversed it reads
121-. - Why does
0 + "1"fail in Python?TypeError: Python doesn't mixintandstrwith+. Convert withint()first. - What is the time complexity of digit problems? O(d), one step per digit, which is O(log n). Space O(1).
- How else can you get both quotient and remainder?
divmod(n, 10)returns(n // 10, n % 10).
Glossary
| Term | Meaning | Example |
|---|---|---|
| Digit | One of the symbols 0 to 9 in a number | 1234 has digits 1, 2, 3, 4 |
Remainder operator % (modulo) |
What is left after dividing; in Python it takes the sign of the right side | 1234 % 10 is 4, -123 % 10 is 7 |
True division / |
Division that always returns a float | 123 / 10 is 12.3 |
Floor division // |
Division rounded down to a whole number | 123 // 10 is 12, -123 // 10 is -13 |
| Float | A number with a decimal point | 12.3, 3.0 |
inf |
Infinity: a float too big to hold | 1e308 * 10 |
divmod(a, b) |
Returns (a // b, a % b) |
divmod(1234, 10) → (123, 4) |
abs(x) |
Absolute value: the number without its sign | abs(-123) → 123 |
| Absolute value | The size of a number, ignoring the sign | |-123| = 123 |
Slice [::-1] |
A copy of a sequence, backwards | "123"[::-1] → "321" |
int(s) |
Converts a string to an integer | int("0021") → 21, int("321-") → ValueError |
ValueError |
Raised when a value has the right type but a bad content | int("-") |
TypeError |
Raised when an operation gets the wrong type | 0 + "1" |
| Arbitrary precision | Integers of any size, limited only by memory | a 29-digit number reverses exactly |
| Palindrome | Reads the same forwards and backwards | 121, 1221, madam |
| Reverse of a number | The digits in the opposite order | 1200 → 21 |
| Standard input (stdin) | The input stream a program reads; in the compiler, the input box | for line in sys.stdin: |
str.strip() |
Removes spaces and newlines from both ends | "123\n".strip() → "123" |
str.lstrip("-") |
Removes leading - characters |
"-123".lstrip("-") → "123" |
| Augmented assignment | Short form that updates a variable | n //= 10 is n = n // 10 |
| Falsy | A value that counts as False in a condition | 0, "", [] |
| Edge case | An input at the boundary that often breaks code | 0, one digit, negatives, trailing zeros |
| Time complexity | How the number of steps grows with the input size | O(d) |
| Space complexity | How the extra memory grows with the input size | O(1) |
| Big-O notation | A way to write complexity, keeping only how it grows | O(1), O(d), O(n) |
| O(1) | Constant: the same amount however big the input | three variables |
| O(d) | Grows with the number of digits d | one loop turn per digit |
| O(log n) | Grows with the logarithm of n; for digits, d ≈ log₁₀ n | 1,000,000 has 7 digits |
| Logarithm (log₁₀ n) | How many times you can divide n by 10 before reaching 1 | log₁₀ 1000 = 3 |
Summary
n % 10is the last digit;n // 10drops it. Loop until the number is 0.- In Python 3,
/always gives a float: plainn / 10in the loop ends ininf. - The string trick crashes on
-123('321-') because the-gets reversed too. //rounds down:-123 // 10is-13and-123 % 10is7. Work onabs(n)and keep the sign.- Python ints never overflow: huge numbers reverse exactly.
- Palindrome: save
originalbefore the loop that destroysn; negatives are never palindromes. - Input is always a string: convert with
int()before adding;int("-")fails, so convert the whole line. - Counting digits: start at 1, so 0 has one digit.
- All three questions: O(d) time, O(1) space.
Next episode: Number questions II: prime check (why up to √n), the Sieve of Eratosthenes, Armstrong numbers.