FULL PYTHON FIX · 5 MIN READ

Why Does input() Cause a TypeError When Adding a Number?

The characters a person types look like a number, but input() returns a string. Find the mismatched types, convert deliberately, and handle text that cannot be converted.

Video guide: Why Does input() Cause a TypeError When Adding a Number?

The preview is stored on this site. YouTube loads only when you press Play. Watch on YouTube

Read the video transcript

Select a timestamp to watch that moment on YouTube.

  1. 00:00

    Suppose a program asks for an age. You type twenty, press Enter, and expect the next age to be twenty-one. Here is the entire program: assign the result of input to age, then print age plus one. It looks reasonable because the person did enter a number. Pause for a moment and predict what the terminal will display. The important question is not what the characters look like to a human; it is what kind of value Python has stored. In this episode we will run the failing version, read the traceback, inspect the value, convert it deliberately, and then test an input that cannot be converted. You can use the same method whenever a value enters a program from a keyboard, a file, or an external service.

  2. 00:46

    First observe the actual behavior; then change one thing and rerun. That is much faster than guessing at several fixes at once. The visible characters can fool us: twenty typed on a keyboard and twenty written as an integer literal have different types. You can prove that distinction with type before trying to repair any arithmetic expression. Let us execute the original two lines with twenty as the input. The terminal stops at the plus operation and reports a TypeError. On current Python versions the message says that a string can only be concatenated with another string, not an integer. The exact wording may differ by version, but the conflicting types are the clue.

  3. 01:29

    The traceback points to print age plus one, not to the input call itself. Input completed successfully; it returned a value, and the assignment stored that value in age. The failure happens only when Python tries to evaluate the expression for print. If you see a similar traceback in your own program, locate the line named after the word File, then look closely at the values on each side of the operator. Here, the left side is age and the right side is the integer one. We need evidence about age before we choose a correction. When reading the traceback, start at the final exception line, then inspect the file and line above it.

  4. 02:09

    The error message describes the operation Python rejected; it does not necessarily tell you where the wrong value first entered the program. Add a diagnostic print immediately before the failing expression. Print the representation of age and the name of its type. With the same keyboard input, Python shows the quoted representation of twenty and the type name str. Those quotation marks are a sign that the stored value is text. The input function always gives us a string, even when the user types characters that resemble a whole number. By contrast, the literal one in our code is an int.

  5. 02:49

    Adding two integers performs arithmetic. Adding two strings joins text. Mixing a string and an integer in this expression is neither of those operations, so Python refuses it. Do not solve this by wrapping the one in str if your intention is to calculate the next age. That would join characters and produce two-zero-one, rather than twenty-one. Also avoid hiding this specific failure behind a broad exception handler. We know the cause: the value must be converted before arithmetic, and the conversion itself needs a clear response when the user enters something else. Try printing type of the literal one as well.

  6. 03:30

    It reports int, which makes the mismatch visible without relying on memory. If a value came from a CSV file, a web form, or an environment variable, make the same check at that boundary. Change only the assignment. Call int on the string returned by input, then store that integer in age. Run the file again and enter twenty. This time the terminal prints twenty-one. Conversion happens before the plus operation, so both operands are integers when Python evaluates the expression. You can make the intent more readable in a user-facing program by writing a prompt such as enter your age, and by storing the raw text separately before converting it.

  7. 04:13

    The two-line form is useful for isolating the bug, but the expanded form makes debugging easier because you can inspect the raw text. Notice that print does not return a number for further calculation; it only displays the result. If later code needs the next age, assign age plus one to a variable first. The small correction is now verified for valid whole-number input, but one successful example does not define what happens for every possible input. Converting at the input boundary gives the rest of the program a clear contract: age is an integer after that line succeeds. If other functions need age, pass that integer to them instead of asking every function to parse the original text again.

  8. 04:59

    Now test the word twenty instead of the digits. The int function cannot parse that text, so it raises a ValueError. That is a different error from the first TypeError. We can catch ValueError around the conversion and display a useful message: enter a whole number. Keep the exception handler narrow so it does not silently conceal unrelated programming mistakes. A production form might ask again in a loop, but this short example makes the boundary visible: keyboard text enters, conversion either succeeds or tells the user what format is needed. Try a negative age and decide whether your program should reject it; int accepts a minus sign, while the rules of your application may not.

  9. 05:44

    Then try a blank line and a decimal such as twenty point five. Predict which strings int can parse before you run them. Finally, write a tiny program that asks for a quantity, adds one, and prints the new quantity. Make it handle an invalid response without crashing. The related Input and Output lesson on PythonLessonLab lets you run the code and practice the same distinction in the browser. A blank response, a decimal, and a word are different test cases even though all three fail an integer conversion. Decide which formats your application accepts, and report the expected format to the user instead of exposing a raw traceback.

