Python Input and Output
In this tutorial, we will go through learning how to take input from users and print them using different formatting available at Python.
Before taking input, let’s see how we can print something in Python.
Contents
How to print variables or values in Python?
The print() function helps to print output data to the standard console device screen. To understand it, you can see the following example:-
print("Hello World") name = "John Doe" print(name)
The output of the above program will be
John Doe
print(*objects, sep=’ ‘, end=’\n’, file=sys.stdout, flush=False)
How to format output in Python?
To format the output in Python, format() method is used which allows simple placeholder for formatting.
There are four different ways of handling formatting in Python.
- Default arguments
- Positional arguments
- Keyword arguments
- Mixed arguments
Let us explore with some examples:-
# default arguments print("Hello {}, your marks roll number is {}.".format("John", 79)) # positional arguments print("Hello {0}, your roll number is {1}.".format("John", 79)) # keyword arguments print("Hello {name}, your roll number is {roll}.".format(name="John", roll=79)) # mixed arguments print("Hello {0}, your roll number is {roll}.".format("John", roll=79))
The output of the above program is:-
Hello John, your roll number is 79.
Hello John, your roll number is 79.
Hello John, your roll number is 79.
How to take input from users in Python?
Taking input in Python is much simpler than in any other programming language. The use of input() function will get a prompt in the screen and ask for input. The value is assigned to the variable that is used to take the input from the user.
Let us use the following program to make a better understanding of taking input from users and printing them in the screen.
name = input("Hello, please input your name: ") print("Your name is", name)
The output of the above program is:-
Your name is John Doe
Please, note that the input that we took from the user is always a string. So, if you need some integer or float operation, make sure you use appropriate type conversion. Learn more about Python Data Type Conversion.