Как я могу написать две функции рядом друг с другом в Python? - PullRequest
0 голосов
/ 04 ноября 2019

[всем привет, у меня есть проблема, и я просто не могу ее решить: (

это мой код, и я хочу, чтобы мой вывод был похож на изображение, которое я загрузил. Спасибо всем] 1

def celiusToFahrenheit():
 print("Celsius\t\t\tFahrenheit")
 for c in reversed(range(31,41)):
    f=(9/5)*c+32
    print(c,"\t\t\t\t",\
          format(f,".1f"))

def fahrenheitToCelsius():
 print("Fahrenheit\t\t\tCelsius")
 for f in reversed(range(30,130,10)):
    c=(5/9)*(f-32)
    print(f,"\t\t\t\t",\
          format(c,".2f"))

https://i.stack.imgur.com/swcx6.png

выход

Ответы [ 2 ]

2 голосов
/ 05 ноября 2019

Если вы хотите выровнять значения, вы можете указать длины и выравнивания. См. https://docs.python.org/3/library/string.html#format-specification-mini-language

Добавление к ответу @ L3viathan выше ...

def celiusToFahrenheit():
    yield "{:^12} {:^12}".format("Celsius", "Fahrenheit")
    yield "-"*25
    for c in reversed(range(31, 41)):
        f = (9 / 5) * c + 32
        yield "{:12} {:>12}".format(c, format(f, ".1f"))


def fahrenheitToCelsius():
    yield "{:^12} {:^12}".format("Fahrenheit", "Celsius")
    yield "-"*25
    for f in reversed(range(30, 130, 10)):
        c = (5 / 9) * (f - 32)
        yield "{:12} {:>12}".format(f, format(c, ".1f"))


for left, right in zip(celiusToFahrenheit(), fahrenheitToCelsius()):
    print(left, "|", right)
1 голос
/ 04 ноября 2019

Генераторы подойдут для этого: вместо печати внутри функций, yield их строки:

def celiusToFahrenheit():
    yield "Celsius\t\t\tFahrenheit"
    for c in reversed(range(31, 41)):
        f = (9 / 5) * c + 32
        yield "{}\t\t\t\t{}".format(c, format(f, ".1f"))

def fahrenheitToCelsius():
    yield "Fahrenheit\t\t\tCelsius"
    for f in reversed(range(30, 130, 10)):
        c = (5 / 9) * (f - 32)
        yield "{}\t\t\t\t{}".format(f, format(c, ".1f"))

Затем вы можете перебирать оба сразу:

for left, right in zip(celiusToFahrenheit(), fahrenheitToCelsius()):
    print(left, "|", right)
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...