There's more than one way to do this.
Taking input from the intepreter
For Python 2.x, you can use the raw_input() function:
my_input = raw_input("Please enter an input: ")
#do something with my_input
Note that the input is always a string. To retrieve a number, you can use the built-in int()
function:
my_input = int(raw_input("Please enter an input: "))
#do something with my_input
As one other answer mentioned, this will throw an error if the input is a float.
There's also another function, input
, in Python 2.x. However, in this version of Python, input
evaluates the input, which is a bad idea. It's not recommended to use it.
For Python 3.x, however, you can use the input() function without any problem, since it's a replacement for raw_input
:
my_input = input("Please enter an input: ")
#do something with my_input
Taking input from command line arguments
You can also retrieve your input from command line arguments, when executing your script like this:
$ python my_script.py arg1 arg2
The arguments will be stored in the list sys.argv
. sys.argv[0]
is the first argument, sys.argv[1]
is the second argument, and so on.
Example:
import sys
my_input = sys.argv[0]
#do something with my_input
See the details of it here
This method works for both versions, Python 3.x and 2.x .
Hope this helps!