PYTHON: input() When you need to get a variable from a user. You can use the input() function to assign a value to that variable. The input() function requires you to write a 'prompt' for a user's input to your program. You need to write this between the brackets, encasing it in quotes. It then prints the user prompt on the screen, and stores the typed input as a variable as soon as the user presses the 'RETURN' or 'ENTER' key. For example:
Warning - input always returns a string, even if the user typed in a number. Therefore if the user types in a number you have to convert that to a number variable type before you can treat it as one. For example, let's make a simple program that asks for your age, then works out how many years to your retirement.
The '67-age' calculation cannot be done - there is a 'type error' - the variable 'age' is a string - it is defined via the input() function - which always returns a string variable. We cannot deduct a string variable from a number. Convert it!We need to convert the 'string number' to a 'true number'. In this case an integer (a whole number). We can do this using the function int()
The number required in your code may not be an integer. If you need to convert the user's input string to a decimal number, (called a floating point number in Python), you will have to use the function float() instead of int(). |
|