Input and Output
In Python, you can interact with users using the input() and print() functions.
print() – Displaying OutputLet’s start by displaying something to the screen. The print() function sends information from your program to the user.
print("Hello, World!")
Hello, World!
Python simply prints the string "Hello, World!" to the console. This is your first output.
You can print more than one item by separating them with commas:
name = "Arjun"
age = 25
print("Name:", name, "Age:", age)
Name: Arjun Age: 25
Each argument is converted to a string if needed, and Python automatically inserts spaces between them. You don’t need to manually add spaces unless you want specific formatting.
input() – Getting User InputThe input() function pauses the program and waits for the user to type something and hit enter.
name = input("What is your name? ")
print("Hello", name)
What is your name? Arjun
Hello Arjun
input() always returns a string. Even if you type numbers, Python treats them as strings.type() to check the data type if you're unsure.To convert user input to another type (like integer or float), use casting functions:
age = input("Enter your age: ")
print("Type before conversion:", type(age))
age = int(age)
print("Type after conversion:", type(age))
Enter your age: 20
Type before conversion: <class 'str'>
Type after conversion: <class 'int'>
Always check and validate user input to prevent errors. Here's a basic numeric check:
user_input = input("Enter a number: ")
if user_input.isdigit():
number = int(user_input)
print("You entered:", number)
else:
print("That’s not a valid number.")
Enter a number: 45
You entered: 45
Enter a number: hello
That’s not a valid number.
print() is for output. Use sep and end to customize formatting.input() is for input. It always returns a string.int(), float(), or str() to convert types as needed.