Advanced Input
We all know about the print statement to send textual data to the screen. But how are we going to accept textual data from the user? To solve this issue, Python provides the in-built input() method.
The below example demonstrates its usage.
What is your name?
James Bond
My name is James Bond.
The input() method accepts and returns strings or textual data only. Even numerical values will be returns as a string, as illustrated in the example below.
What is your age?
46
Ohh, you are 46 years old.
<class 'str'>
As demonstrated in the earlier example(s), we used a separate print statement to ask questions. It is alright to use the print statement to ask a question or display a prompt message, but it can add to the clutter. Python's input() method accepts the prompt as its argument value to make code readable and clear, as illustrated below.
Which is your favourite color?
blue
Your favourite color is blue.
Notice the "\n" newline character at the end. It is to print the message and accept user input from the following line. Without it, it will prompt for the user input on the same line. As an exercise, re-write the same without using the "\n" at the end and observe the behavior.
As stated above, the input() method accepts and returns only strings. We must first accept the number as a string and then convert it into the required type using the corresponding constructor to accept numerical values. This data-type conversion is called typecasting and will be covered later.
Here is an example.
What is your age?
46
What is your net worth?
100000
You age is 46 and your net worth is $100000.0!
Based on the current estimate, by the age of 56, your net worth will reach $500000.0!
You can perform arithmetic with values inside a string, provided you are using f-string to format string and is within the braces .
The input() method only accepts values from the command prompt
The input() method accepts values only from the command prompt. To receive user input using a GUI(Graphical User Interface), we have to use a UI framework like PyGtk, PyQT, Tkinter., etc.
At present, covering GUI programming is beyond the scope of this tutorial. However, you can refer this for more information.
In this chapter, we learned about accepting input from the user from the command line using the in-built input() method, showing a default prompt message to make the intent clear and accepting numerical values.