Python’s input() Function

Harold Nelson

What is input()?

The input() function in Python is used to get input from the user.

It pauses your program and waits for the user to type something and press Enter.

Basic Syntax

The basic syntax is simple:

variable_name = input()

This will store whatever the user types into variable_name.

Simple Example

Let’s say hello to the user.

name = input()
print("Hello, " + name + "!")

If the user types “Alice” and presses Enter, the output will be:

Hello, Alice!

The prompt Argument

You can provide a message to the user, called a prompt.

name = input("Please enter your name: ")
print("Hello, " + name + "!")

This is much more user-friendly!

Return Value: Always a String!

The input() function always returns a string.

Even if the user types a number, it’s treated as a string.

age = input("Enter your age: ")
print(type(age))

If the user enters 25, the output will be:

<class 'str'>

Type Conversion

To use the input as a number, you need to convert it.

Use int() for integers and float() for decimal numbers.

age_str = input("Enter your age: ")
age_int = int(age_str)
print(age_int * 2)

Example with Numbers

A simple calculator to add two numbers.

num1 = int(input("Enter the first number: "))
num2 = int(input("Enter the second number: "))
sum = num1 + num2
print("The sum is:", sum)

A Mini-Quiz

Let’s combine what we’ve learned.

answer = input("What is the capital of France? ")

if answer.lower() == "paris":
    print("Correct!")
else:
    print("Sorry, the answer is Paris.")

Common Pitfalls

  1. Forgetting type conversion: Leads to TypeError when doing math.
  2. Not providing a prompt: The user won’t know what to do.
  3. Assuming valid input: Users can type anything! (Error handling is an advanced topic).

Summary

  • input() gets user input.
  • It optionally takes a prompt string.
  • It always returns a string.
  • Use int(), float(), etc. to convert the type.

Happy coding!