









Python Basic Input and Output
1. Using print()
– Displaying Output
Let’s start by displaying something to the screen. The print()
function sends information from your program to the user.
print("Hello, World!")
Hello, World!
What’s Happening?
Python simply prints the string "Hello, World!"
to the console. This is your first output.
Printing Multiple Values
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
Explanation
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.
2. Using input()
– Getting User Input
The 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
Important Notes:
input()
always returns a string. Even if you type numbers, Python treats them as strings.- Use
type()
to check the data type if you're unsure.
Type Conversion (Casting)
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'>
Verifying and Validating Input
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.
Tips
print()
is for output. Usesep
andend
to customize formatting.input()
is for input. It always returns a string.- Use
int()
,float()
, orstr()
to convert types as needed. - Always validate user input to avoid runtime errors.