Learn how to take user input from the command line using the input()
function
The input()
function reads a line from input, converts it to a string, and returns it.
name = input("Enter your name: ")
print("Hello,", name)
Since all input is read as a string, you often need to convert it:
age = input("Enter your age: ")
age = int(age) # Convert to integer
print("You will be", age + 1, "next year.")
a, b = input("Enter two numbers separated by space: ").split()
a = int(a)
b = int(b)
print("Sum:", a + b)
x, y = map(int, input("Enter two integers: ").split())
print("Product:", x * y)
# Input: 1 2 3 4 5
numbers = list(map(int, input("Enter numbers: ").split()))
print("You entered:", numbers)
try-except
blocks to catch conversion errors.split()
to handle space-separated input values.map()
for efficient conversion of multiple values.try:
num = int(input("Enter a number: "))
print("Square:", num * num)
except ValueError:
print("That was not a valid number!")