Home > Enterprise >  How to stop printing when the value is none (Python)?
How to stop printing when the value is none (Python)?

Time:08-07

I am trying to print a list of ingredients and the amount required for a recipe, but there could be anywhere from 1 ingredient to 15 from a list of random recipes. I want to account for them all, but I don't want the ingredients of the measurements to print if the value is None.

An example of what I am pulling from:

'strIngredient1': 'Coffee', 'strIngredient2': 'Grain alcohol', 'strIngredient3': None, 'strIngredient4': None

I was trying to say, if strIngredient equals None, pass, else print the ingredient and the measurement, but everything I try will continue to print None.

if "strIngredient1" == '':
        pass
    else:
        print(f"{df2['strIngredient1'][x]} {df2['strMeasure1'][x]}")

For example, but I don't want the None None to print:

Drink name: Zorro Sambuca 2 cl Baileys irish cream 2 cl White Creme de Menthe 2 cl None None None None None None None None None None None None None None None None None None None None None None None None

Any suggestions?

CodePudding user response:

So few things here:

  • You need to make sure you're indented properly as the else is not correct
  • You're checking for an empty string and not None
  • You're checking a string of strIngredient1 against an empty string which logically will never be True

You could try something like this:

if df2['strIngredient1'][x] is None:
    pass
else:
    print(f"{df2['strIngredient1'][x]} {df2['strMeasure1'][x]}")

This should pass through assuming the value in df2['strIngredient1'][x] is None.

Please refer to this to understand string comparison: https://flexiple.com/python-string-comparison/

Additional Output

This checks the strMeasure1 for None and then prints only strIngredient1 otherwise print both ingredient and measure.

if df2['strMeasure1'][x] is None:
    print(df2['strIngredient1'][x])
else:
    print(f"{df2['strIngredient1'][x]} {df2['strMeasure1'][x]}")

CodePudding user response:

Your condition has strIngredient1 between quotes so its checking if the string strIngredient1 matches an empty string (which will always output False, hence it always goes to the else block).

so your conditions needs to check if

df2['strIngredient1'][x] == None
  • Related