How to print at the same line of an input?

Viewed 128

The output should be like this:

Please enter the miles you drove: 256
Please enter the gallons of gas you put in the tank: 
10.1 You got 25.346534653465348 mpg on that tank of gas.

I did this:

miles = float(input("Please enter the miles you drove: "))
gallons = float(input("Please enter the gallons you put in the tank: \n"))
print("You got", miles/gallons, "mpg on that tank of gas.")

but the output shown is:

Please enter the miles you drove: 256
Please enter the gallons you put in the tank: 
10.1
You got 25.346534653465348 mpg on that tank of gas.

I need for the 10.1 and the print to be on the same line

How can I do that?

4 Answers

This is not really possible to achieve with the input() function, but you can use ANSI escape sequences, if the terminal emulator you are using supports them. Here is an example:

miles = float(input("Please enter the miles you drove: "))
gallons = input("Please enter the gallons you put in the tank: \n")
offset = len(gallons)
gallons = float(gallons)
print(f"\33[1A\33[{offset}C You got { miles / gallons } mpg on that tank of gas.")

The \33[1A sequence will move the cursor up one line, and \33[{offset}C will move it to the right by the length of the second entered value.

Please check this out a piece of code.

miles= float(input("Please enter the miles you drove: "))

gallons = float(input("Please enter the gallons you put in the tank: "))
ratio = miles/gallons
print(" You got",ratio, "mpg on that tank of gas.")

This will give you as expected

Try this format

miles = float(input("Please enter the miles you drove: "))
gallons = float(input("""Please enter the gallons you put in the tank:
"""))
print(f"You got {miles/gallons} mpg on that tank of gas.")

#Give this code a try, also don't be afraid to put (f' at the beginning of your print lines if you want to put variables in there!

miles = float(input("Please enter the miles you drove: "))
gallons = float(input("Please enter the gallons you put in the tank: "))
divide = miles/gallons 
print(f'You got {divide} mpg on that tank of gas.')
Related