Lesson Notes
The input()
function takes a single str
object and prints it to the console to alert the user your program is expecting input.
The user types input into the console at the prompt and input returns whatever the user types as a str
result = input(`<prompt>`)
<prompt>
: strYou MUST save the value in variable, otherwise it is immediately deleted. You can call the variable anything you like as long as you follow the basic naming rules.
INCORRECT
input("Please input a value: ") #no error message but lost data
CORRECT
var = input("Please input a value: ")
input returns EVERYTHING as a str
You must cast it to an integer or float to use the object as a number type (i.e. in arithmetic)
Note: You don't need to cast the value if you are expecting a str
data type
Without Casting
var = input("Please input a value: ")
print(var, type(var))
var = var + 5 # TYPE ERROR!!!!
With Casting
var = input("Please input a value: ")
var = int(var) # cast to a number type
print(var, type(var))
var = var + 5 # SUCCESS!!!
Casting is when you change the type of some data, for example, from str
to int
.
HINT: shorter form of casting from input
var = int(input(“Pick a number:”))
Sometimes you must convert an object to a different data type:
However, it must make sens for the data to be converted to the new type:
var = int('a') # ERROR - `a` can't be converted to a number
var = int('3.0') # ERROR - only numbers are allowed, not `.`
var = float('3.0') # SUCCESS in this case you would need to use a `float`