← Back

Home β€Ί Problems β€Ί Converting text that isn't a number

Converting text that isn't a number

πŸ› Fix the bug Topic: functions Difficulty: easy Free

What this problem practises

Function bugs are mostly about names and values: positional argument order, default parameters evaluated once at definition time, local versus global scope, and the implicit None returned whenever a function has no return.

This is a fix-the-bug problem: a short program is given in its broken state, and the task is to repair the code so it produces the required output. The interactive editor runs your fixed version in the browser and checks it for you β€” no setup, no local interpreter.

Difficulty: easy β€” the fix or the trick is normally a single line, and a careful read should be enough.

The challenge

This should convert user input to a number and double it, but crashes. Fix it.

The code runs in PyDebug’s in-browser compiler. Open the problem, run the snippet, watch the exact error or output, and keep iterating until it is right. Signed-in solves count toward XP and your daily streak.

The error it raises

Run the broken snippet and Python stops with this exact error: ValueError: invalid literal for int() with base 10: 'twenty'. Match it to the Python errors guide, then repair the line that produced it β€” knowing the message is half the fix.

The snippet

The interactive editor pre-fills exactly this code, broken and ready to repair:

age_text = "twenty"
age = int(age_text)
print(age * 2)

Understand the rule

int() and float() can convert text only when the text represents a valid number in the requested format. A value such as 'twenty' or an empty string is not a numeric literal, so Python raises ValueError instead of guessing what the user meant.

How to trace it

  1. Inspect the raw string before converting it; input often contains spaces or a word instead of digits.
  2. Choose int for whole numbers and float for decimal values.
  3. Strip harmless surrounding whitespace, but do not silently rewrite arbitrary text.
  4. Validate or handle ValueError at the boundary where user input enters the program.

Common wrong fixes

Rule to remember

Conversion answers whether text has a numeric shape; validation answers whether that number is acceptable for your application. Keep those two checks separate.

Solve it in the interactive editor β†’

πŸ”’ Learning path: Variables and Data Types

Problem 4 of 13 in this path. Work them in order β€” each one builds on the rule before it.

← Previous problemNext in path: Converting invalid text to a number β†’

More functions problems

Keep going