Python

P
PythonHub
Progress 0%

Python

  • Home
  • History of Python
  • Applications of Python
  • Introduction To Python
    • What is Python
    • Character Set
    • Tokens in Python
    • Python Execution Mode
    • Variable And Identifiers
    • Data Types in Python
    • Operators And Expressions
    • Constants in Python
    • Assignment Statement
    • Input / Output in Python
    • Simple Python Scripts
    • Namespace in Python
    • 📝 Assignments
  • Operators in Python
    • Arithmetic Operators
    • Assignment Operators
    • Shorthand Assignment Operators
    • Relational Operators
    • Logical Operators
    • Bitwise Operators
    • Special Operators
    • 📝 Assignments
  • Input Output in Python
    • Accept Input
    • Output Formatting
    • 📝 Assignments
  • Conditional Statement
    • Decision Making
    • if Statement
    • IF-ELSE STATEMENT
    • IF-ELSE LADDER
    • NESTED IF-ELSE
    • Short Hand IF-ELSE
    • 📝 Assignments
  • Loops
    • Introduction to Loops
    • While Loop
    • Nested While Loop
    • 📝 While Loop Assignments
    • For Loop
    • For Loop Examples
    • Nested For Loop
    • Nested For Loop Examples
    • Infinite While Loops
    • Infinite For Loops
    • Break, Continue and Else in Loops
    • Difference Between For and While Loop
    • For Each Loop
    • 📝 For Each Assignments
    • 📝 All Loops Assignments
  • List
    • List in Python
    • Access List Elements
    • List Functions
    • Iterate (Loop) List
    • List Comprehension
    • 📝 Assignments
  • Tuple
    • Tuple in Python
    • Access Tuple Elements
    • Tuple Functions
    • Iterate (Loop) Tuple
    • Unpack Tuple
    • Tuple Comprehension
    • 📝 Assignments
  • Set
    • Set in Python
    • Access Set Elements
    • Set Methods
    • Iterate (Loop) Set
    • Pack/Unpack Set
    • Set Comprehension
    • 📝 Assignments
  • Dictionary
    • Dictionary
    • Access Dictionary Items
    • Dictionary Methods
    • Iterate (Loop) Dictionary
    • Formatting Dictionaries
    • Nested Dictionaries
    • Dictionary Comprehension
    • 📝 Assignments
  • Diff List Tuple Set Dictionary
    • List vs Tuple
    • List vs Set
    • List vs Dictionary
    • Tuple vs Set
    • Tuple vs Dictionary
    • Dictionary vs Set
    • 📝 Assignments
  • Exception
    • Error vs Exception
    • Exception Handling
    • Types of Exception
    • User Defined Exception
    • Logging Exception
    • 📝 Assignments
  • Functions
    • Introduction to Functions
    • Modular Programming
    • Types of Functions
    • Inbuilt Functions
    • Need For User-Defined Function
    • Elements of User Defined Function
    • Function Arguments
    • Nesting of Functions
    • Recursion
    • Global Local and Non Local
    • Python Lambda Functions
    • 📝 Assignments
  • Python Module
    • Introduction to Module
    • Inbuilt Modules in Python
    • User Defined Module
    • 📝 Assignments
  • File Handling
    • Introduction to Files
    • Create File
    • Read Files
    • Write to File
    • Rename File
    • Copy File
    • Move File
    • List Files in Directory
    • Binary Files
    • Zipping and Unzipping Files
    • 📝 Assignments
  • Strings
    • Basics of Strings
    • String Special Operators
    • String Formatting Operators
    • String Methods
    • 📝 Assignments
  • Regular Expressions
  • Python OOPS
    • Basics of Object Oriented
    • What are Classes and Objects?
    • Creating Class and Object
    • OOP vs Procedural Programming
    • Difference Between Classes and Objects
    • Constructors
    • Destructor
    • Built Class Methods and Attributes
    • Class and Instance Variables
    • Inheritance in Python
    • Single Inheritance
    • Multiple Inheritance
    • Multilevel Inheritance
    • Hierarchical Inheritance
    • Hybrid Inheritance
    • Abstraction
    • Method Overriding
    • Abstract Method
    • Interfaces in Python
    • Abstract Class vs Interface
    • Public, Private and Protected
    • Overloading vs Overriding
    • Inheritance vs Composition
    • Encapsulation
    • Polymorphism
    • Inner Classes
    • 📝 Assignments
  • Advanced Python
    • Iterator in Python
    • Generator in Python
    • Decorator in Python
    • Type Hints in Python
    • Async/Await Programming
    • Dataclasses in Python
    • Context Managers in Python
    • Property Decorator in Python
    • __slots__ in Python
    • Enums in Python
    • Walrus Operator in Python
    • Match-Case in Python
    • 📝 Assignments
  • Python Standard Library
    • Collections Module
    • Itertools Module
    • Functools Module
    • Datetime Module
    • JSON Module
    • OS Module
    • Sys Module
    • Random Module
    • Math Module
    • 📝 Assignments
  • Python Testing
    • Unit Testing in Python
    • Pytest Framework
    • Mocking in Python
    • 📝 Assignments
  • Python Best Practices
    • PEP 8 Style Guide
    • Docstrings in Python
    • Logging in Python
    • Code Optimization Tips
    • Debugging Techniques
    • 📝 Assignments
  • MySQL Database in Python
    • Introduction to MySQL with Python
    • DBMS vs File System
    • Connecting to MySQL Database
    • Create Database in MySQL
    • Create Table in MySQL
    • Insert Data in MySQL
    • Insert Multiple Rows
    • Select Data from MySQL
    • WHERE Clause in MySQL
    • Update Data in MySQL
    • Delete Data from MySQL
    • Parameterized Queries
    • Transaction Management
    • Error Handling
    • Connection Pooling
    • MySQL Drivers Guide
    • Joins in MySQL
    • Aggregation Functions
    • Backup MySQL Database
    • Best Practices
    • 📝 Assignments
  • MySQL Database Operations
    • SELECT Statement
    • MySQL Operators
    • DDL Statements
    • DML Statements
    • Subqueries
    • JOIN Operations
    • Aggregation
    • Case Study
    • 📝 Assignments
  • Graphics in Python
  • Threads in Python
    • Introduction to Threads
    • Process vs Threads
    • Concurrent Programming & GIL
    • Uses of Threads
    • Creating Threads
    • Single Tasking
    • Multi Tasking
    • Thread Synchronization
    • 📝 Assignments
  • Interview Questions & Answers
  • Python Case Studies
  • Multiple Choice Questions
  • 📝 Practice Problems
