What are some common uses of type()?


#1

Question

What are some common uses of type()?

Answer

Often when you write programs you’ll want to get input from the user, whether it be their name, age, or something random like their favorite type of cheese.
Regardless of what the input is, you’ll likely want to check that the user did in fact input the type of data you’re looking for. Otherwise, you may end up doing some invalid operation, like dividing a word by a number!
We can use type() to ensure that the user’s input is the type of data we’re expecting, and can fail to accept their input until it’s valid. This can be a difficult part of programming because it’s hard to know what all a user can input into your program, so you have to be careful about what you accept as input.


FAQ: Learn Python: Functions - type()