Home>

Thank you for viewing m (_ _) m
I am a beginner in programming and studying python while reading a book, but an error (can't multiply sequence by non-int of type'float') I ended up.
9th line of chap461.py ... I want to call the add_charge function of the module (chap4func) by specifying the variable bill
Line 10: I want to call the create_mail function of the module (chap4func) by specifying the key (name) of the variable rec and the variable bill
Thanks for your answer.

Error message
Traceback (most recent call last):
  File "/Users/anonymous/Documents/chap461.py", line 9, in<module>
    bill = chap4func.add_charge (bill)
  File "/Users/anonymous/Documents/chap4func.py", line 10, in add_charge
    return int (bill * 1.07)
TypeError: can't multiply sequence by non-int of type 'float'
Applicable source code
chap4func.py
def create_mail (recv, bill):
    tmp = '' 'Mr. {}
im Saito
i need {} yen
'' '
    msg = tmp.format (recv, bill)
    print (msg)
def add_charge (bill):
    return int (bill * 1.07)
chap461.py
import chap4func
data = [
{'name': 'yamamoto', 'bill': '40000', 'crg': True},
{'name': 'takahashi', 'bill': '25000', 'crg': False}
 ]
for rec in data:
    bill = rec ['bill']
    if rec ['crg']:
        bill = chap4func.add_charge (bill)
    chap4func.create_mail (
    rec ['name'], bill)
  • Answer # 1

    bill is a string type. Try rewriting data as follows.

    data = [
        {'name': 'yamamoto', 'bill': 40000, 'crg': True},
        {'name': 'takahashi', 'bill': 25000, 'crg': False}
    ]

    It is also ant to leave it as a string and convert it to int when it is needed.

    Error reproduction
    >>>'spam' * 3
    'spamspamspam'
    >>>
    >>>'spam' * 3.14
    Traceback (most recent call last):
      File "<stdin>", line 1, in<module>
    TypeError: can't multiply sequence by non-int of type 'float'

  • Answer # 2

    I don't know if the book is wrong or just a typo,

    def add_charge (bill):
        return int (bill) * 1.07

    seems correct.

    If you perform a multiplication operation on a character string (not limited to built-in sequence types such as list and tuple), you can get a repeated version of the contents. The cause of the error is that you have to apply ...

    >>>"hoge" * 2
    'hogehoge'
    >>>"hoge" * 1.5
    Traceback (most recent call last):
      File "<stdin>", line 1, in<module>
    TypeError: can't multiply sequence by non-int of type 'float'

    In any case, I think the question code is different from the intended operation.

    I want to convert the string to a number and then multiply it by 1.07.