Get in Touch
  • tech2dsm@gmail.com

© Sankalan Data Tech

Python Language Interactive Tutorial

⌨️ Python input() Function: Complete Guide

Python input() Function - Accept User Input

The input() function is your program's way of listening to the user — it's how your code becomes a conversation, not just a monologue.

Created by Sankalan Data Tech Team Verified
Data Engineers, Analysts, Scientists & Trainers
Created by experienced Python developers, data engineers, and data scientists to make programming easy through practical examples, real-world experience, and clear explanations.
📑 On this page:
  • What is Input in Python?
  • Syntax of input()
  • Accepting String Input
  • Accepting Integer Input
  • Accepting Float Input
  • Accepting Complex Numbers
  • Accepting Boolean Input
  • Accepting Tuple Input
  • Accepting List Input
  • Handling Multiple Inputs
  • Best Practices
  • Try It Yourself
  • Quick Quiz
  • FAQ
Share this tutorial:
Twitter LinkedIn Facebook WhatsApp Reddit Telegram Email Copy Link
📚 What You'll Learn Here
  • What input is — how programs receive data from users
  • The input() function — syntax and basic usage
  • Accepting different data types — strings, integers, floats, complex numbers, booleans
  • Accepting collections — lists, tuples, sets
  • Handling multiple inputs — using split() and map()
  • Best practices — input validation, error handling
  • Hands-on practice with the interactive editor

What is Input in Python?

Think of input as the way your Python program listens to the world around it. Every time a user types something on their keyboard, clicks a button, or even speaks into a microphone, they're providing input. In Python, the input() function is the simplest and most common way to accept input from the user.

When you call input(), your program pauses and waits for the user to type something and press Enter. Once they do, whatever they typed is returned as a string. This simple action — waiting, listening, and receiving — is what makes programs interactive and dynamic.

💡 Why does this matter? Without input, every program would be like a pre-recorded message — it says the same thing every time, no matter who's listening. With input, your program can respond differently based on what the user says. That's the beginning of true interactivity.

