1

I'm a little stuck at trying to figure out this python syntax (I know is going to be a super simple fix too). What I want to do is say

if unit is not g, ml, or kg then return a flag. I tried:

if unit != ('g' or 'ml' or 'kg'):
return 1

If unit is set to g, the program doesn't return 1

If unit is set to ml, or kg, the program returns 1.

How do I make it so I can simply, and clearly say to return 1 if unit is not g, ml, or kg?

edit: I know I can do

if unit != 'g':
if unit != 'ml':
if unit != 'kg':
return 1

but this is 3 lines of code where I think 1 line can solve it.

  • `return unit not in ('g', 'ml', 'kg')`. (That will return `True`, not `1`, but for most purposes they're equivalent, and it seems like you intend for this to be a boolean flag anyway.) – Samwise May 31 '22 at 23:58
  • Do you add an indentation before `return 1`? – Yuchen Ren May 31 '22 at 23:59
  • yes there is an indent before the return 1, I'm a little lost on formatting the indent for the post. I apologize for that. – Robert Munroe Jun 01 '22 at 00:09

1 Answers1

1

Note: You can't return a value from an if statement, you can only return a value from a function.

I would create a list of the units:

units = ['g','ml','kg']

Then test if the unit is in the list or not.

unit = 'g'
if unit in units:
    print(True)
else:
    print(False)
Jeff
  • 71
  • 5