Reputation: 11
minutes = input("Enter number of minutes you want to convert to seconds: ")
print (minutes + " minutes is " + float(minutes) * 60 + " seconds.")
I'm getting this error can only concatenate str (not "float") to str
.
But if I use str
(instead of float
), it just prints the number of minutes inputted 10 times
eg 10101010....
Upvotes: 0
Views: 68
Reputation: 896
Although many answers have been added, but there is one more way other than those and as simple as all others, maybe even simpler. Just separate your different data-types
with a ,
:)
print (minutes , "minutes is" , float(minutes) * 60 , "seconds.")
Upvotes: 1
Reputation: 2054
The reason this doesn't work is that float(minutes) * 60
returns a float, which cannot be concatenated to a string. However, str(minutes) * 60
will multiply the STRING minutes by 60, which is also not what you want.
The solution is to convert to float to perform the calculation, then convert back to a string. See the code below:
minutes = input("Enter number of minutes you want to convert to seconds: ")
print (minutes + " minutes is " + str(float(minutes) * 60) + " seconds.")
If you input 3
, this code will print 3 minutes is 180.0 seconds.
Other ways of doing the same thing include:
Format strings:
print("%s is %0.1f seconds." % (minutes, float(minutes) * 60))
If you're using Python 3, f-strings:
print(f"{minutes} is {float(minutes) * 60} seconds.")
Upvotes: 0
Reputation:
You cannot concatenate string with a float Use a format string instead:
print("%s minutes is %f seconds" % (minutes, float(minutes) * 60))
10 minutes is 60.000000 seconds
Upvotes: 0
Reputation: 33
float(minutes) * 60 is not a string and therefore cannot be concatenated with with the rest of your string
consider converting float(minutes) * 60 to a string
minutes = input("Enter number of minutes you want to convert to seconds: ")
print (minutes + " minutes is " + str(float(minutes) * 60) + " seconds.")
Upvotes: 1