Here's something important to remember: input() always returns a string. Even if the user types a number, Python treats it as text until you tell it otherwise. This is why you'll often see code like int(input()) or float(input()) — it's your way of saying, "Take this text and treat it as a number."

Syntax of input()

The syntax of input() is beautifully simple. You call the function, optionally pass a message (called a prompt) that the user will see, and assign the result to a variable.

# Basic Syntax
variable = input(Message)

# Example
age = input("Enter your age: ")
print(f"You entered: {age}")

📖 Breaking it down: The Message is what your user sees — it's your program asking a question. The user types their response and hits Enter. That response is captured and stored in your variable. It's a simple exchange: your program asks, the user answers, and your program remembers.

One thing to keep in mind: the prompt is optional. If you call input() without any message, the program will simply wait for the user to type something, with no visual cue. This can be useful in some situations, but in most cases, a clear prompt makes your program easier to use.

1. Accepting String Input

The simplest use of input() is to accept text. This is also the most common, because names, addresses, emails, and countless other types of information are naturally represented as strings.

When you use input() without any type conversion, the result is a string. You can then use it with other strings, check its length, or display it back to the user.

# Accepting String Input
name = input("Enter your name: ")
print(f"Hello, {name}! Welcome to Python!")

# Output:
# Enter your name: Guido van Rossum
# Hello, Guido van Rossum! Welcome to Python!

💡 Real-world application: This is how user registration forms work. When a user signs up, the program asks for their name, stores it, and uses it to personalize the experience. It's a simple concept, but it's the foundation of every user-facing application.

2. Accepting Integer Input

Sometimes, you need numbers — not just any numbers, but whole numbers that you can do math with. This is where converting input to an integer comes in.

The int() function takes a string and converts it to an integer. But there's a catch: if the user types something that isn't a valid number (like "twenty" or "3.14"), Python will raise an error. This is why error handling is so important in real programs.

# Accepting Integer Input
age = int(input("Enter your age: "))
print(f"Next year you will be {age + 1} years old!")

# Output:
# Enter your age: 19
# Next year you will be 20 years old!

⚠️ Common pitfall: If the user enters "twenty" instead of "20", the program will crash with a ValueError. In a real application, you would use try-except to handle this gracefully. We'll cover error handling later in this tutorial.

3. Accepting Float Input

What if you need decimal numbers? Heights, weights, temperatures, prices — these are all commonly represented as floating-point numbers (floats). Python doesn't have a special function for float input, so you use float() to convert the string.

Just like with integers, if the user enters something that can't be converted to a float, Python will raise an error. This is especially common with user input, so always be prepared for unexpected input.

# Accepting Float Input
height = float(input("Enter your height in meters: "))
print(f"Your height is {height} meters")

# Output:
# Enter your height in meters: 1.75
# Your height is 1.75 meters

💡 Why use floats? Floats are essential for scientific and engineering applications. They allow you to work with precise measurements, calculate percentages, and handle any situation where whole numbers aren't enough. In many real-world applications, floats are used more often than integers.

4. Accepting Complex Numbers

If you're working in scientific computing, physics, or engineering, you might need complex numbers. Python has built-in support for complex numbers, and you can accept them as input using complex().

A complex number has a real and imaginary part, written as a + bj (where j is the imaginary unit). Python's complex() function can parse this format directly from user input.

# Accepting Complex Numbers
cmplx = complex(input("Enter a complex number: "))
print(f"The complex number is {cmplx}")

# Output:
# Enter a complex number: 11+3j
# The complex number is (11+3j)

📖 When to use complex numbers: Complex numbers are used in electrical engineering, quantum mechanics, signal processing, and many other advanced fields. If you're doing basic programming, you might never need them, but it's good to know they exist!

5. Accepting Boolean Input

Booleans (True and False) are the foundation of decision-making in programming. But accepting boolean input from users is trickier than it seems.

The bool() function converts any value to a boolean. But here's the catch: any non-empty string becomes True, and only empty strings become False. This means if the user types "False" or "0", bool() still returns True.

# Accepting Boolean Input
b = bool(input("Enter value to convert to boolean: "))
print(f"The value in boolean is: {b}")

# Output:
# Enter value to convert to boolean: 1
# The value in boolean is: True

# Enter value to convert to boolean: False
# The value in boolean is: True  (Surprise! Non-empty string = True)

