Day 4: Input & Output in Python
Making Your Programs Interactive
Introduction
Till now, your programs were static — they always produced the same output.
But real-world programs don’t work like that.
They take input from users, process it, and then show output.
This is the core idea of programming:
Input → Processing → Output
In this blog, you’ll learn how to:
- Take input from users
- Display output properly
- Format output professionally
What is Input?
Input is data provided to a program during execution.
This data can come from:
- Keyboard (user typing)
- Files
- APIs (advanced)
But for now, we focus on user input from keyboard.
Why Input is Important?
Without input:
- Programs are fixed
- No flexibility
- Same output every time
Example:
Static Program:
print("Hello Piyush")
Dynamic Program:
name = input("Enter your name: ")
print("Hello", name)
Now the output changes based on user → interactive program
Taking Input in Python
Python provides a built-in function:
input()
Basic Example:
name = input("Enter your name: ")
print(name)
Important Concept (VERY IMPORTANT)
input() always returns a string
age = input("Enter your age: ")
print(type(age)) # Output: <class 'str'>
Type Conversion (Revision)
To perform calculations, convert input:
age = int(input("Enter age: "))
print(age + 5)
Common Conversions:
int(input()) # integer
float(input()) # decimal
str(input()) # string (default)
What is Output?
Output is the result displayed to the user after processing input.
Without output:
- User cannot see results
- Program has no visible effect
Displaying Output in Python
Python uses:
print()
Basic Example:
print("Hello World")
Printing Multiple Values
name = "Piyush"
age = 21
print("Name:", name, "Age:", age)
sep and end (Advanced Printing)
Separator (sep)
print("Python", "Java", "C++", sep=" | ")
End Parameter (end)
print("Hello", end=" ")
print("World")
String Formatting
String formatting helps display output in a clean and professional way.
1. f-Strings (Recommended)
name = "Piyush"
age = 21
print(f"My name is {name} and I am {age} years old")
Fast, readable, modern
2. .format() Method
print("My name is {} and I am {}".format(name, age))
3. % Formatting (Old Style)
print("My name is %s and age is %d" % (name, age))
Escape Characters
print("Hello\nWorld") # New line
print("Hello\tWorld") # Tab
print("He said \"Hi\"")
Practice Questions
Basic
Take name as input and print:
"Welcome, <name>"
Take two numbers and print their sum
Take age and print:
"You will be <age+5> after 5 years"
Intermediate
Take name and marks, print:
"<name> scored <marks> marks"
Take 3 numbers and print their average
Tricky
a = input("Enter number: ")
b = input("Enter number: ")
print(a + b)
Why is output concatenation and not addition?
print("Hello", end="---")
print("World", end="***")
Predict output
a, b = input().split()
print(int(a) + int(b))
What if user enters only one value?
.png)

0 Comments:
Post a Comment