Forum Archive

Pythonista While Loop Print Traceback Error

Zanmyk

So i’ve been having trouble with making a while loop in Pythonista and it stems from while not being recognized as a variable, what could possibly be done to fix this or make significant progress in fixing this?

cvp

@Zanmyk could you post your code?

Zanmyk

Insert Code Here
```# ---- Imports -----

from random import choice

------ A. Functions ------

A1. Choose dishes

def chooseDishes(days):
    while len(myMenu) < int(days): #this is the only part of the code with an error


chosenDish = choice(foodWeLike)
     if chosenDish not in myMenu
       myMenu.append(chosenDish)
    print("Done! Here's your menu…")
print()
for dish in myMenu:
print(dish)
print()
print("Out of all these days, my favorite has to be... " + choice(myMenu))

A2. Build Shopping list

def buildShoppingList():
myShoppinglist = []
if "Pizza" in myMenu:
myshoppinglist.append(pizza)
if "Beef Burgers" in myMenu:
myshoppinglist.append(beefBurgers)
if "Pork Stir Fry" in myMenu:
myshoppinglist.append(porkStirFry)
if "Chicken Fajitas" in myMenu:
myshoppinglist.append(chickenFajitas)
if "Orange Chicken" in myMenu:
myshoppinglist.append(orangeChicken)
if "Lasagna" in myMenu:
myshoppinglist.append(lasagna)
for dish in myShoppinglist:
for ingredient in dish:
print(ingredient)

------ B. Lists ----------

foodWeLike = ["Pizza", "Beef Burgers", "Pork Stir Fry", "Chicken Fajitas", "Orange Chicken", "Lasagna",]

pizza = ["Pizza Base", "Tomato Sauce", "Cheese", "Pepperoni"]
beefBurgers = ["Beef Patties", "Burger Rolls", "Lettuce", "Tomatoes", "Relish"]
porkStirFry = ["Pork loin", "Peppers", "Onion", "Hoi Sin Sauce", "Noodles"]
chickenFajitas = ["Chicken Breast", "Red Peppers", "Onion", "Fajita Kit"]
orangeChicken = ["Chicken Breast", "Orange Sauce", "Panko crumbs"]
lasagna = ["Cooked Lasagna Noodles", "Traditional Italian Cheese", "Parmesean Cheese", "Mozzarella Cheese", "Eggs", "Ground Beef", "Ricotta Cheese"]

myMenu = []
myShoppinglist = []

1. How many days to plan?

print("Hello, I'm Munch, i'll help you to plan your dinner menu...")

answer = input("How many days would you like me to plan? ")

print("OK, I'm going to plan " + answer + " dinner(s) from your favorite meals list")

2. Choose dishes

chooseDishes(answer)

3. Build shopping list?

answer = input("Would you like a shopping list for this menu?")

if answer == 'y':
buildShoppinglist()
else:
print("You got it! Bye for now 🙂")
```

JonB

please edit your post, select the code, the tap the little icon, so it adds the 3 backticks before and after your code.

then, run your code, and use Print Traceback to print the full error and paste it back here.

cvp

@Zanmyk Move these two lines just before your functions definitions

myMenu = []
myShoppinglist = []

def chooseDishes(days):
  ...

And missing : at end of

     if chosenDish not in myMenu:

Good luck and next time, follow advice of @JonB , it helps us

Zanmyk
# ---- Imports -----

from random import choice

# ------ A. Functions ------

# A1. Choose dishes

def chooseDishes(days):
 while len(myMenu) < int(days): 
     ^ #so it seems there's an invalid character in my code and well, i'm at loss trying to figure out what to do with this.
  chosenDish = choice(foodWeLike)
   if chosenDish not in myMenu:
            myMenu.append(chosenDish)
    print("Done! Here's your menu…")
        print()
        for dish in myMenu: 
                print(dish)
        print()
        print("Out of all these days, my favorite has to be... " + choice(myMenu))






# A2. Build Shopping list

def buildShoppingList():
      myShoppinglist = []
        if "Pizza" in myMenu: 
        myshoppinglist.append(pizza)
        if "Beef Burgers" in myMenu: 
        myshoppinglist.append(beefBurgers)
        if "Pork Stir Fry" in myMenu: 
        myshoppinglist.append(porkStirFry)
        if "Chicken Fajitas" in myMenu: 
        myshoppinglist.append(chickenFajitas)
        if "Orange Chicken" in myMenu: 
        myshoppinglist.append(orangeChicken)
        if "Lasagna" in myMenu: 
        myshoppinglist.append(lasagna)
        for dish in myShoppinglist:
            for ingredient in dish:
                  print(ingredient)

