0

im trying to export two lists to an excel file using pandas, but i cannot append my data using this method.

product_list1 = ["apple", "pear", "oragne", "melon"]
product_list2 = ["bread", "sugar", "flour", "salt"]
list_codes = []
list_numbers = []

def quantity_check(list_type, list_number):
    choise = input("Quantity:")
    if choise in range(1, 99):
        list_numbers.append(choise)
        list_codes.append(list_type[list_number])
quantity_check(product_list1,0)
quantity_check(product_list1,1)
quantity_check(product_list1,2)
quantity_check(product_list1,3)

print (list_numbers)
print (list_codes)

This outputs the two empty lists for some reason.

2 Answers2

1

The input function returns a string.
You first need to cast the result into a number before checking if the choice is contained in the range.

def quantity_check(list_type, list_number):

    choise = input("Quantity:")
    try:
        choice_numeric = int(choise)
        if choice_numeric in range(1, 99):
            list_numbers.append(choise)
            list_codes.append(list_type[list_number])
    except:
        print("The choice is not a number")

I added a try catch block in order not to fail if the user enters an input that is not a number

Luca
  • 11
  • 3
  • The exception handling is a good idea. One thing to note is that the code appends `choise` instead of `choice_numeric` so the list would contain strings rather than integers. – Prins Aug 27 '22 at 16:27
1

You should convert the user input to an integer as the input function returns a string by default:

def quantity_check(list_type, list_number):
    choice = int(input('Quantity:'))

    if choice in range(1, 99):
        list_numbers.append(choice)
        list_codes.append(list_type[list_number])

If you would like to add some exception handling then you can do so using try...except as follows:

def quantity_check(list_type, list_number):
  try:
    choice = int(input('Quantity:'))
  
    if choice in range(1, 99):
      list_numbers.append(choice)
      list_codes.append(list_type[list_number])
      
  except ValueError:
    print('Quantity should be numerical.')
Prins
  • 1,051
  • 1
  • 6
  • 9
  • Better omit the `global`. It has no effect here and [isn't considered good practice](https://stackoverflow.com/a/19158418/15873043) anyway. – fsimonjetz Aug 27 '22 at 17:03
  • 1
    @fsimonjetz I have updated the answer to omit global as it is not required in this case as the global variables are not being reassigned. – Prins Aug 27 '22 at 17:13