Module 1 · Foundations of Programming ⏱ 19 min

Taking User Input

By the end of this lesson you will be able to:
  • Describe how input() reads a line of typing and returns it to the program
  • Explain that input() always returns a string, even when the user types a number
  • Convert that string with int() or float() so it can be used in math
  • Recognise ValueError and write basic defensive checks

So far your programs have been monologues — they run, they print, they finish. A useful program is a conversation: it asks a question, the user answers, and the program responds. In Python that conversation starts with input(). It is the first tool that lets your code react to a real person rather than hard-coded data.

But input() comes with a catch that breaks nearly every beginner's program at least once. The value it returns is always text, even when the user types a number. Learning to convert that text into the right type — and to handle the errors when conversion fails — is the skill that turns a static script into an interactive tool.

flowchart LR
  P["input('Your name: ')"] --> W["waits for the user to type"]
  W --> R["returns the text as a string"]
  style P fill:#3776ab,color:#fff
input() shows a prompt, waits for one line of typing, and returns that text as a string.

input(prompt) does three things in order: it prints the prompt string to the screen, it pauses and waits for the user to type a line and press Enter, and it returns everything they typed as a string. That string includes the text exactly as entered — no automatic conversion, no trimming of spaces, no special handling for numbers.

The prompt argument is optional but omitting it is rude. A bare input() gives the user no clue what you are waiting for, so they stare at a blank cursor. A clear prompt like input("Enter your birth year: ") makes the program feel professional. The prompt string is printed exactly as given, with no automatic space after it — add your own if you want one: input("Name: ") puts the cursor right after the colon.

The canonical input() pattern — shown for reference, not run, since this sandbox has no keyboard.
name = input("What's your name? ")
print("Hello, " + name + "!")

age_text = input("Your age: ")
age = int(age_text)
print("Next year you'll be", age + 1)

Because the return is always a string, you cannot do math with it directly. If the user types 42, the result is "42", the text, not 42, the integer. Adding 1 to "42" raises a TypeError, because Python refuses to mix strings and numbers. The fix is explicit conversion: wrap the result in int() or float() before you use it.

Conversion is straightforward when the text is clean. int("42") gives the integer 42; float("3.14") gives the floating-point number 3.14. You can do this in one line: age = int(input("Your age: ")). The inner input() runs first, returning a string, and int() converts it immediately.

flowchart LR
  I["input('Age: ')"] --> S["'30' (str)"]
  S --> C["int() / float()"]
  C --> N["30 (int)"]
  C --> F["3.14 (float)"]
  style I fill:#3776ab,color:#fff
  style C fill:#1e293b,color:#fff
The conversion pipeline: input() gives a string, then int() or float() turns it into a number.
The same idea, runnable here: we hard-code the text input() would have returned, then convert it.
# In a real program: age_text = input("Your age: ")
age_text = "30"          # what input() would have returned
age = int(age_text)       # now it's a real integer
print("Next year you'll be", age + 1)

# In a real program: price_text = input("Price: ")
price_text = "19.99"
price = float(price_text)
print(f"With 8% tax: ${price * 1.08:.2f}")

But conversion can fail. int("hello") raises a ValueError, because "hello" is not a valid integer. In a real program you would wrap this in a try block to catch the error and ask again. For now, the important habit is simply to remember: read with input(), convert with int() or float(), and only then do math.

A common beginner pattern is to convert first and ask questions later. But defensive programming means checking before you convert, or catching the error when conversion fails. text.isdigit() checks whether every character is a digit — useful for simple validation, though it fails on negative numbers and decimals because the - and . characters are not digits.

flowchart LR
  U["user types 'abc'"] --> T["int('abc')"]
  T --> E["ValueError"]
  T -.->|"safe path"| V["check .isdigit() first"]
  style T fill:#3776ab,color:#fff
  style E fill:#b45309,color:#fff
Conversion can raise ValueError; checking first or using try keeps the program from crashing.

The difference between int() and float() matters more than it seems. int("3.14") raises a ValueError — Python will not silently drop the decimal for you. If you need an integer from text that might contain a decimal, convert to float() first, then truncate: int(float("3.14")) gives 3. This two-step dance is common when reading numeric data from files or user input where you are not sure whether the value is whole or fractional.

For numbers that might include a decimal point, float() is more forgiving than int() — it accepts "3.14" and "2" alike. But it still rejects "abc". The general rule is: use int() when you need a whole number, float() when you need decimals, and always be ready for the user to type something unexpected.

Practising conversion with simulated inputs — the same logic you'd use with real input().
# Simulating user input with hard-coded strings
birth_year_text = "1995"
birth_year = int(birth_year_text)
current_year = 2024
age = current_year - birth_year
print(f"You are about {age} years old.")

height_text = "1.75"
height = float(height_text)
print(f"Height in cm: {height * 100:.1f}")

# Safe conversion check
score_text = "95"
if score_text.isdigit():
    score = int(score_text)
    print(f"Valid score: {score}")
else:
    print("That is not a whole number.")
Exercise

The user types 42 in response to n = input(). What type is n?

Exercise

You write age = input('Age: ') and then print(age + 1). What happens when the user types 30?

Exercise

Write years_until_100(age_text) that converts the string to an integer and returns how many years until that person turns 100. For example, years_until_100("25") should return 75.

def years_until_100(age_text):
    # convert to int and return 100 - age
    pass
Exercise

This function is meant to double a number that arrives as text, but it produces the wrong result. Fix the conversion so it works correctly.

def double_input(number_text):
    return number_text * 2
Exercise

Write tip_amount(bill_text, percent_text) that converts both arguments to floats, calculates the tip as bill * percent / 100, and returns it rounded to two decimal places. For example, tip_amount("100.00", "15") should return 15.0.

def tip_amount(bill_text, percent_text):
    # convert, calculate tip, round to 2 decimals
    pass

Recap

  • input(prompt) displays text, waits for the user, and returns their typing as a string.
  • Always convert with int() or float() before doing math.
  • int() requires whole numbers; float() handles decimals.
  • Conversion can raise ValueError when the text is not a valid number.
  • Check with .isdigit() for simple cases, or use try to catch bad input gracefully.

Next you will store values in named variables and discover the types that Python uses behind the scenes.

Checkpoint quiz

What does input("Name: ") do?

After n = input() returns the text "7", how do you turn it into an integer you can do math with?

Go deeper — technical resources