Make the error happen

Imagine asking a user for their age and displaying their age next year. Entering 20 feels like it should make age + 1 equal 21. Run the program below, type 20, and read the final line of the traceback.

The error is at the addition, not at the prompt. Python received the characters 2 and 0 as text. The + operator can join two strings or add two numbers, but it cannot infer which operation you intended when given a string and an integer.

Broken program — enter 20 at the prompt
PYTHON
age = input('Age: ')
print(age + 1)
ERROR (LAST LINE)
TypeError: can only concatenate str (not "int") to str

Inspect the values before changing the code

When a traceback mentions types, print the type of each value beside the failing expression. Here, age is str even though its visible contents are 20. The literal 1 is int. That observation explains the exact mismatch without guessing.

A numeric-looking string is still a string: '20' + '1' would produce '201', which is concatenation rather than arithmetic. Converting 1 to text would silence this error but give the wrong answer for an age calculation. Choose the type that matches the operation you actually need.

Diagnostic run — enter 20
PYTHON
age = input('Age: ')
print(repr(age), type(age).__name__)
print(repr(1), type(1).__name__)
OUTPUT
Age: 20
'20' str
1 int

Convert numeric text before arithmetic

For a whole-number age, int(age) converts the text to an integer. Keep the raw text separate from the converted value while learning; the names make the transition visible and make debugging easier. Then perform arithmetic on integers and format the result for display.

Use float() when fractional numbers are actually expected, such as 2.5 hours. Do not convert every input automatically: a name, email address, or postal code may look numeric but should remain text. Conversion belongs at the point where your program needs a number.

Correct program — enter 20
PYTHON
raw_age = input('Age: ')
age = int(raw_age)
print(f'Next year: {age + 1}')
OUTPUT
Age: 20
Next year: 21

Test valid and invalid input

One successful input is not enough. int() raises ValueError if the text does not represent an integer. Catch that specific exception and give the user a useful message. Avoid a broad except clause here; it could hide an unrelated bug in the program.

Try 20, then try twenty, an empty line, and a negative value. Whether a negative age is allowed is a separate validation rule: int() checks syntax, not your application's meaning. Add an age >= 0 check if your application requires it.

Guard conversion — enter twenty
PYTHON
raw_age = input('Age: ')
try:
    age = int(raw_age)
except ValueError:
    print('Please enter a whole number.')
else:
    print(f'Next year: {age + 1}')
OUTPUT
Age: twenty
Please enter a whole number.
  • 20 should print Next year: 21.
  • twenty should print the helpful error message.
  • 20.5 should also be rejected by int(); choose float() only if decimals are part of the requirement.

Practice the fix

Ask for the number of tickets, then print how many tickets there will be after buying two more. Test 3 and three. Keep the raw input and converted integer in different variables, and catch ValueError for the text case.

Need a hint?

Start with raw = input('Tickets: '), then use int(raw) inside try. Put the calculation in else so it only runs when conversion succeeds.

Python console

Ready to run

Edit and run the code here. Input lines are supplied without echoing typed characters, so prompts may look shorter than the terminal examples above.

Does your code use input()? Add one value per line
Ctrl / ⌘ + Enter to run
OUTPUT
Your output appears here.

Key takeaways

  • input() always returns str, even when the user types digits.
  • Inspect types at the failing expression before applying a fix.
  • Use int() or float() for arithmetic, according to the data you expect.
  • Catch ValueError from conversion and validate application-specific rules separately.

Related lessons

Sources and further reading