0

Python

Code - 1

hrs = input("Enter Hours:")
rate = input("Enter Rate:")
pay = float(hrs * rate)
    print("Pay:", pay)

Code - 2

 hrs = input("Enter Hours:")
 rate = input("Enter Rate:")
 pay = float(hrs) * float(rate)
    print("Pay:", pay)

While executing the Code - 1 I'm getting the following error - "TypeError: can't multiply sequence by non-int of type 'str' on line 5" but the Code - 2 is completely fine and running. I just want to know that is there really any difference between these 2 codes? If yes, then what is it? (I'm a novice who just started with programming )

Pratik Raj
  • 11
  • 3
  • "input" always returns a string and evaluation of expressions (like the one to the right of = in third lines) follows the usual order similar to arithmetic (here: from inside parentheses to outside). – Michael Butscher Apr 10 '20 at 15:50
  • 1
    function `input` returns a string. So in code 1 it would be like saying `float("45.25" * "25.81")` thus asking to multiply two strings and convert the result to a float. – DarrylG Apr 10 '20 at 15:50

2 Answers2

2

This code float(hrs * rate) cannot work because hrs and rate are both strings. What would you expect to be the result of "hello" * "world"?

When you do float(hrs) * float(rate) on the other hand, you are multiplying the result of two calls to float - in other words, you are multiplying two floats.

Lydia van Dyke
  • 2,466
  • 3
  • 13
  • 25
0

In the first code, you multiply 2 variables first, then convert it to float, but if one of them is str (or both in this case), then there will be an error.

In the second code, you convert each of them to float before multiplying, that's why there is no error at all

Binh
  • 1,143
  • 6
  • 8