Python Forum

Full Version: For Loops Driving Me Insane
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Trying to figure out how for loops work and I'm really struggling.

I'm able to make a program that will let me pick a single piece of candy and tell me how many calories are in that single piece of candy, but what I want is for the program to ask how many total pieces of candy I had and then add up all the calories for that candy and then display a total amount of calories consumed. I feel like I'm close to doing that, but nothing I have tried works. Here's my code.

I've hashed out the entries at the top as I think I need them to ask how many pieces of candy I had.

multi = int(input ("How many things did you eat?: "))
for num in range(multi):
    candy = input("""
1. Snickers Ice Cream Bar
2. Nutter Butters
3. Twix
4. Twizzlers
5. Ice Cream Sandwich

Which Candy Did You Eat? (Enter Number): """)

    candy_calories = {
        "1": 100,
        "2": 250,
        "3": 600,
        "4": 400,
        "5": 325,

}
output = []
total_candy = []
total = 0
for cal in candy:
    output = candy_calories.get (cal, "!")
    total_candy.append(output)
    total += int(total_candy)
print(total)
Naturally, this fails, and normally I'd be looking for help rather than a straight up answer, but I've been working on this for hours and I'm Wall Wall Wall and I'm ready for somebody to just tell me the answer with the hopes that I can learn from it, and then do it again, this time without help.
Where are you saving input? candy only reference the last input.

Why does output = candy_calories.get(cal, "!")? candy_calories values are all numbers. Why do you want to return a string if cal is not a key in the dictionary?

Python has a built in function that will give you the sum of a list of numbers.
(Apr-29-2022, 10:12 PM)deanhystad Wrote: [ -> ]Where are you saving input? candy only reference the last input.

Why does output = candy_calories.get(cal, "!")? candy_calories values are all numbers. Why do you want to return a string if cal is not a key in the dictionary?

Python has a built in function that will give you the sum of a list of numbers.

That's what I'm trying to figure out. What would be the correct way to save the input for the number of total pieces of candy consumed so that I can later add them up for total calories?

Is output = candy_calories.get (cal, "!") converting to a string? I thought it was just grabbing the values of the dictionary entries.
values = []
for i in range(10):
    values.append(i)
print(values)
Output:
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Modify this to have an input and append the input value.
# You don't really need numbers for the choccy bars

sweets = {'Snickers Ice Cream Bar': 100, 'Nutter Butters': 200,  'Twix': 300, 'Twizzlers': 400, 'Ice Cream Sandwich': 500}
print('We have these very fattening choccy bars to help you put on weight, you fat lump or enter q ... ')
for key in sweets.keys():
    print(key)

mychoices = []
while True:
    print('Enter q to quit.')
    choice = input('Choose a choccy from the list above you fat slob ... ')
    if choice == 'q':
        break
    mychoices.append(choice)

calories = 0
# add up the calories
Or if you just want to use the number as input,

sweets = {1: ['1 Snickers Ice Cream Bar', 100], 
          2: ['2 Nutter Butters', 200],  
          3: ['3 Twix', 300], 
          4: ['4 Twizzlers', 400], 
          5: ['5 Ice Cream Sandwich', 500]
          }
          
          
print('We have these very fattening choccy bars to help you put on weight, you fat lump or enter q ... ')

for key in sweets.keys():
    print(sweets[key][0])
 
calories = 0
mychoices = []

while True:
    print('Enter q to quit and show result.')
    choice = input('Choose a choccy number from the list above you fat slob ... ')
    if str(choice) == 'q':
        break
    mychoices.append(int(sweets[int(choice)][1]))


for c in mychoices:
    calories += c
    
print(f"calories = {calories}")
(Apr-30-2022, 04:59 AM)Pedroski55 Wrote: [ -> ]
# You don't really need numbers for the choccy bars

sweets = {'Snickers Ice Cream Bar': 100, 'Nutter Butters': 200,  'Twix': 300, 'Twizzlers': 400, 'Ice Cream Sandwich': 500}
print('We have these very fattening choccy bars to help you put on weight, you fat lump or enter q ... ')
for key in sweets.keys():
    print(key)

