How to use raw_input() in Python
Learn to use Python's raw_input function. Explore different methods, tips, real-world applications, and how to debug common errors.
%2520in%2520Python.jpeg)
In Python, the raw_input function is a fundamental way for your programs to get user input. It captures text directly from the command line, which makes it essential for interactive scripts.
In this article, you'll learn key techniques and tips for using raw_input effectively. You will also find real-world applications and debugging advice to help you build robust, interactive programs.
Basic usage of raw_input()
name = raw_input()
print "Hello, " + name + "!"--OUTPUT--John
Hello, John!
The raw_input() function effectively pauses the program's execution, waiting for the user to type something into the console and press Enter. Whatever is entered before that keypress is then captured and assigned to the name variable.
Crucially, raw_input() always returns the user's entry as a string. This is why the name variable can be directly concatenated with "Hello, " to form the output. Even if the user enters a number, it’s treated as a string until you explicitly convert it.
Basic techniques with raw_input()
Now that you've got the basics down, you can make raw_input() more robust by adding prompts, converting input types, and providing default values.
Using prompts with raw_input()
name = raw_input("Please enter your name: ")
print "Nice to meet you, " + name + "!"--OUTPUT--Please enter your name: Maria
Nice to meet you, Maria!
You can make your programs more user-friendly by passing a string to the raw_input() function. This string acts as a prompt, displaying a message to the user right before they're expected to type. It's a simple way to guide them on what kind of information you need.
- It tells the user exactly what to enter.
- It avoids the confusion of a blank, blinking cursor, making your script more intuitive.
Type conversion with raw_input()
age_str = raw_input("Enter your age: ")
age = int(age_str)
birth_year = 2023 - age
print "You were born around", birth_year--OUTPUT--Enter your age: 25
You were born around 1998
Since raw_input() returns a string, you can't perform mathematical operations on its output directly. You need to convert the string to a numerical type first. In the example, the int() function converts the age_str variable into an integer, making it possible to calculate the birth year.
- This conversion is essential for any math operations.
- Functions like
int()andfloat()are your tools for changing the input's data type. - Failing to convert will result in a
TypeErrorwhen you try to run calculations.
Default values with raw_input()
color = raw_input("What's your favorite color? (default: blue) ") or "blue"
print "Your favorite color is", color--OUTPUT--What's your favorite color? (default: blue)
Your favorite color is blue
You can easily set a default value for when a user provides no input. This trick leverages Python's or operator. If the user simply presses Enter, raw_input() returns an empty string, which Python treats as a "falsy" value.
- The
oroperator evaluates the user's input first. If it's a non-empty string (truthy), that value is assigned to the variable. - If the input is an empty string (falsy), the expression defaults to the value on the right—in this case,
"blue".
This is a clean and Pythonic way to handle optional inputs without extra if statements.
Advanced techniques with raw_input()
With the basics of raw_input() covered, you're ready to tackle more complex scenarios like capturing multi-line text, handling passwords, and understanding its Python 3 alternative.
Multi-line input with raw_input()
print "Enter a poem (type 'END' on a new line when finished):"
lines = []
while True:
line = raw_input()
if line == "END":
break
lines.append(line)
print "\nYour poem:\n" + "\n".join(lines)--OUTPUT--Enter a poem (type 'END' on a new line when finished):
Roses are red
Violets are blue
Python is fun
And so are you
END
Your poem:
Roses are red
Violets are blue
Python is fun
And so are you
Because raw_input() only reads one line at a time, you need a loop to capture multi-line entries. The example sets up a while True loop that keeps asking for input, creating an effective way to gather text until you tell it to stop.
- Each line you enter is stored in the
lineslist. - The loop terminates when it sees a sentinel value. In this case, typing
"END"on its own line triggers thebreakstatement.
After the loop finishes, "\n".join(lines) neatly stitches all the collected lines back into a single string.
Password input with raw_input()
import getpass
password = getpass.getpass("Enter your password: ")
print "You entered a password with length:", len(password)--OUTPUT--Enter your password:
You entered a password with length: 6
Using raw_input() for passwords is a security risk because it echoes every character you type to the screen. For sensitive information, you should use Python's built-in getpass module instead. The getpass.getpass() function prompts the user for input but keeps it hidden from view, so nothing appears on the console as they type.
- This prevents "shoulder surfing"—where someone could see the password by looking at your screen.
- It’s the standard, secure way to handle sensitive text input in command-line applications.
Python 3 alternative to raw_input()
# Python 2
name = raw_input("Enter name (Python 2): ")
# Python 3 equivalent
# name = input("Enter name (Python 3): ")
print "Hello,", name--OUTPUT--Enter name (Python 2): Alex
Hello, Alex
When you move to Python 3, the function you're looking for is simply input(). The old raw_input() function was renamed, and its behavior is now the default for Python 3's input(). This change streamlined the language by getting rid of the confusing and often unsafe input() function from Python 2, which tried to evaluate user entries as code.
- In Python 3, you should use
input()for all standard user input. - It behaves identically to Python 2's
raw_input(), always returning a string, so you still need to perform type conversions for numbers.
Move faster with Replit
Replit is an AI-powered development platform that lets you go from learning techniques like raw_input() to building applications instantly. It comes with all Python dependencies pre-installed, so you can skip environment setup and focus on coding.
Instead of piecing together functions, you can use Agent 4 to build a complete product directly from a description. It handles the coding, database connections, APIs, and deployment. For example, you could describe practical tools that use the input methods from this article, such as:
- A command-line unit converter that prompts for a value and converts it, using type conversion to handle the numbers.
- An interactive journal that collects multi-line entries from the user until a stop command is entered.
- A simple profile generator that asks for a name and favorite color, using a default value if the color is left blank.
Simply describe your app, and Replit will write the code, test it, and fix issues automatically, all within your browser.
Common errors and challenges
While raw_input() is straightforward, you'll often encounter issues like type errors, invalid entries, and extra whitespace that require careful handling.
Handling type errors with raw_input()
A frequent pitfall is forgetting that raw_input() always returns a string. If you try to add two numbers using the + operator, Python will join them as text instead of performing a mathematical sum, which can cause confusing bugs.
The code below shows this common error in action.
# Bug: forgetting that raw_input() returns strings
value1 = raw_input("Enter first number: ")
value2 = raw_input("Enter second number: ")
result = value1 + value2
print "The sum is:", result
Instead of adding the numbers, the + operator concatenates the strings "10" and "20" into "1020". This happens because raw_input() returns text, not numerical values. The corrected code below shows how to handle this properly.
# Fixed: convert string inputs to numbers before operations
value1 = raw_input("Enter first number: ")
value2 = raw_input("Enter second number: ")
result = float(value1) + float(value2)
print "The sum is:", result
To fix this, you must explicitly convert the string inputs to numbers. By wrapping each variable in the float() function, you're telling Python to treat them as numerical values, not text. This ensures the + operator performs mathematical addition instead of string concatenation. Always do this when gathering numbers for calculations. Otherwise, your math will produce incorrect results like "1020" instead of 30.
Dealing with invalid input in raw_input()
Another common challenge is handling input that doesn't match what your program expects. If you try to convert a non-numeric string to an integer using int(), your script will crash with a ValueError because the conversion is impossible.
The following code demonstrates this problem. When the user enters text instead of a number, the program stops unexpectedly.
# Bug: program crashes when user enters non-numeric data
age = int(raw_input("Enter your age: "))
years_to_retirement = 65 - age
print "You have", years_to_retirement, "years until retirement"
When the user enters text like 'twenty', the int() function has nothing to convert, triggering a ValueError that halts the program. The following example shows how to anticipate and manage this potential crash.
# Fixed: add error handling for invalid input
try:
age = int(raw_input("Enter your age: "))
years_to_retirement = 65 - age
print "You have", years_to_retirement, "years until retirement"
except ValueError:
print "Invalid input. Please enter a number."
To prevent crashes from invalid entries, you can wrap your conversion logic in a try...except block. The code inside the try statement attempts to run. If the int() function fails and raises a ValueError, the program doesn't crash. Instead, it executes the code in the except block, allowing you to handle the error gracefully. This approach is crucial for building robust programs that anticipate and manage unexpected user input.
Managing whitespace in raw_input()
Users often add extra spaces before or after their input from raw_input(). This seemingly harmless whitespace can break your logic, especially when you're comparing strings for equality. The code below demonstrates how an accidental space can cause a simple username check to fail.
# Bug: unexpected whitespace affects comparison
username = raw_input("Username: ")
if username == "admin":
print "Administrator access granted"
else:
print "Regular user access granted"
When a user types " admin ", the comparison username == "admin" fails due to the extra spaces. As a result, the program incorrectly grants regular user access. See how to fix this in the following example.
# Fixed: strip whitespace for more reliable comparison
username = raw_input("Username: ").strip()
if username == "admin":
print "Administrator access granted"
else:
print "Regular user access granted"
To fix this, chain the .strip() method directly to your raw_input() call. It immediately removes any leading or trailing whitespace from the user's entry, ensuring your comparisons work reliably even with accidental spaces.
- Always use
.strip()when your logic depends on exact string matches, such as checking usernames, commands, or "yes/no" answers.
Real-world applications
Now that you know how to handle errors, you can combine these techniques to build interactive command-line tools.
Building a simple calculator with raw_input()
By combining raw_input() with float() conversion, you can create a simple command-line calculator for basic arithmetic operations.
num1 = float(raw_input("Enter first number: "))
num2 = float(raw_input("Enter second number: "))
print "Sum:", num1 + num2
print "Product:", num1 * num2
This code puts several concepts together into a working tool. It prompts for input and immediately converts the string from raw_input() into a decimal-ready number using float(). This is a concise way to prepare user input for calculations.
- The choice of
float()is important because it allows the calculator to work with decimal values, not just whole numbers. - After conversion, the
num1andnum2variables behave like any other number, so you can use standard operators like+and*for calculations.
Creating an interactive quiz with raw_input()
By combining raw_input() with a loop and string methods like .lower(), you can create an interactive quiz that asks questions and keeps score.
score = 0
questions = ["What is the capital of France?", "What is 7 * 8?"]
answers = ["paris", "56"]
for i in range(len(questions)):
user_answer = raw_input(questions[i] + " ")
if user_answer.lower() == answers[i]:
print "Correct!"
score += 1
else:
print "Incorrect. The answer is", answers[i]
print "Your final score:", score, "out of", len(questions)
This script builds a quiz by pairing two lists: one for questions and one for answers. A for loop iterates through them using an index, which allows you to pull the question and its matching answer at the same time.
- The
user_answer.lower()method makes the check case-insensitive, so "Paris" is graded the same as "paris". - A
scorevariable tracks correct responses. - The final tally is printed once all questions are answered.
This structure is a straightforward way to manage quiz content and logic together.
Get started with Replit
Put your raw_input() skills to use by building a real tool. Just tell Replit Agent what you want: "build a command-line budget tracker" or "create a number guessing game."
Replit Agent writes the code, tests for errors, and deploys your app from your browser. Start building with Replit.
Create and deploy websites, automations, internal tools, data pipelines and more in any programming language without setup, downloads or extra tools. All in a single cloud workspace with AI built in.
Create and deploy websites, automations, internal tools, data pipelines and more in any programming language without setup, downloads or extra tools. All in a single cloud workspace with AI built in.

.png)

.png)