Week 3 : integers,floating points

Hi
couldn’t understand the difference between these two.Can some one help me understand whats wrong with code 1?
#code 1 with error:
hours_per_day = ‘2.5’
hours_per_week = float ( hours_per_day *7 )
print (my_name +’ is studying at '+ str (hours_per_week ) + ‘hours’ )

#code 2 without error:
hours_per_day = ‘2.5’
hours_per_day= float ( hours_per_day )
hours_per_week = float ( hours_per_day *7 )
print (my_name +’ is studying at '+ str (hours_per_week ) + ‘hours’ )

  1. You’re multiplying a string 2.5 directly with 7, this will give you 2.52.52.52.52.52.52.5 as a string. Which can never be converted into float type.
  2. You’re doing it the right way by first converting string into float and then multiplying it with 7.

still not clear: why cant I convert these two lines into a single line:
hours_per_day= float ( hours_per_day )
hours_per_week = float ( hours_per_day *7 )

You can do so by using:

hours_per_week = float(float(hours_per_day)*7)

Thanks. It would be really helpful if you could explain the difference

The snippet that you shared, you were at first multiplying a string with an integer. Which would give you a string that can never be converted into float type, as it had multiple decimals.
The snippet that i shared, it first converts 2.5 to float, and then multiplies it with 7
The same can also be done as :

hours_per_week = float(hours_per_day)*7
1 Like