如何在python中彼此相邻编写两个函数?

[大家好,我有一个问题,但我解决不了:(

这是我的代码,我希望我的输出在上载的图像中看起来像。谢谢大家] 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,\
          format(c,".2f"))

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

the output

liweisb 回答:如何在python中彼此相邻编写两个函数?

如果要对齐值,可以指定长度和对齐方式。 参见{{3}}

在上述@ 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)
,

生成器非常适合: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,".1f"))

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

然后您可以一次遍历两者:

for left,right)
本文链接:https://www.f2er.com/3168153.html

大家都在问