Python Forum

Full Version: Outputting a float value in a print() statement
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
For some reason, it's not letting me concatenate a float in my print statement on line 6:

#!/usr/bin/env python3
#BasicUserInterface.py

#MACH 1 = 761.2071 mph
#1 mph = MACH 0.0013

def calculateMACH(mph):
    mach = mph * 0.0013
    return mach

def calculateTime(mph, distance):
    time = distance / mph
    return time

def calculateMinutes(mph, distance):
    time = distance / mph
    milesPerMinute = time / 60
    return milesPerMinute

def main():
    choice = "y"
    while choice.lower() == "y":
        mph = float(input("Enter speed in mph:"))
        distance = float(input("Enter number of miles to destination:"))        

        mach = calculateMACH(mph)
        time = calculateTime(mph, distance)
        milesPerMinute = calculateMinutes(mph, distance)

        if mph > 761.2071:
            print("You are traveling faster than the speed of sound!")

        print("You are traveling at MACH " + str(mach))
        print("At that speed, you should reach your destination in " +
              str(round(time, 2)) + " hours, or " +
              str(round(milesPerMinute, 2) + " minutes."))

        choice = input("Do you want to continue? (y/n)")
        print()

    print("Bye!")

if __name__ == "__main__":
    main()
Error:
===== RESTART: I:/Python/Python36-32/SamsPrograms/BasicUserInterface.py ===== Enter speed in mph:60 Enter number of miles to destination:60 You are traveling at MACH 0.078 Traceback (most recent call last): File "I:/Python/Python36-32/SamsPrograms/BasicUserInterface.py", line 44, in <module> main() File "I:/Python/Python36-32/SamsPrograms/BasicUserInterface.py", line 36, in main str(round(milesPerMinute, 2) + " minutes.")) TypeError: unsupported operand type(s) for +: 'float' and 'str'
What's wrong?
Your closing bracket is not in place. See the prev. str() function.

It's better though to use string formatting instead of concatenation.
print("At that speed, you should reach your destination in {} hours, or {} minutes.".format(str(round(time, 2)), str(round(milesPerMinute, 2)))
(Jan-11-2018, 07:32 AM)wavic Wrote: [ -> ]It's better though to use string formatting instead of concatenation.
Python Code: (Double-click to select all)
1

print("At that speed, you should reach your destination in {} hours, or {} minutes.".format(str(round(time, 2)), str(round(milesPerMinute, 2)))

well, it is good to use string formatting in its full power

>>> hours = 1.23456
>>> print('you will reach your destination in {:.3f} hours, or {:.2f} minutes'.format(hours, hours*60))
you will reach your destination in 1.235 hours, or 74.07 minutes
format specification mini language