I'm currently learning Python, and at the moment I'm writing a simple grocery list program.

At one point in the program, the user is asked how many items are on their shopping list. What I want to do is take the number that the user inputs (lets say it's 5), and the program then requests input from the user for 5 different grocery items (item name and cost). For the time being I've just added a bunch of code to accept values for 1 - 10 items, but I'd like to have a small chunk of code that can accept any value and request the appropriate amount of data. I'm terrible at explaining this, but basically if the user inputs 5 for their number of items, they're required to input information for 5 items. If they put 30 for their number of items, they're required to input information for 30 items. So when printed on their screen it would look something like:

How many items on your list? 5

Item 1 Name: Bananas
Item 1 Cost: $1.25

Item 2 Name: Pasta
Item 2 Cost: $ ..

All the way through Item 5 (or whatever number they gave the program).

I would appreciate any help, and sorry if my explanation was redundant / confusing.

Recommended Answers

All 14 Replies

It would be easier to help you in your problem if you posted your code and error message you are getting.

I'm not getting an error message, my temporary 'solution' is working fine.

What I'm asking is HOW I could code the program to handle any value without having a section of code for each value.

For example, right now my code is pretty much:

while item_amount:
    itemnumber = raw_input('How many items on your list?: ')
    try:
        number = int(itemnumber)
        if number == 1:
        codecodecodecode
        codecodecodecode

        elif number == 2:
        codecodecodecode
        codecodecodecode

    except ValueError:
        print " "
        print "Please enter a number."
        item_amount = True

That's (obviously) not exactly what my code looks like, but it's to give you an idea. I basically have if / elif code for every value from 1 - 10, and I'm looking for a simpler solution.

Look into dictionary.
Example Banana is the key and price is the value.
So if you call key you get price.

Here is a code example you can look.
This code will run in a loop given bye argument number given to function.
And save result to a dictionary,that you can use later.

def question(times=None):
    '''Dok string some info about code'''
    grocery_ditch = {}
    print 'Enter grocery item and price'
    for i in range(times):
        key = raw_input('item %d' % int(i+1))
        value = int(raw_input('price'))
        grocery_ditch[key] = value
    print grocery_ditch  #Or use return to get result out of function

question(3)

Look into dictionary.
Example Banana is the key and price is the value.
So if you call key you get price.

Here is a code example you can look.
This code will run in a loop given bye argument number given to function.
And save result to a dictionary,that you can use later.

def question(times=None):
    '''Dok string some info about code'''
    grocery_ditch = {}
    print 'Enter grocery item and price'
    for i in range(times):
        key = raw_input('item %d' % int(i+1))
        value = int(raw_input('price'))
        grocery_ditch[key] = value
    print grocery_ditch  #Or use return to get result out of function

question(3)

Ok say so lets say I had this line:

test = int(raw_input('How many items on your shopping list? '))

How would I get that function to run "test" times?

Edit: Nevermind, figured it out.

times = int(raw_input('How many items on your shopping list? '))

def question(times):
    grocery_list = {}
    print
    print 'Enter grocery item and price.'
    print
    for i in range(times):
        key = raw_input('Item %d Name: ' % int(i+1))
        value = raw_input('Item %d Price: $' % int(i+1))
        print
        grocery_list[key] = value
    print grocery_list

question(times)

Ok so now that the user entered the information and it's stored in a dictionary, how can I 'access' each piece of information individually.

Let's say they entered information for 4 items, so that would make grocery_list =

{'Pasta': '2.25', 'Soda': '3.55', 'Bananas': '1.09', 'Cereal': '2.75'}

How could I print those names in a list and their total cost like so:

Grocery List

Bananas
Pasta
Cereal
Soda

The total cost of your grocery list is $9.64

How about:

grocery_list = {'Pasta': '2.25', 'Soda': '3.55', 'Bananas': '1.09', 'Cereal': '2.75'}
print ("""
Grocery List

%s

The total cost of your grocery list is $%.2f""" %
       ('\n'.join(grocery_list),
        sum(map(float, grocery_list.values()))
        ) )

How about:

articles = {'Pasta': '2.25', 'Soda': '3.55', 'Bananas': '1.09', 'Cereal': '2.75'}
print ("""
Grocery List

%s

The total cost of your grocery list is $%.2f""" %
       ('\n'.join(articles),
        sum(float(articles[key]) for key in articles)
        ) )

I got an invalid syntax error for the comma after join(articles).

I'm using Python 2.7 if that has anything to do with it. I fixed the print function to work with 2.7 but I don't know what else is different between 2.x and 3.

Only the print implementation.

You can do

from __future__ import print_function

and keep the 3.x print style.

Cheers and Happy coding

Alright thanks guys, got everything working!

Edit: I lied. Might be able to figure out this last problem, if not I'll post it.

Current edit of my code with map is running OK in 2.7, I rechecked. Also the version in your quote is OK in 2.7. Copy paste error?

Current edit of my code with map is running OK in 2.7, I rechecked. Also the version in your quote is OK in 2.7. Copy paste error?

Yeah your code is working fine now, the problem is in:

grocery_list = {'Pasta': '2.25', 'Soda': '3.55', 'Bananas': '1.09', 'Cereal': '2.75'}

It should equal whatever was entered by the user in this function:

def item_entry(items):
    grocery_list = {}
    print ('\nEnter grocery item and price.\n\n')
    for i in range(items):
        key = raw_input('Item %d Name: ' % int(i+1))
        value = raw_input('Item %d Price: $' % int(i+1))
        print()
        grocery_list[key] = value
    os.system("cls")  

item_entry(items)

Those values I gave were just an example of user input.

Return value of that function is None as there is no return statements. grocery_list is local variable so the value of it is lost.

Return value of that function is None as there is no return statements. grocery_list is local variable so the value of it is lost.

Ah ok, I get it.

I set grocery_list as a global variable and got rid of this line:

grocery_list = {'Pasta': '2.25', 'Soda': '3.55', 'Bananas': '1.09', 'Cereal': '2.75'}

So now everything is working as intended.

Thanks again guys, appreciate the help!

More correct answer though is to return the grocery_list and do:

grocery_list = item_entry(items)
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.