Computer ScienceChapter 3: Programming Fundamentals (Python)
3.7 Python Input/Output (I/O)
Input/Output (I/O)
Explanation level
Introduction
Programs are meant to interact with users. They take some input from the user, process it, and produce output. Python provides simple functions for both tasks: `input()` for taking input from the user and `print()` for displaying output. Understanding these two functions is essential for writing interactive programs.
Definition
Input/Output (IO) in Python refers to the process of receiving data from the user (input) and displaying results to the user (output).
- Input = Getting data from the user
- Output = Showing results to the user
Main Idea
The Python Shell is interactive and accepts commands. So, results of arithmetic operations and desired output using the `print` function can be used. User can enter data through the `input()` function, via which data will be stored in a variable. This way, the same input does not need to be entered again and again by the user, and whenever the data is required, the corresponding variable is used.
Core Concept
- `print()` — Displays output on the screen
- `input()` — Takes input from the user
- `eval()` — Converts input into a number (if needed)
Detailed Explanation
The print() Function
Parenthesis followed by `print`, i.e. `print()` function instructs Python to output whatever is inside the parenthesis, within quotes.
Basic Syntax: ```python print("Your message here") ```
Example: ```python print("I Love Pakistan!!!") ```
Output: ``` I Love Pakistan!!! ```
Important Point: Even if a space is entered before or after the sentence within the quotes, it will be displayed as it is.
Example — Spaces Matter: ```python print("I Love Pakistan !!!") ```
Output: ``` I Love Pakistan !!! ```
Example — Leading Spaces: ```python print(" I Love Pakistan!!!") ```
Output: ``` I Love Pakistan!!! ```
The spaces are preserved exactly as they are typed.
The input() Function
Computer Programs are meant to be processed while taking some input and generating corresponding output. User can enter data through the `input()` function, via which data will be stored in a variable.
Basic Syntax: ```python variable_name = input("Prompt message: ") ```
Example — Taking Input: ```python country = input("Enter the name of your country: ") print("I love", country) ```
Output: ``` Enter the name of your country: Pakistan I love Pakistan ```
- `input("Enter the name of your country: ")` — Displays the prompt and waits for the user to type something.
- The user types `Pakistan` and presses Enter.
- The value `Pakistan` is stored in the variable `country`.
- `print("I love", country)` — Displays `I love Pakistan`.
The eval() Function
Python provides basic variable types as `char`, `integer`, `float`, `boolean`, etc. The `input()` function treats the entered data as a set of characters (string). Hence, if a numeral is entered, it needs to be converted to a number, explicitly using the `eval()` function.
In Python, `eval()` function evaluates expressions which are generally mathematical in nature. However, it also assesses strings/set of characters and responds with an integral value.
Why eval() is needed:
Without `eval()`, if you input a number, it is treated as a string. So `"123" + "123"` gives `"123123"` (concatenation) instead of `246` (addition).
Example — Without eval(): ```python num = input("Enter a Number: ") print("Double of the said number is", num + num) ```
Output: ``` Enter a Number: 123 Double of the said number is: 123123 ```
- `num = input(...)` stores `"123"` as a string
- `num + num` concatenates the strings, giving `"123123"`
Example — With eval(): ```python num = eval(input("Enter a number: ")) print("Double of the said number is", num + num) ```
Output: ``` Enter a Number: 123 Double of the said number is: 246 ```
- `eval(input(...))` converts the input `"123"` to the integer `123`
- `num + num` adds the numbers, giving `246`
Concatenation
When two variables are added while the values are characters, the add function joins the values rather than adding them up. The respective terminology is concatenation of two strings or characters to merge them up.
Example — Concatenation: ```python first = "Hello" second = "World" result = first + " " + second print(result) ```
Output: ``` Hello World ```
Example — Numeric Addition: ```python a = 10 b = 20 result = a + b print(result) ```
Output: ``` 30 ```
- 0 = 1 (concatenation)
- 0 = 1 (addition)
Summary of IO Functions
| Function | Purpose | Example |
|---|---|---|
| `print()` | Display output | `print("Hello")` |
| `input()` | Take input as string | `name = input("Enter name: ")` |
| `eval()` | Convert input to number | `num = eval(input("Enter number: "))` |
Intermediate Level
How input() Works
When you call `input()`:
- The prompt message is displayed on the screen.
- The program pauses and waits for the user to type something.
- When the user presses Enter, the typed text is captured as a string.
- The string is stored in the variable.
Important: The `input()` function always returns a string. Even if the user types numbers, the result is a string.
Type Conversion
Since `input()` returns a string, you often need to convert the input to the required data type.
Using eval(): ```python num = eval(input("Enter a number: ")) ``` `eval()` automatically detects whether the input is an integer or a float.
Using int(): ```python num = int(input("Enter an integer: ")) ``` `int()` converts the input to an integer. If the user types a decimal, it will cause an error.
Using float(): ```python num = float(input("Enter a decimal: ")) ``` `float()` converts the input to a decimal number.
Comparison:
| Method | Purpose | Example Input | Result |
|---|---|---|---|
| `input()` | Get string | `"123"` | `"123"` (string) |
| `int(input())` | Get integer | `"123"` | `123` (int) |
| `float(input())` | Get decimal | `"123.45"` | `123.45` (float) |
| `eval(input())` | Auto-detect | `"123"` or `"123.45"` | `123` or `123.45` |
Practical Examples
Example 1 — Area of a Rectangle:
```python length = eval(input("Enter length: ")) width = eval(input("Enter width: ")) area = length * width print("Area of rectangle:", area) ```
Output: ``` Enter length: 5 Enter width: 3 Area of rectangle: 15 ```
Example 2 — Average of Three Numbers:
```python a = eval(input("Enter first number: ")) b = eval(input("Enter second number: ")) c = eval(input("Enter third number: ")) average = a + b + c3 print("Average:", average) ```
Output: ``` Enter first number: 10 Enter second number: 20 Enter third number: 30 Average: 20.0 ```
Example 3 — Simple Interest:
```python principal = eval(input("Enter principal amount: ")) rate = eval(input("Enter rate of interest: ")) time = eval(input("Enter time in years: ")) interest = principal * rate * time100 print("Simple Interest:", interest) ```
Output: ``` Enter principal amount: 1000 Enter rate of interest: 5 Enter time in years: 2 Simple Interest: 100.0 ```
Formula / Mathematical Form
Not applicable for this topic.
Solved Example
Example — Calculate Simple Interest
- Principal amount = 1000
- Rate of interest = 5%
- Time = 2 years
Required: - Simple Interest
Formula: ``` Simple Interest = Principal × Rate × Time100 ```
Code: ```python principal = eval(input("Enter principal amount: ")) rate = eval(input("Enter rate of interest: ")) time = eval(input("Enter time in years: ")) interest = principal * rate * time100 print("Simple Interest:", interest) ```
Output: ``` Enter principal amount: 1000 Enter rate of interest: 5 Enter time in years: 2 Simple Interest: 100.0 ```
- `principal = 1000`
- `rate = 5`
- `time = 2`
- `interest = 1000 * 5 * 2100 = 100.0`
- Print the result
Important Points
- - `print()` displays output on the screen.
- - `input()` takes input from the user and returns it as a string.
- - `eval()` converts the input string to a number.
- - Without `eval()`, numbers entered by the user are treated as strings.
- - `"123" + "123"` gives `"123123"` (concatenation).
- - `123 + 123` gives `246` (addition).
- - Spaces in `print()` are preserved exactly as typed.
- - The `input()` function always returns a string.
- - Use `int()`, `float()`, or `eval()` to convert input to numbers.
- - Use f-strings or `.format()` for formatted output.
- - Escape characters like `\n` and `\t` add special formatting.
Remember
- - **0** = Display output.
- - `input()` = Take input as string.
- - `eval()` = Convert input to number.
- - `int(input())` = Take integer input.
- - `float(input())` = Take decimal input.
- - `eval(input())` = Auto-detect number type.
- - Concatenation = Joining strings with `+`.
- - Addition = Adding numbers with `+`.
- - **0** = New line.
- - **0** = Tab.
Common Mistakes
- - Forgetting eval() when taking numeric input: Without `eval()`, `"10" + "20"` gives `"1020"` instead of `30`.
- - Using int() for decimal input: `int(input())` fails if the user types a decimal. Use `float()` or `eval()` instead.
- - Thinking input() returns a number: It always returns a string.
- - Confusing concatenation with addition: `"10" + "20"` is concatenation; `10 + 20` is addition.
- - Forgetting quotes in print(): `print(Hello)` causes an error. Use `print("Hello")`.
- - Not handling invalid input: If the user types text when a number is expected, `eval()` or `int()` will cause an error.
- - Mixing tabs and spaces: Python is strict about indentation — be consistent.
Quick Revision
The Python Shell is interactive and accepts commands. So, result of arithmetic operations and desired output using the `print` function can be used. Parenthesis followed by `print`, i.e. `print()` function instructs Python to output whatever is inside the parenthesis, within quotes.
Computer Programs are meant to be processed while taking some input and generating corresponding output. User can enter data through the `input()` function, via which data will be stored in a variable. This way, the same input does not need to be entered again and again by the user, and whenever the data is required, the corresponding variable is used.
Python provides basic variable types as `char`, `integer`, `float`, `boolean`, etc. The `input()` function treats the entered data as a set of characters. Hence, if a numeral is entered, it needs to be converted to number, explicitly using the `eval()` function. In Python, `eval()` function evaluates expressions which are generally mathematical in nature. However, it also assesses strings/set of characters and responds with an integral value.
When two variables are added while the values are characters, the add function joins the values rather than adding them up. The respective terminology is concatenation of two strings or characters to merge them up.
60-Second Revision
- **0** = Display output.
- `input()` = Take input as string.
- `eval()` = Convert input to number.
- `int(input())` = Integer input; `float(input())` = Decimal input.
- **Concatenation:** 0 = 1.
- **Addition:** 0 = 1.
- Without eval(): Numbers are treated as text.
- With eval(): Numbers are treated as numbers.
- Escape characters: `\n` = new line, `\t` = tab.
- Warning: Always use `eval()` or `int()`/`float()` when taking numeric input.
Did you understand this topic?
Your answer is saved with your learning record. It does not mark the topic as mastered.
Quick revision
Revision Zone
Review the key facts, formulas and checks before you move on.3.7 Python Input/Output (I/O)
Sticky Notes · Quick Revision
Key Point 1
- **0** = Display output.
Key Point 2
- `input()` = Take input as string.
Key Point 3
- `eval()` = Convert input to number.
Key Point 4
- **0** = Integer input.
Key Point 5
- **0** = Decimal input.
Key Point 6
- **0** = Auto-detect.
Key Point 7
- **Concatenation:** 0 = 1.
Key Point 8
- **Addition:** 0 = 1.
Key Point 9
- **0** = New line; **1** = Tab.
Key Point 10
- f-string: `f"Name: {name}"`.
Same supplied content as this Notes page (shared canonical source).