In this article, we will explore how Python handles user input and output. We'll start by discussing input, and then move on to output.
Input in Python
In Python, regardless of the data provided by the user, it is always taken as a string. Therefore, if we want to use the input as a different data type, we need to convert it. Here's the syntax for taking input from the user:
Syntax :
$ input(βMessage to userβ)
Example:
As you can see, when the user enters their name, Python stores it as a string. We'll cover more examples later on.
How to take input from users in Python?
To receive input from the user, Python provides an inbuilt function called βinput()β. We can also pass a message to the user to indicate what we expect them to enter.
Example:
1. We can store the value obtained from the user in variables using the βinput()β function.
2. If we check the datatype of the βNameβ variable it is a string as shown below.
3. Even when the user enters a number, Python still treats it as a string. We can convert it to an integer using appropriate conversion functions.
Lets convert digits into Integer from String.
For now thatβs all about the input in Python.
Output in Python
Python provides a built-in function βprint()β to display output to the user.
Syntax:
$ print(βOutput Stringβ, sep=β β, end = β/nβ, file = file, flush = flush )
Example:
Note : Even if we provide numbers in print() internally python converts it into a string then displays it to the user.
1. Let's see how we can use the separator βsepβ in βprint()β. The βsepβ parameter is used to specify the separator between values.
So, whatever we provide in sep it will insert in between the values as shown above.
2. By default, the βendβ parameter in βprint()β is set to '\n', which represents a new line. If we want to change it, we can specify a different value for βendβ.
3. Python uses placeholders β{ }β to indicate values that will be replaced by the values passed through βstr.format()β in order.
Syntax:
name = "John"
print("{}, is the founder of Neptuneworld.".format(name))
Output: John, is the founder of Neptuneworld.
4. How to format or truncate float values to a desired decimal place.
We can format or truncate floating-point values to a desired number of decimal places using the βformat()β function.
Example 1:
num=665.6754567, truncate to 2 decimal places.
num = 665.6754567
print("{:.2f}".format(num)) # Output: 665.68
Example 2:
num= 5546.456543, truncate to 3 decimal places.
num = 5546.456543
print("{:.3f}".format(num)) # Output: 5546.457
Conclusion
Now that you have a good understanding of Python input and output, you can comfortably handle user input and display output to the user.
If youβre still thirsty for more information, have questions, or simply would like to share your thoughts, then feel free to reach out in the comments section below.