Allowing Python Script Input
Sometimes you might need a script user to provide data into your script from the keyboard. To accomplish this task, Python provides the input function. The input function is a built-in function and has the following syntax:
variable=input(user prompt)
In Listing 4.24, the variable cups_consumed is assigned the value returned by the input function. The script user is prompted to provide this information. An input function argument designates the prompt provided to the user. The script user types an answer and presses the Enter key. This action causes the input function to assign the answer 3 as a value to the variable cups_consumed.
Listing 4.24 Variable Assignment via Script Input
>>> cups_consumed=input("How many cups did you drink? ") How many cups did you drink? 3 >>> print("You drank", cups_consumed, "cups!") You drank 3 cups! >>>
For the user prompt, you can enclose the prompt’s string characters in either single or double quotes. The prompt is shown enclosed in double quotes in Listing 4.24’s input function.
The input function treats all input as strings. This is different from how Python handles other variable assignments. Remember that if cups_consumed=3 were in your Python script, it would be assigned the data type integer, int. When using the input function, as shown in Listing 4.25, the data type is set to string, str.
Listing 4.25 Data Type Assignments via Input
>>> cups_consumed=3 >>> type(cups_consumed) <class 'int'> >>> cups_consumed=input("How many cups did you drink? ") How many cups did you drink? 3 >>> type(cups_consumed) <class 'str'> >>>
To convert variables (input from the keyboard) from strings, you can use the int function. The int function will convert a number from a string data type to an integer data type. You can use the float function to convert a number from a string to a floating-point data type. Listing 4.26 shows how to convert the variable cups_consumed to an integer data type.
Listing 4.26 Data Type Conversion via the int Function
>>> cups_consumed=input("How many cups did you drink? ") How many cups did you drink? 3 >>> type(cups_consumed) <class 'str'> >>> cups_consumed=int(cups_consumed) >>> type(cups_consumed) <class 'int'> >>>
You can get really tricky here and use a nested function. Nested functions are functions within functions. The general format is as follows:
variable=functionA(functionB())
Listing 4.27 uses this method to properly change the input data type from a string to an integer.
Listing 4.27 Using Nested Functions with input
>>> cups_consumed=int(input("How many cups did you drink? ")) How many cups did you drink? 3 >>> type(cups_consumed) <class 'int'> >>>
Using nested functions makes a Python script more concise. However, the trade-off is that the script is a little harder to read.