Skip to content

Module 2 · Python Syntax and Fundamentals — topic 12 of 14

input()

How input() reads a line from the keyboard, why it always returns a string, how to clean and convert the result, and how to handle empty or unexpected input.

Beginner 12 min read·Lesson 26 of 306 in Python Programming

Learning objectives

  • Read user input with a prompt
  • Clean input with strip() and convert it
  • Handle empty input gracefully

Definition

How input() reads a line from the keyboard, why it always returns a string, how to clean and convert the result, and how to handle empty or unexpected input.

Introduction

input() pauses the program, shows a prompt, and waits until the user types something and presses Enter. Whatever they typed comes back as a string, without the Enter key itself.

Why it matters

Real users type extra spaces, capital letters, nothing at all, or text where you expected a number. Learning to read, clean and check input from the start makes your programs feel solid instead of crashing on the first unexpected key press.

Detailed explanation

input(prompt) prints the prompt without a newline, so add a trailing space to separate it from the typing.

The return value is always a str, even if the user types digits. Convert with int(), float() or other functions when you need a number.

strip() removes spaces from both ends; lower() makes comparisons case-insensitive.

If the user just presses Enter, input() returns an empty string "", which is falsy, so if not answer: detects it.

Converting invalid text such as "abc" with int() raises ValueError. You will learn to catch it with try/except in Module 12; for now, check with methods such as isdigit().

Each call to input() reads exactly one line. To collect several values, either call input() several times with a clear prompt each time, or ask for them on one line and split the answer, for example input("Enter two numbers: ").split() returns a list of the separate words.

When a program is run with input redirected from a file instead of a keyboard, input() reads from that file line by line. This is how the examples in these lessons are checked automatically, and it is a handy way to test your own programs without typing the same answers again and again.

Syntax

Python
answer = input("Your prompt: ").strip()
  • The prompt ends with a space.
  • .strip() is called on the returned string straight away.
  • answer is always a string.

Code examples

Cleaning input

Python
city = input("City: ").strip().title()
print(f"[{city}]")
Input
   new delhi  
Output
City: [New Delhi]

Case-insensitive answers

Python
reply = input("Continue? (yes/no) ").strip().lower()
print(reply == "yes")
Input
YES
Output
Continue? (yes/no) True

More examples

Checking before converting

Python
raw = input("How many tickets? ").strip()
if not raw:
print("You didn't enter anything.")
elif not raw.isdigit():
print(f"'{raw}' is not a whole number.")
else:
tickets = int(raw)
print(f"Booking {tickets} ticket(s), total Rs {tickets * 180}")
Input
3
Output
How many tickets? Booking 3 ticket(s), total Rs 540

Step-by-step explanation

  • strip() removes accidental spaces before checking.
  • if not raw catches an empty answer.
  • isdigit() is True only if every character is a digit, so int() is safe in the else branch.
  • The final line multiplies by the ticket price of 180.

Expected output

Running “Checking before converting” with the sample input shown prints exactly:

TextInput
3
TextOutput
How many tickets? Booking 3 ticket(s), total Rs 540

Practical applications

  • Command-line installers ask “Proceed (y/n)?” and accept Y, y, yes or YES.
  • Banking kiosks validate numeric input before using it.
  • Survey scripts trim spaces so “ Delhi” and “Delhi” are counted together.

Best practices

  • Strip and normalise input immediately.
  • Validate before converting.
  • Explain clearly what to type in the prompt, including units.

Common mistakes

Comparing without normalising

Avoid

if answer == "yes":

Prefer

if answer.strip().lower() == "yes":

Users may type Yes or yes with spaces; normalise before comparing.

Converting unchecked input

Avoid

n = int(input("Number: ")) # user types ten

Prefer

raw = input("Number: ")
if raw.isdigit():
n = int(raw)

int("ten") raises ValueError and stops the program.

Key takeaways

  • input() shows a prompt and returns the typed line as a string.
  • Clean input with strip() and lower().
  • Check input before converting to avoid ValueError.

Try it yourself

  1. 1
    Ask for a pin code and print whether it is exactly 6 digits.
    Show hint

    Combine len() and isdigit().

  2. 2
    Ask for a colour and print a message only if the answer is red, in any capitalisation.

Finished reading? Mark it complete to update your dashboard.

Suggested practice

1 question test this exact topic. Answers and explanations are revealed after you submit.

  • BeginnerWhat type does input() always return?
Practise this topic