⚠️ Important: If you need to accept true/false input, it's better to check the input text explicitly. For example: user_input = input("Enter True or False: ").lower(); is_true = user_input == "true". This gives you full control over the conversion.

6. Accepting Tuple Input

Sometimes you need to collect multiple values at once. Tuples are immutable sequences that are perfect for storing related pieces of data, like coordinates or multiple scores.

To accept a tuple as input, you need to split the user's input into individual values, convert each value to the desired type, and then create a tuple from them. This is a powerful technique for handling multiple inputs efficiently.

# Accepting Tuple Input
t = input("Enter numbers separated by commas: ")
t = tuple(int(x) for x in t.split(","))
print(f"The tuple is: {t}")

# Output:
# Enter numbers separated by commas: 1,2,45,67,89,23,12,50
# The tuple is: (1, 2, 45, 67, 89, 23, 12, 50)

💡 Real-world use: Tuples are great for storing fixed-length data like coordinates (x, y), RGB color values (red, green, blue), or date components (year, month, day). They're immutable, which means once you create them, they can't be changed accidentally.

7. Accepting List Input

Lists are similar to tuples but mutable — you can add, remove, and change elements. This makes them perfect for collections that might grow or change over time.

The process of accepting list input is very similar to tuples, but you create a list instead of a tuple. The map() function is a cleaner way to convert each element.

# Accepting List Input
lst = input("Enter numbers separated by spaces: ")
lst = list(map(int, lst.split()))
print(f"The list is: {lst}")

# Output:
# Enter numbers separated by spaces: 10 20 30 40 50
# The list is: [10, 20, 30, 40, 50]

💡 When to use lists: Lists are perfect for shopping carts, to-do lists, or any collection that needs to be modified. Unlike tuples, you can add items, remove items, or sort the list — making lists one of the most versatile data structures in Python.

8. Handling Multiple Inputs

One of the most elegant features of Python is its ability to handle multiple inputs in a single line. This is done using the split() method, which splits a string into a list based on a separator (space by default).

Combined with map(), you can convert multiple values at once. This is especially useful when you want the user to enter several values without being interrupted by multiple prompts.

# Handling Multiple Inputs
x, y = input("Enter two numbers: ").split()
x = int(x)
y = int(y)
print(f"Sum: {x + y}")

# Using map for cleaner code
a, b, c = map(int, input("Enter three numbers: ").split())
print(f"Product: {a * b * c}")

# Output:
# Enter two numbers: 10 20
# Sum: 30
# Enter three numbers: 2 3 4
# Product: 24

📖 How it works: input().split() turns "10 20" into ["10", "20"], and map(int, ...) converts each string to an integer. It's a beautiful, concise way to handle multiple inputs — one of Python's signature features.

9. Best Practices for Using input()

The input() function seems simple, but there's a lot you can do to make your programs more robust, user-friendly, and professional. Here are some best practices that will help you write better code.

✅ Always Provide Clear Prompts

Imagine using a program that just stops and waits, without telling you why. That's frustrating! A clear prompt tells the user exactly what to do. It's good user experience and reduces the chance of errors.

# GOOD: Clear, descriptive prompt
age = int(input("Enter your age (18-65): "))

# BAD: Vague prompt
age = int(input("Enter: "))

✅ Handle Input Errors Gracefully

Users will make mistakes — it's part of being human. A well-designed program doesn't crash when a user types "twenty" instead of "20". It catches the error, explains the issue, and gives the user another chance.

# Error Handling Example
try:
    age = int(input("Enter your age: "))
    print(f"You are {age} years old")
except ValueError:
    print("Please enter a valid number!")

✅ Strip Whitespace from Input

Users often accidentally include extra spaces at the beginning or end of their input. Using strip() removes these spaces automatically, making your program more forgiving and user-friendly.

# Remove extra spaces
name = input("Enter your name: ").strip()
print(f"Hello, {name}!")

✅ Use Loops for Retry Logic

One of the most professional things you can do is give users multiple chances to enter valid input. A simple while loop can keep asking until the user gets it right.

# Retry logic with while loop
while True:
    try:
        age = int(input("Enter your age: "))
        break
    except ValueError:
        print("Please enter a valid number!")
print(f"Your age is {age}")

Try It Yourself!

The best way to learn is by doing. Experiment with the input() function directly in your browser. Modify the code, try different inputs, and see how Python responds. Don't be afraid to break things — that's how you learn!

