Home > OS >  How do I call a math function on each of the items obtained from a list from .split in an input?
How do I call a math function on each of the items obtained from a list from .split in an input?

Time:10-02

def bill_cal():
  split_amount = bill_amount_list * (1-cashback_rate) / person_split_no
  print(f"each person should pay {split_amount}.")

bill_amount = input("How much is the bill? You can enter multiple bills separated by comma.\n")
bill_amount_list = bill_amount.split(",")
cashback_rate = float(input("Is there any credit card cashback on the bills? 2% = 0.02\n"))
person_split_no = int(input("How many people are splitting the bill?"))
for bill in map(float, bill_amount_list):
  bill_cal()

I am trying to cast float on each item obtained from bill_amount.split(","), and perform the bill_cal() function, but got below error:

How much is the bill? You can enter multiple bills separarted by comma.
100,200
Is there any credit card cashback on the bills? 2% = 0.02
.02
How many people are splitting the bill?2
Traceback (most recent call last):
  File "main.py", line 10, in <module>
    bill_cal()
  File "main.py", line 2, in bill_cal
    split_amount = bill_amount_list * (1-cashback_rate) / person_split_no
TypeError: can't multiply sequence by non-int of type 'float'

CodePudding user response:

You are "multiplying" your bill_amount_list which is... well, a list. Sequences can be "multiplied" by int (meaning you will repeat the sequence), but not by float, hence your error.

Pass your bill to the function, and use it in the computation:

def bill_cal(amount):
    split_amount = amount * (1-cashback_rate) / person_split_no
#...
for bill in map(float,bill_amount_list):
  bill_cal(bill)

CodePudding user response:

You need to call the function with a local variable. Also it's good practice to check your input as well like this:

if item.isnumeric():
    'call the function'
  • Related