Error: "can’t Multiply Sequence by non-int of type 'float'"

Asked

Viewed 603 times

-2

I’m making this simple unit converter.

I need him to do:

  • Calculation of average speed in Km/h;
  • Print this result.

Then, in another function, I need to convert it to m/s and print the result again.

But I keep getting the following error in the Output of the code snippet that I attached below:

"can’t Multiply Sequence by non-int of type 'float'"

dist_k1= 169.0
time_h1= 0.6

dist_k2= 169.0
time_h2= 1.0

dist_k3= 300.0
time_h3= 1.5

def get_deltaV(dist_k, time_h):
    DeltaV = dist_k/time_h
    return DeltaV,"Km/h"

DeltaV1= get_deltaV(dist_k1, time_h1)
DeltaV2= get_deltaV(dist_k2,time_h2)
DeltaV3= get_deltaV(dist_k3,time_h3)

print(DeltaV1)
print(DeltaV2)
print(DeltaV3)

def get_ms (DeltaV):
    ms =DeltaV / 3.6
    return (ms,"m/s")

ms1 = get_ms(DeltaV1)
ms2 = get_ms(DeltaV2)
ms3 = get_ms(DeltaV3)

print(ms1)
print(ms2)
print(ms3)

Why is this error occurring? How can I fix it?

  • 3

    get_deltaV returns a tuple and this return you are passing as parameter to get_ms, where the value is multiplied by 3.6. It should not be get_ms(DeltaV1[0])?

  • It worked, thank you

  • But what would be the reason for that?

  • Of what? Of the error? What would be the expected result for the operation (10, 'km/h') / 3.6?

  • would then why are you sharing a tuple?

  • 1

    Exactly, as I commented initially when multiplication was still.

Show 1 more comment

1 answer

2


Comments have responded, but follow the code a little more pythonico:

from collections import namedtuple

routes = namedtuple('Routes', ['dist_k', 'time_h'])

routes = map(routes._make, [
    (169.0, 0.6),
    (169.0, 1.0),
    (300.0, 1.5)
])


def get_delta_v(*route):
    delta_v = route[0] / route[1]
    return delta_v, '{} Km/h'.format(delta_v)


def get_ms(delta_v):
    ms = delta_v / 3.6
    return ms, '{} m/s'.format(delta_v)


for route in routes:
    print(get_delta_v(*route)[1])
    print(get_ms(get_delta_v(*route)[0])[1])
  • 1

    Do you mind explaining the changes to me? I’m still learning Python so any explanation is already study.

  • Of course @Marcellofabrizio, you can use namedtuple whenever working with constants, in your case you have a fixed sequence that would be distance and time, so I used namedtuple, it brings some benefits ex: access via (dot Notation) or access as if it were a tupla,route.dist_k or route[0]. Another correction was in variable statement, python uses camelCase only in classes, variables or methods and Snake case _

Browser other questions tagged

You are not signed in. Login or sign up in order to post.