Home Blogs All Courses
python c OA ( Online Assessment ) Amazon Web Services (AWS) leetcode dsa algorithms java Machine learning
Get Referral
Login Sign Up

python › Python Input Function

Python input() Function: Taking User Input with Examples

phoolchandra  ·  Oct 23, 2026  · Published


A program that only prints is like a teacher who never listens. The input() function lets your program listen to the user — take their name, marks, age or choice, and respond. In this blog you will master input(), understand why it always returns a string, convert input into numbers, take multiple values in one line, and handle wrong input safely.

Watch the video first, then use this blog as your notes. Every section has runnable examples, and at the end you will find a "Predict the Output" quiz, practice challenges, a self-check list, interview questions and a quick summary.

How to use this blog: Open the Python shell (type python in your terminal) or any online Python editor and type every example yourself. Change the values, break the code and see what happens — that is how concepts really stick.

1. What is the input() Function?

input() is a built-in function that pauses the program, waits for the user to type something and press Enter, and then returns what was typed.

name = input("Enter your name: ")
print("Hello,", name)
Enter your name: Riya
Hello, Riya

Syntax

variable = input(prompt)
PartMeaning
promptOptional message shown to the user (e.g. "Enter your age: ")
Return valueWhatever the user typed, always as a string (str)
Enter keyEnds the input; the newline itself is not included

Tip: Add a space or : at the end of your prompt. input("Name:") makes the cursor touch the text; input("Name: ") looks much cleaner.

2. The Golden Rule: input() Always Returns a String

This is the #1 source of beginner bugs. Even if the user types a number, Python gives you text.

a = input("First number: ")    # user types 5
b = input("Second number: ")   # user types 3
print(a + b)                   # 53   <-- strings are joined, not added!
print(type(a))                 # <class 'str'>

Fix: convert (type cast) the input using int() or float().

a = int(input("First number: "))    # 5
b = int(input("Second number: "))   # 3
print(a + b)                        # 8

3. Type Conversion Cheat Table

FunctionConverts input toExample inputResult
int(input())Integer2525
float(input())Decimal number9.59.5
str(input())String (already a string!)hi'hi'
input().split()List of stringsa b c['a', 'b', 'c']
list(map(int, input().split()))List of integers10 20 30[10, 20, 30]
price = float(input("Enter price: "))   # 49.99
qty = int(input("Enter quantity: "))    # 3
print("Total =", price * qty)           # Total = 149.97

4. Taking Multiple Inputs in One Line

Competitive programming and coding tests often give several values on one line. Use split().

# user types: Riya 17
name, age = input("Enter name and age: ").split()
print(name, "is", age)          # Riya is 17

# user types: 4 5
a, b = map(int, input("Enter two numbers: ").split())
print("Product:", a * b)        # Product: 20

# user types: 10 20 30
marks = list(map(int, input("Enter marks: ").split()))
print(marks)                    # [10, 20, 30]
print("Average:", sum(marks) / len(marks))   # Average: 20.0

# comma separated input, user types: 3,6,9
nums = list(map(int, input("Numbers: ").split(",")))
print(nums)                     # [3, 6, 9]

How map() works here: input().split() gives ['4', '5']. map(int, ...) applies int to every item, and unpacking gives a = 4, b = 5.

5. Handling Wrong Input Safely

If the user types abc when you expect a number, int() crashes with a ValueError. Professional programs handle this.

age = int(input("Enter age: "))   # user types: abc
# ValueError: invalid literal for int() with base 10: 'abc'

Solution 1 — try / except

try:
    age = int(input("Enter age: "))
    print("Next year you will be", age + 1)
except ValueError:
    print("Please enter a valid number!")

Solution 2 — keep asking until valid

while True:
    value = input("Enter a positive number: ")
    if value.isdigit():
        number = int(value)
        break
    print("Invalid input, try again.")

print("You entered", number)

Clean the input with strip(), lower()

answer = input("Continue? (yes/no): ").strip().lower()
# "  YES " becomes "yes"
if answer == "yes":
    print("Continuing...")

Gotchas: int("3.5") fails — use int(float("3.5")) to get 3. And int(" 7 ") works, because int() ignores surrounding spaces.

6. Security Warning: Never Use eval(input())

You may see tutorials using eval(input()) to "automatically" convert input. Avoid it — eval executes whatever the user types as Python code, which can be dangerous. Use int(), float() or ast.literal_eval() instead.

7. Python 2 vs Python 3

