0
0
PythonHow-ToBeginner · 3 min read

How to Take Input from User in Python: Simple Guide

In Python, you can take input from the user using the input() function. It reads a line from the user and returns it as a string. To use the input as a number, convert it with int() or float().
📐

Syntax

The basic syntax to take input from the user is using the input() function. You can optionally pass a prompt string to show a message to the user.

  • input(): Waits for user input and returns it as a string.
  • input(prompt): Displays the prompt message before waiting for input.
python
user_input = input("Enter something: ")
💻

Example

This example asks the user to enter their name and age, then prints a greeting message. It also converts the age input from string to integer.

python
name = input("What is your name? ")
age = int(input("How old are you? "))
print(f"Hello, {name}! You are {age} years old.")
Output
What is your name? Alice How old are you? 30 Hello, Alice! You are 30 years old.
⚠️

Common Pitfalls

One common mistake is forgetting that input() always returns a string. If you need a number, you must convert it explicitly. Another issue is not handling invalid input, which can cause errors.

Example of wrong and right ways:

python
# Wrong way (causes error if input is not a number)
age = input("Enter your age: ")
print(age + 5)  # This will cause an error because age is a string

# Right way
age = int(input("Enter your age: "))
print(age + 5)  # This works because age is converted to int
📊

Quick Reference

Remember these tips when taking input:

  • input() returns a string.
  • Use int() or float() to convert input to numbers.
  • Always validate user input to avoid errors.
  • Use prompt messages to guide the user.

Key Takeaways

Use input() to get user input as a string in Python.
Convert input to numbers with int() or float() when needed.
Always provide a prompt message inside input() to guide the user.
Handle invalid input carefully to avoid runtime errors.
Remember that input() never returns numbers directly.