Input and output (I/O) are essential concepts in programming. In this section, we will learn how to gather input from the user and display output using Python.
Python provides a built-in function called input()
that allows you to prompt the user for input. Let’s consider a simple example:
name = input("Please enter your name: ")
print("Hello, " + name + "!")
In the above code, the input()
function takes a string argument which serves as the prompt message to the user. The user is expected to enter some text, which is then stored in the name
variable. The print()
function is used to display a greeting message along with the user’s name.
When you run the above code, it will display:
Please enter your name: (user can enter their name here)
Hello, (user's name)!
You can use the input()
function to gather various types of input, such as numbers:
age = int(input("Please enter your age: "))
print("You will be " + str(age + 1) + " years old next year.")
In the above code, the input()
function is used to receive the age as input from the user. Since the input is expected to be a number, we use the int()
function to convert the input to an integer. The print()
function then displays a message using the user’s age incremented by one.
To display output in Python, we mainly use the print()
function. We have already seen examples of this function in the previous sections.
The print()
function can display both simple text and complex expressions. You can concatenate multiple strings using the +
operator for printing:
print("Today is " + "Monday")
This will output:
Today is Monday
You can also use the print()
function to display the values of variables:
number = 42
print(number)
This code will display:
42
If you want to format the output, you can use placeholders by enclosing variables in curly braces ({}
) and using the format()
method:
name = "John"
age = 25
print("My name is {} and I am {} years old.".format(name, age))
In the above code, the format()
method replaces the placeholders {}
with the values of the variables name
and age
. The result will be:
My name is John and I am 25 years old.
You can also assign names to the placeholders for better readability:
name = "John"
age = 25
print("My name is {n} and I am {a} years old.".format(n=name, a=age))
This will produce the same output:
My name is John and I am 25 years old.
Now that you understand how to gather user input and display output, you have a powerful toolset to create interactive Python programs!
It is important to practice using these functions and familiarize yourself with the possibilities they offer. With time and experience, you can master input and output in Python and make your programs more dynamic and user-friendly.