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.
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.
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.
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
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.