Python Get input from Console
How to prompt for user input and read command-line arguments. Python user input from the keyboard can be read using the
input() built-in function. The input from the user is read as a string and can be assigned to a variable. After entering the value from the keyboard, we have to press the “Enter” button. Then the
input() function reads the value entered by the user.
1. What is Console in Python?
Console (also called Shell) is basically a command-line interpreter that takes input from the user i.e one command at a time and interprets it. If it is error free then it runs the command and gives required output otherwise shows the error message. A Python Console looks like this.
2. Python Get input from Console
To read user input you can try the
cmd module for easily creating a mini-command line interpreter (with help texts and autocompletion) and
input for Python 3+) for reading a line of text from the user.
text = raw_input("prompt") # Python 2 text = input("prompt") # Python 3
There are two modules for parsing command line options:
(deprecated since Python 2.7, use
argparse instead) and
getopt. If you just want to input files to your script, behold the power of
3. String and Numeric input
input() function, by default, will convert all the information it receives into a string. Numbers, on the other hand, need to be explicitly handled as such since they come in as strings originally.
user_input1 = input ("Enter a integer number: ") int_number = int(user_input1) print ("The number you entered is: ", input_number) user_input2 = input ("Enter a decimal number: ") float_number = float(user_input2) print ("The number you entered is: ", float_number)
Another way to do the same thing is as follows:
int_number = int(input ("Enter a integer number: ")) print ("The number you entered is: ", input_number) float_number = float(input ("Enter a decimal number: ")) print ("The number you entered is: ", float_number)