0%

Talking with Your Program

When Conversion Fails

Conversion only works when the text has the expected shape.

The playground contains:

age_text = input("Enter a whole-number age: ")
age = int(age_text)
print(f"Python stored {age} as an integer.")

Press Run, enter the word ten, and press Enter.

Python will report an error similar to:

ValueError: invalid literal for int() with base 10: 'ten'

Nothing is wrong with input(). It successfully returned the "ten". The error occurs on the next line because int() cannot turn that word into an integer.

The error tells you which assumption failed

The program assumes that the answer contains a whole number. The person entered something else.

This is different from a . Python understood the code. It encountered a that the conversion could not use while the program was running.

often means: “This type of conversion is possible, but this particular value is not suitable.”

Try a suitable value

Run the program again. This time, enter 10.

The conversion succeeds and the program prints:

Python stored 10 as an integer.

Also try 10.5. It is a valid decimal number, but it is not written as a whole integer, so int("10.5") reports a ValueError. float("10.5") would accept it.

Why does int("ten") report a ValueError?

What programs do about unexpected input

Real programs should often detect an unsuitable answer and ask again or show a friendly message. Doing that well requires decisions and repetition, which you will learn in later chapters.

For now:

  • write prompts that make the expected answer clear;

  • use int() only when you expect a whole number;

  • use float() when decimals should be allowed;

  • read a ValueError as information about the value being converted.

Creating this error deliberately gives you a useful reference for the next time you meet it unexpectedly.

Task

Run the program with ten, then with 10, and compare the results. Complete the quiz once you can explain why one converts and the other does not.