Input#

The input() function in Python allows a developer to accept input from a user at runtime. This is especially useful when creating interactive scripts or simple user interfaces in the terminal.

Basic Usage#

The simplest way to use the input() function is to call it without any arguments. When you do this, the program will pause, allowing the user to type their input, and will continue once the Enter key is pressed.

user_input = input()
print("You entered:", user_input)

When you run the code above, the program will wait for you to input something. Whatever you input will then be displayed in the next line.

Prompting the User#

You can also provide a string to input(), which will act as a prompt for the user:

name = input("Enter your name: ")
print(f"Hello, {name}!")

When this code is run, the user will see “Enter your name: ” and can respond accordingly.

Note on Data Types#

It’s crucial to understand that the input() function always returns a string. If you’re expecting a number, you need to cast it to the appropriate type. For example, the following process would convert the input to an integer:

age = input("Enter your age: ")
age = int(age)  # Convert the string input to an integer
print(f"In 5 years, you'll be {age + 5} years old.")

And this is how you would do the same for a float:

weight = input("Enter your weight in kg: ")
weight = float(weight)
print(f"Half your weight is: {weight / 2} kg")