How do you determine types of variables in python? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 3

How do you determine types of variables in python?

So basically, I want to try to make the code do something if type(x) is int of float: do something. Else: print("error") But it doesn't seem to work, because It always prints error no matter what. https://code.sololearn.com/cM4veVi65Es1/?ref=app

21st Nov 2019, 7:22 PM
Dzaan Svetski Bichi
Dzaan Svetski Bichi - avatar
7 Answers
+ 9
Hi, thanks for sharing your code. Now it's clear what you are trying to do. As you use input() function, everything you type in will be returned as a string. So 5 gets "5", 2.45 gets "2.45", True gets "True". What you can do is, to try getting the input as the desired data type. If you expect to get an int, you can use Inp = int(input("enter an integer number: ")) As long as the user does a correct input, this does work. If not, the program will crash with an exception. But you should use try:... except:... block. You could also go a way, by just accepting that input always generates strings, but try to figure out what type of data it contains. You could use string methods like if inp.isdigit(): to get the real data type. So also take a look at the python docs to find more about this.
21st Nov 2019, 8:49 PM
Lothar
Lothar - avatar
+ 11
Here is some code that may help you. But anyway - please post your code here. a = 1 b = 'hello' c = [1,2,3] d = (4,5,6) e = {7,8,9} f = {'a': 1, 'b': 2} print(type(a)) print(type(b)) print(type(c)) print(type(d)) print(type(e)) print(type(f)) # output: ''' <class 'int'> <class 'str'> <class 'list'> <class 'tuple'> <class 'set'> <class 'dict'> ''' so you can do: if type(a) == int: # do something ...
21st Nov 2019, 7:49 PM
Lothar
Lothar - avatar
+ 7
Can you please share your code here? This makes it much easier for people who want to help. Thank's!
21st Nov 2019, 7:38 PM
Lothar
Lothar - avatar
+ 5
leave your input as it is... a string.. Make a try....block that tries to convert your input to an int/float and do what ever you need to do with that int/float... In the except part for the try block print out the string length.
21st Nov 2019, 9:14 PM
rodwynnejones
rodwynnejones - avatar
+ 4
Your code is only prompting for a string input, therefore the output is always the length of the input. Example: input => 365 is string input => length 3 So your code needs to be able to identify if a text character can be converted to an integer. if you can write a bit of code to do that, then converting it will be easy and your code will work. Have a play, post again if you can't resolve
21st Nov 2019, 8:57 PM
Rik Wittkopp
Rik Wittkopp - avatar
+ 3
This is simply a checker but its functional. I would appreciate if you post your attempt. checkIntFloat = lambda n: type(n) in [int,float]
21st Nov 2019, 7:50 PM
Choe
Choe - avatar
22nd Nov 2019, 1:14 AM
Rik Wittkopp
Rik Wittkopp - avatar