Python 2Python 3
raw_input() returned a stringinput() returns a string
input() evaluated the text as code (unsafe)Removed — the old behaviour no longer exists

8. Mini Project: Student Report Card

name = input("Student name: ")
maths = float(input("Maths marks: "))
physics = float(input("Physics marks: "))
chemistry = float(input("Chemistry marks: "))

total = maths + physics + chemistry
percentage = total / 3

print("-" * 30)
print(f"Name       : {name}")
print(f"Total      : {total:.0f} / 300")
print(f"Percentage : {percentage:.2f}%")
print("-" * 30)
Student name: Aman
Maths marks: 92
Physics marks: 85
Chemistry marks: 88
------------------------------
Name       : Aman
Total      : 265 / 300
Percentage : 88.33%
------------------------------

Try it yourself: Extend the report card to print a grade: A for 90%+, B for 75%+, C otherwise. (You will learn if/elif/else in a later lesson!)

Quiz: Predict the Output

Don't run the code yet! Write your answers in a notebook, then check the Answers section at the end of this blog.

Q1. The user types 5 and then 3. What is printed?

a = input()
b = input()
print(a + b)

Q2. The user types 10. What is printed?

x = input()
print(x * 2)

Q3. The user types 10. What is printed?

x = int(input())
print(x * 2)

Q4. The user types 4 5. What is printed?

a, b = map(int, input().split())
print(a * b)

Q5. The user types 3.5. What happens?

n = int(input())

Q6. The user types 7. What is printed?

print(type(input()))

Q7. The user types Riya 17 20. What happens?

name, age = input().split()

Practice Challenges

Solve these from easy to tricky:

  1. Ask the user for their name and city, and print: Riya from Lucknow is learning Python!
  2. Take two numbers and print their sum, difference, product and quotient.
  3. Take the radius of a circle and print its area rounded to 2 decimals. (Hint: 3.14159 * r ** 2)
  4. Take temperature in Celsius and print it in Fahrenheit.
  5. Take 5 numbers in one line and print the largest and the smallest.
  6. Keep asking the user for their age until they enter a valid whole number.

Solutions for challenges 2, 3 and 5 are in the Answers section.

Self-Check: Can You Do This?

Tick off each skill once you are confident:

Frequently Asked Interview Questions

Q: What does input() return?
Always a string (str), regardless of what the user types.

Q: How do you take integer input in Python?
n = int(input())

Q: How do you take multiple integers in one line?
a, b = map(int, input().split()) or list(map(int, input().split())).

Q: What is the difference between input() in Python 2 and 3?
Python 3's input() is the same as Python 2's raw_input() — it returns a string. Python 2's input() evaluated the text as code.

Q: How do you read input faster in competitive programming?
Use sys.stdin.readline(), which is faster than input() for large inputs (remember to strip the newline).

Summary

  • input(prompt) pauses the program and returns what the user typed.
  • It always returns a string — convert with int() or float().
  • Use split() and map() for multiple values on one line.
  • Wrap conversions in try / except ValueError to handle bad input.
  • Clean input with strip() and lower().
  • Never use eval(input()).

Quick Revision Cheat Sheet

ConceptSyntax / Key point
Text inputname = input("Name: ")
Integer inputn = int(input())
Float inputx = float(input())
Two integersa, b = map(int, input().split())
List of intslist(map(int, input().split()))
Safe conversiontry: ... except ValueError:

Answers

Quiz answers

  1. 53 – both are strings, so they are joined.
  2. 1010 – string repetition.
  3. 20
  4. 20
  5. ValueError – int() cannot convert "3.5" directly. Use int(float(...)).
  6. <class 'str'>
  7. ValueError: too many values to unpack – three values but only two variables.

Challenge solutions

# Challenge 2
a = float(input("First number: "))
b = float(input("Second number: "))
print("Sum:", a + b)
print("Difference:", a - b)
print("Product:", a * b)
print("Quotient:", a / b)

# Challenge 3
r = float(input("Radius: "))
area = 3.14159 * r ** 2
print(f"Area = {area:.2f}")

# Challenge 5  (input: 4 9 1 7 3)
nums = list(map(int, input("Enter 5 numbers: ").split()))
print("Largest:", max(nums))    # 9
print("Smallest:", min(nums))   # 1

Conclusion

With print() and input() your programs can now talk and listen. Next, learn about Python data types to understand exactly what kind of values you are working with.

If this blog helped you, watch the full video above, subscribe to the channel and share it with a friend who is learning Python. Happy coding!