user7069258 user7069258 - 4 months ago 29
Python Question

Alternative to defining numbers

I want the user to input in 8 digits followed by a space and another single digit number. If the entered number is part of my pre made list, then the program would output the name of that item and how much of the user wants to purchase.

Here is my code

orange = 12345670
pineapple = 87654325
items = [orange, pineapple]
print("Input a 8 digit number followed by a space and a 1 digit number")
print("E.g. 12345670 2")
c = input("Number: ")
c1 = int(c[0])
c2 = int(c[1])
c3 = int(c[2])
c4 = int(c[3])
c5 = int(c[4])
c6 = int(c[5])
c7 = int(c[6])
c8 = int(c[7])
c9 = int(c[9])
c10 = (str(c1)+str(c2)+str(c3)+str(c4)+str(c5)+str(c6)+str(c7)+str(c8))
if str(c10) not in items:
print("Item not found")
print("That would be "+str(c9)+" of "+str(c10))

The problem is that,

  • It always outputs
    Item not found

  • If it does work, it outputs
    That would be *x* of number inputted
    instead of
    That would be *x* of orange/pineapple


If you are going to use these numbers as lookups, I would store it in a dict, which is what that data structure is for.

foods = {12345670 : 'orange',
         87654325 : 'pineapple'}

Then you could do something like this

c = '12345670 2'
item, count = c.split()
item = int(item)

if item in foods:
    print('That would be {} of {}'.format(count, foods[item]))
    print('Item not found')


That would be 2 of orange