Completed
-
1. Introduction to Python
-
2. Python Basics
-
3. Working with Data Structures
-
4. Functions and Modules
-
5. Object-Oriented Programming (OOP)
-
6. File Handling
-
7. Error and Exception Handling
-
8. Python for Data Analysis
-
9. Advanced Topics in Python
-
10. Working with APIs
-
11. Python for Automation
-
12. Capstone Projects
- 13. Final Assessment and Quizzes
2.2 Input and Output
Input and output (I/O) operations are fundamental for interacting with users and external systems. In Python, input and output operations allow you to retrieve data from the user, process it, and display the results. Python provides simple functions to handle these operations effectively.
1. Input in Python
The input() function is used to take input from the user. By default, it takes input as a string, and if you need to handle different data types (like integers or floats), you must explicitly convert the input.
Using the input() function:
- Basic Input:
name = input("Enter your name: ") print("Hello, " + name + "!")
In this example:- The program prompts the user with the message Enter your name: .
- The input provided by the user is stored in the name variable.
- The program then prints a greeting using the user's input.
Converting Input to a Different Type:
Since input() returns a string, you may need to convert the input to another data type (e.g., integer, float) using functions like int() or float().
- Example with Integer Conversion:
age = input("Enter your age: ") age = int(age) # Convert the input to an integer print(f"Your age is {age}.")
Here:- The input() function retrieves the user's age as a string.
- The int() function converts the string into an integer so that it can be used in numerical operations.
- Example with Float Conversion:
weight = input("Enter your weight in kg: ") weight = float(weight) # Convert the input to a float print(f"Your weight is {weight} kg.")
In this case:- The input is converted to a floating-point number using float(), which allows handling decimal numbers.
2. Output in Python
Python provides several ways to display output using functions like print() and formatted strings. This allows you to display messages, values, and results to the user.
Using the print() function:
The print() function is used to send data to the standard output (usually the screen). It can print strings, numbers, or any other data type.
-
Basic Output:
print("Hello, World!")
This simply prints the string Hello, World! to the console. -
Printing Variables:
name = "Alice" print("Hello, " + name + "!")
In this example:- The print() function prints a string with the value of the name variable concatenated.
Formatted Output:
Python provides several ways to include variable values in strings, making output more readable and customizable.
-
Using f-strings (formatted string literals):
Introduced in Python 3.6, f-strings are a concise and efficient way to embed expressions inside string literals. You prefix the string with an f and place expressions inside curly braces {}.
name = "Alice" age = 25 print(f"Hello, {name}! You are {age} years old.")
Output:Hello, Alice! You are 25 years old.
This method is clean, readable, and very efficient. -
Using str.format() method:
Prior to f-strings, Python used the str.format() method for string formatting.
name = "Alice" age = 25 print("Hello, {}! You are {} years old.".format(name, age))
Output:Hello, Alice! You are 25 years old.
This method also supports more complex formatting options, such as alignment and width specification. -
Using % formatting (old-style):
This is an older approach for string formatting and is less commonly used now.
name = "Alice" age = 25 print("Hello, %s! You are %d years old." % (name, age))
Output:Hello, Alice! You are 25 years old.
3. Formatting Output:
You can customize how the output is displayed using formatting options.
-
Controlling Decimal Places:
Python allows you to format numbers, such as controlling the number of decimal places displayed.
pi = 3.14159265359 print(f"Value of Pi: {pi:.2f}")
Output:Value of Pi: 3.14
This rounds the value of pi to two decimal places. -
Padding and Alignment:
You can align text and control the width of numbers or strings in your output.
print(f"{'Left aligned':<20}") # Left alignment print(f"{'Right aligned':>20}") # Right alignment print(f"{'Centered':^20}") # Center alignment
Output:Left aligned Right aligned Centered
4. Input and Output with Files
In addition to standard input/output, Python allows reading from and writing to files. You can use the built-in open() function to work with files.
-
Reading from a File:
with open('data.txt', 'r') as file: content = file.read() print(content)
-
Writing to a File:
with open('output.txt', 'w') as file: file.write("Hello, file!")
In both examples, open() is used to open the file in read ('r') or write ('w') mode. The with statement ensures that the file is properly closed after the operation.
Summary
- Input: Python provides the input() function to take input from the user. By default, input is treated as a string, and you can convert it to other types (e.g., int, float).
- Output: The print() function is used to display data on the screen. You can use various methods like f-strings, str.format(), or % formatting to include variables in your output.
- File I/O: Python allows reading from and writing to files using the open() function, which can be useful for storing or processing large datasets.
Understanding how to handle input and output is essential for creating interactive programs that can work with users and external data.
Commenting is not enabled on this course.