[英]How to print at the same line of an input?
output 應該是這樣的:
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.
我這樣做了:
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.")
但顯示的 output 是:
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.
我需要 10.1 和打印在同一行
我怎樣才能做到這一點?
請檢查這段代碼。
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.")
這會給你如預期的那樣
試試這個格式
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.")
使用input()
function 這實際上是不可能實現的,但是您可以使用ANSI 轉義序列,如下所示:
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.")
\33[1A
序列會將 cursor 向上移動一行,而\33[{offset}C
會將其向右移動第二個輸入值的長度。
#試試這段代碼,如果你想把變量放在那里,也不要害怕把 (f' 放在打印行的開頭!
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.')
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.