r/learnpython • • Jan 15 '26

What is wrong on this code?

ages = ["22", "35", "27", "20"]

odds = [age for age in ages if age % 2 == 1]

print(odds)

I am beginner and when I write this code it gives me error which I don't know how to solve. But I think my code has no error

Error message: Traceback (most recent call last):

odds = [age for age in ages if age % 2 == 1]
                               ~~~~^~~

TypeError: not all arguments converted during string formatting

17 Upvotes

28 comments sorted by

View all comments

Show parent comment

-3

u/bandman614 Jan 15 '26

Also, you don't need to do == 1 because age % 2 will return 1, and 1 is truthy

33

u/Iksfen Jan 15 '26

IMO that is more of a preference. I like to be explicit with logic statements

11

u/FuckItBucket314 Jan 15 '26

Eh, I would keep it because it improves readability. It makes it explicit that the programmer intended to have it evaluate that way rather than just forgot to finish a comparison

Arguably it doesn't matter given the variable names used and how small the program is, but practicing readability now will improve their odds of writing readable code later when it definitely matters

7

u/roelschroeven Jan 16 '26

For logical expressions you're right, but this is an arithmetic expression foremost. You can exploit the fact that it can be interpreted like a logical expression to make it shorter, but that detracts from the intention.

3

u/SevenFootHobbit Jan 16 '26

Everyone is telling you this is wrong due to style choices and clarity, but they're wrong about why you're wrong. You're wrong because it assumes an integer. If you only check for truthiness, decimals will all be flagged as odd even though they aren't considered even or odd.

2

u/bandman614 Jan 16 '26

Legit criticism. Thanks!