This question seems mind-boggling simple, yet I can't figure it out. I know you can check datatypes in python, but how can you set a conditional based on the datatype? For instance, if I have to write a code that sorts through a dictionary/list and adds up all the integers, how do I isolate the search to look for only integers?
I guess a quick example would look something like this:
y = [] for x in somelist: if type(x) == <type 'int'>: ### <--- psuedo-code line y.append(x) print sum(int(z) for z in y)
So for line 3, how would I set such a conditional?
Sets can be created by using the built-in set() function with an iterable object or a sequence by placing the sequence inside curly braces, separated by 'comma'. Type of elements in a set need not be the same, various mixed-up data type values can also be passed to the set.
The statement can be a single line or a block of code. #If the condition is true, the statement will be executed. num = 5 if num > 0: print(num, "is a positive number.") print("This statement is true.") #When we run the program, the output will be: 5 is a positive number. This statement is true.
How about,
if isinstance(x, int):
but a cleaner way would simply be
sum(z for z in y if isinstance(z, int))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With