1

I'm looking for a way to assign a variable to a specific list item by having the same . Here is my code to enlighten things.

    count = 0
    beer = 5/100
    maltbeer = 7/100
    tablewine = 12/100
    fortifiedwine = 17/100
    aperitif = 24/100
    spirits = 40/100
    percentageCalc = 0
    for i in drinks:
        count =+ 1
        percentageCalc = percentageCalc + drinks[count]

The drinks are inputed into drinks and can vary depending on what was inputed.

i.e: drinks = ['beer', 'beer', 'spirits', 'maltbeer']

drinks is appended inputs only accepted as one of the variables seen further up.

2 Answers 2

1

Use a dictionary for the various types of drinks:

abv = {"beer": 5
       "maltbeer": 7,
       "tablewine": 12,
       "fortifiedwine": 17,
       "aperitif": 24,
       "spirits": 40}

percentage = 0

for drink in drinks:
    if drink in abv:
        percentage += percentageCalc + abv[drink]
    else:
        print("don't know about %s" % drink)

percentage /= 100.0

I also removed the /100 calculation from the individual items and added at the end, and implemented an error message in case the drink isn't known.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you very much for such a quick answer! My teacher having me concentrating on visualbullsh*t has made me forget so much about python. I was foolish to think I could just throw myself back in with ease.
0

You can use a dictionary to hold each of the drink types as a dictionary key. The value for each drink is its percentage.

drink_strength = {
    'beer': 5/100,
    'maltbeer': 7/100,
    'tablewine': 12/100,
    'fortifiedwine': 17/100,
    'aperitif': 24/100,
    'spirits': 40/100,
}

drinks = ['beer', 'beer', 'spirits', 'maltbeer', 'lemonade']
percentage_calc = sum(drink_strength.get(drink, 0) for drink in drinks)
print(percentage_calc)

Output

0.5700000000000001

The percentage is calculated by successively adding the percentages for each drink, or, if the drink is unknown, 0 percent is assumed.

N.B. Above code assumes Python 3. If using Python 2 you can add to the top of your file:

from __future__ import division

so that, e.g. 7/100 = 0.7 and not 0 as Python 2 integer division would produce.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.