# ------ B. Lists ----------

foodWeLike = ["Pizza", "Beef Burgers", "Pork Stir Fry", "Chicken Fajitas", "Orange Chicken", "Lasagna",]

pizza = ["Pizza Base", "Tomato Sauce", "Cheese", "Pepperoni"]
beefBurgers = ["Beef Patties", "Burger Rolls", "Lettuce", "Tomatoes", "Relish"] 
porkStirFry = ["Pork loin", "Peppers", "Onion", "Hoi Sin Sauce", "Noodles"]
chickenFajitas = ["Chicken Breast", "Red Peppers", "Onion", "Fajita Kit"]
orangeChicken = ["Chicken Breast", "Orange Sauce", "Panko crumbs"]
lasagna = ["Cooked Lasagna Noodles", "Traditional Italian Cheese", "Parmesean Cheese", "Mozzarella Cheese", "Eggs", "Ground Beef", "Ricotta Cheese"]

        myMenu = []
        myShoppinglist = []

# 1. How many days to plan?

print("Hello, I'm Munch, i'll help you to plan your dinner menu...")

answer = input("How many days would you like me to plan? ")

print("OK, I'm going to plan " + answer + " dinner(s) from your favorite meals list")

# 2. Choose dishes

chooseDishes(answer)


# 3. Build shopping list?

answer = input("Would you like a shopping list for this menu?")

if answer == 'y':
      buildShoppinglist()
else:
      print("You got it! Bye for now 🙂")
cvp

@Zanmyk And?

JonB

If you have an error you don't understand, print the traceback, and paste back here!

I will say that in your first code you had a line reading:

---------------

Which of course is not valid python.

In your second example you wrote

   ^ # some comment...

The leading carrot before the comment character is also invalid python.

I'm wondering if you just forgot the leading comment in both cases.

ccc

Just for fun... Things that you can do with a dict of foods instead of lists of foods...

from typing import Dict, Tuple

foodWeLike: Dict[str, Tuple[str]] = {
    "Pizza": ("Pizza Base", "Tomato Sauce", "Cheese", "Pepperoni"),
    "Beef Burgers": ("Beef Patties", "Burger Rolls", "Lettuce", "Tomatoes", "Relish"),
    "Pork Stir Fry": ("Pork loin", "Peppers", "Onion", "Hoi Sin Sauce", "Noodles"),
    "Chicken Fajitas": ("Chicken Breast", "Red Peppers", "Onion", "Fajita Kit"),
    "Orange Chicken": ("Chicken Breast", "Orange Sauce", "Panko crumbs"),
    "Lasagna": ("Cooked Lasagna Noodles", "Traditional Italian Cheese", "Parmesean Cheese",
                "Mozzarella Cheese", "Eggs", "Ground Beef", "Ricotta Cheese")}

print('Food we like is', ', '.join(sorted(foodWeLike)))

for food, ingredients in foodWeLike.items():
    print(f"{food} contains {', '.join(sorted(ingredients))}")

print('Food containing Chicken Brest:', ', '.join(food for food, ingredients in
                                                  foodWeLike.items()
                                                  if "Chicken Breast" in ingredients))

print('Food containing any cheese:', ', '.join(food for food, ingredients in
                                               foodWeLike.items()
                                               if any('cheese' in ingredient.lower()
                                                      for ingredient in ingredients)))
cvp

@Zanmyk
And your myMenu variable is still not known in your erroneous line because you did not move it's definition myMenu = [] before it's usage

JonB

cvp, that part looked ok to me, though I didn't try to run it.

defs can reference variables that will exist in the scope of the function def, at the time it is called. As long as it exists before the functions are called.

Maybe not the best practice for clarity, but otherwise seems ok to me. I think he just forgot the comment symbol?

def a():
   print(b)
try:
   a()
   print ('success')
except NameError:
   print('fail')

b=1
try:
   a()
   print ('success.')
except NameError:
   print('fail')
cvp

@JonB I agree, but after the original post, and after corrections of missing # and :
I tested his code and got an error on the first line using this variable until I move these lines.

Édit: But now, without moving these lines and after some indent corrections, it runs ok

cvp

I think he puts the leading carrot only to show where he got an error
Else, it is so obvious