Introduction
Input and output operations are fundamental in Python for interacting with users and handling data. In this guide, we'll explore the basics of accepting input from users and displaying output using Python's built-in functions, along with sample code.
Getting User Input
You can get input from the user using the input()
function. It reads a line of text from the user and returns it as a string. For example:
# Getting user input
name = input("Enter your name: ")
print("Hello, " + name + "!")
Displaying Output
Python provides the print()
function for displaying output. You can print text, variables, and expressions. For example:
# Printing output
print("Hello, World!")
number = 42
print("The answer is:", number)
Formatting Output
You can format the output using f-strings or the format()
method. For example:
# Using f-strings
name = "Alice"
age = 30
print(f"My name is {name} and I am {age} years old.")
# Using the format() method
item = "apple"
price = 0.5
formatted_text = "The {} costs ${:.2f}".format(item, price)
print(formatted_text)
Conclusion
Python's input and output functions are essential for building interactive and informative programs. Whether you're collecting user data, displaying results, or formatting output, Python provides straightforward and powerful tools to handle input and output operations effectively.