What are some common uses of type()?

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.

12 Likes

Please, can we get some code examples explaining how check whether the user input is this or that type? That would be helpful while going through these exercises, thanks!

1 Like

found examples simply using google:

https://stackoverflow.com/questions/3501382/checking-whether-a-variable-is-an-integer-or-not

which besides example:

type(x) == int

also yielded explanation why or why not to use type. Quite useful, google is your friend to find information (or whatever search engine you prefer)

1 Like

Thank you for this piece of code, honestly I was trying google, but the results I checked only explained what this function does, but it didn’t explain how to work with it besides printing its output. Maybe I was not using the right query. Google is your friend, but very secretive one if you don’t know exactly how to ask the question lol

2 Likes

Being good at using a search is underrated/useful skill, i googled:

python check type is int

i had an advantage in this case, i already knew the answer and could use that to construct the search query.

Good for you! When I googled “python check type is int”, the first link I clicked showed me this message: “Our system thinks you might be a robot!”

I guess I’m super lucky lol

2 Likes