Index
What is User Input?
User input lets the user type something when the program is running, and the program can use that input to do something.
Syntax:
input("Your message here")
It shows a message to the user and waits for input.
Example 1: Get a Name
name = input("What is your name? ")
print("Hello, " + name + "!")
Output:
What is your name? John
Hello, John!
Example 2: Get a Number (and convert it to int)
By default, input()
gives you a string, even if you type numbers.
To do math, you must convert it using int()
or float()
.
age = input("Enter your age: ")
print("You are " + age + " years old.")
To use it as a number:
age = int(input("Enter your age: "))
print("Next year, you’ll be", age + 1)
Example 3: Add Two Numbers
num1 = int(input("Enter first number: "))
num2 = int(input("Enter second number: "))
sum = num1 + num2
print("Sum is:", sum)
Summary
Task | Example |
---|---|
Take input | input("Enter something: ") |
Convert to number | int(input("Enter a number: ")) |
Convert to float | float(input("Enter a decimal: ")) |