Rene Delgado
Rene Delgado

Reputation: 77

How can I add string, then a variable, then a string again?

I am a novice Python user using 3.6 on Python IDLE. I wrote a program for school to calculate distance traveled depending on speed and time. I was able to get the program to display the numerical value of the distance which is great, but I would like it to also show "miles" after the numerical value that way it shows the unit of measurement. Here is my code:

def main():

#variable for speed
speed = 60

#variables for time
time1 = 5
time2 = 8
time3 = 12

#variables for distance
distance1 = time1 * speed
distance2 = time2 * speed
distance3 = time3 * speed

#display the distance equations
print ("The distance the car will travel in 5 hours is ", distance1 + " miles")
print ("The distance the car will travel in 8 hours is ", distance2 + "miles")
print ("The distance the car will travel in 12 hours is ", distance3 + "miles")

You can see where I tried to concatenate the first string, variable, and the second string. This breaks my code. Any help is appreciated!

Upvotes: 0

Views: 57

Answers (1)

zvone
zvone

Reputation: 19352

I suggest using the latest coolest formatting option implemented in Python, which is the formatted string literals:

print(f"The distance the car will travel in 5 hours is {distance1} miles")

But you may also do any of these:

print("The distance the car will travel in 5 hours is {} miles".format(distance1))
print("The distance the car will travel in 5 hours is %s miles" % distance1)
print("The distance the car will travel in 5 hours is", distance1, "miles")
print("The distance the car will travel in 5 hours is" + str(distance1) + " miles")

Upvotes: 1

Related Questions