mychoices = []
while True:
    print('Enter q to quit.')
    choice = input('Choose a choccy from the list above you fat slob ... ')
    if choice == 'q':
        break
    mychoices.append(choice)

calories = 0
# add up the calories

LOL

Thank you.
My two cents

from tabulate import tabulate
from subprocess import call
import platform
clear = 'cls' if platform == 'win32' else 'clear'

sweets = {1: ['1 Snickers Ice Cream Bar', 100],
          2: ['2 Nutter Butters', 200],
          3: ['3 Twix', 300],
          4: ['4 Twizzlers', 400],
          5: ['5 Ice Cream Sandwich', 500]
          }
calories = 0
mychoices = []

choices = [[sweets[items][0]] for items in sweets.keys()]
call(clear)
while True:
    print(tabulate(choices, headers=['Items']))
    print()
    print('Choose a number from the list of items or q to quit\n')
    choice = input('>> ')
    if str(choice) == 'q':
        break
    try:
        call(clear)
        choice = int(choice)
        if isinstance(choice, int):
            try:
                mychoices.append(sweets[int(choice)][1])
                print(f'Calories Consummed: {sum(mychoices)}\n')

            except KeyError:
                call(clear)
                print('You can only choose from the menu.\n')
    except ValueError:
        call(clear)
        print('You can only enter whole numbers\n')
Output:
Calories Consummed: 900 Items ------------------------ 1 Snickers Ice Cream Bar 2 Nutter Butters 3 Twix 4 Twizzlers 5 Ice Cream Sandwich
I use while loops like this a lot, but I always need to get an answer that is in my list or dictionary.

It occurred to me this morning that you don't have a check to see if the entry is in your "shop".

Use dict.get(key) to check, or you will get an error later when adding the calories.

mychoices = []
while True:
    choice = input('Copy and paste a choccy from the list above you fat slob ... ')
    if choice == 'q':
        break
    while sweets.get(choice) == None:
        choice = input('You gotta choose a choccy from the list above you lipose lump ... ')
    mychoices.append(choice)
Don't forget to add this at the end of the program!

Quote:print('No wonder the bathroom scales always say, "Only one person at a time please!"')
The problem with this approach that i often see is lack of structure.
What i mean that eg loop,menu,calculation,display result...ect all get messed in together.
Structure can be using functions and let then menu only to menu stuff.
When calculate call a function outside of menu.
To give a example of what mean bye this.
def calories_calc(choice):
    candy_calories = {
        "1" : 100,
        "2" : 250,
        "3" : 600,
        "4" : 400,
        "5" : 325,
    }
    total = candy_calories.get(choice, 'Wrong vaule')
    print(f'Calories for this meal was {total}')
    input('Enter to retun to menu\n')

def candys():
    return '''\
    1. Snickers Ice Cream Bar
    2. Nutter Butters
    3. Twix
    4. Twizzlers
    5. Ice Cream Sandwich
    Q. Quit'''

def menu():
    while True:
        print(candys())
        choice = input('Enter your choice: ').lower()
        if choice in '12345':
            calories_calc(choice)
        elif choice == 'q':
           return
        else:
            print(f'Not a correct choice: {choice},try again')

if __name__ == '__main__':
    menu()
Test:
Output:
1. Snickers Ice Cream Bar 2. Nutter Butters 3. Twix 4. Twizzlers 5. Ice Cream Sandwich Q. Quit Enter your choice: 9 Not a correct choice: 9,try again 1. Snickers Ice Cream Bar 2. Nutter Butters 3. Twix 4. Twizzlers 5. Ice Cream Sandwich Q. Quit Enter your choice: 4 Calories for this meal was 400 Enter to retun to menu 1. Snickers Ice Cream Bar 2. Nutter Butters 3. Twix 4. Twizzlers 5. Ice Cream Sandwich Q. Quit Enter your choice: Q