Home > Software design >  Cannot append list with condition
Cannot append list with condition

Time:08-28

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.

CodePudding user response:

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.')

CodePudding user response:

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

  • Related