Loading Pyodide... 0%
Python Code Editor
========================================
INPUT() FUNCTION
========================================

1. STRING INPUT
Enter your name: (user types: Alice)
Hello, Alice!

2. INTEGER INPUT
Enter your age: 25
Next year you'll be 26

3. FLOAT INPUT
Enter your height (m): 1.75
Your height is 1.75m

4. MULTIPLE INPUTS
Enter two numbers: 10 20
Sum: 30

5. TUPLE INPUT
Enter numbers separated by commas: 1,2,3,4
Tuple: (1, 2, 3, 4)

✅ Explore different input types!
🏆

🎉 You've Mastered Python input()!

You understand how to accept user input, convert data types, and handle multiple inputs. These are essential skills for interactive Python programs!

Quick Quiz – Test Your Knowledge

1. What data type does input() always return?
2. How do you convert input to an integer?
3. What function is used to accept multiple inputs in one line?
4. What happens if a user enters "25.5" and you try to convert it with int()?
5. Which method removes extra spaces from user input?

Frequently Asked Questions

🤔 What's the difference between input() and raw_input()? ▼

raw_input() was used in Python 2. In Python 3, input() does everything raw_input() did. input() in Python 2 evaluated the input as code, which was dangerous. Python 3's input() is safe and always returns a string.

🔧 How do I handle errors when converting input? ▼

Use a try-except block to catch ValueError when the user enters invalid data. This prevents your program from crashing. You can also use a while loop to keep asking until the user provides valid input.

📐 Can I accept input without showing a prompt? ▼

Yes! Simply use input() without any message: name = input(). The program will wait for input without displaying a prompt. This is useful in some situations, like when you want to keep the screen clean.

📊 How do I accept password input without showing characters? ▼

Use the getpass module: import getpass; password = getpass.getpass("Enter password: "). This hides the input on the screen, making it perfect for password prompts and sensitive information.

⚡ What is the difference between input() and sys.stdin.read()? ▼

input() reads a single line of input (until Enter is pressed). sys.stdin.read() reads everything from standard input until EOF. Use input() for interactive prompts and sys.stdin.read() for batch processing or reading files.

🎯 Can I set a timeout for input()? ▼

Python's built-in input() doesn't support timeouts directly. However, you can use the signal module or the select module on Unix systems to implement a timeout. For cross-platform solutions, consider using third-party libraries like timeout-input.

💻 Can I use input() to read from a file? ▼

Not directly! input() reads from the keyboard (standard input). To read from files, you'll use the open() function. This is covered in the File Handling section of our tutorials.

📚 Where to Go From Here

Now that you've mastered the input() function and know how to make your Python programs interactive, you're ready to explore the other side of the coin — output formatting. Here are some handpicked topics that will take your Python skills to the next level:

📤 Mastering Output with print()

You've learned how to listen to users — now it's time to speak back to them! The print() function is your program's voice. Learn how to format numbers, align text, and create professional-looking reports.

Explore Output Formatting →

📝 Practice Makes Perfect: I/O Assignments

Theory is good, but practice is what makes you a confident programmer. These hands-on assignments will challenge you to combine input and output in creative ways — from building a simple calculator to creating a personal diary app.

Start Practicing →

🚀 From Scripts to Programs: Real-World Projects

You've written small scripts — now it's time to build something bigger! Learn how to structure your code, handle errors gracefully, and create programs that people actually want to use.

Build Your First Real Scripts →
📖 Related Tutorials You'll Love
  • 📤 Output Formatting — Turn boring print() statements into beautiful, professional output
  • 📝 I/O Assignments — Practice what you've learned with real-world coding challenges
  • 🚀 Simple Python Scripts — Move beyond single-line programs and build something meaningful
  • 📋 Variables and Identifiers — Strengthen your foundation with clean, readable variable naming
📖 Interview & FAQ Resources
  • Python Syntax & Variables Interview Questions
  • SQL - Displaying Data from Multiple Tables FAQ
  • SQL Window Functions & Analytic Functions FAQ
  • Python Data Types Interview Questions
  • Python Tuples and Sets Interview Questions
  • Java Basic Input/Output Interview Questions
  • Java Advanced Threads and Concurrency Interview Questions
Previous: Assignment Statement Next: Output Formatting →