尝试在python中格式化return语句

时间:2017-02-07 02:30:47

标签: python-3.x

import random

def main():
    print('MILES\t KILOMETERS')
    print('-----\t ----------') 
    m = float
    k = float
    for limit in range (1,11): #Keeps the table from going on forever
      final = randyGen(m, k)    #Arguments to function
      print(final)


def randyGen(miles, kilos): #Function to produce miles and kilometers
    miles = random.randint(10,60)
    kilos = miles * 1.60934
    return miles, kilos



main()

input('\n\nPress ENTER to exit.')

我需要里程语句停止在2位小数点,公里位置停在5位。我试图将格式添加到randyGen以及主函数中,但都没有工作。

1 个答案:

答案 0 :(得分:0)

我对你的输出略有改动

import random

def main():
    print('MILES\t KILOMETERS')
    print('-----\t ----------') 
    m = float
    k = float
    for limit in range (1,11): #Keeps the table from going on forever
      final = randyGen(m, k)    #Arguments to function
      print('Km: %3.5f' %final)


def randyGen(miles, kilos): #Function to produce miles and kilometers
    miles = random.randint(10,60)
    print('Miles: %2.2f' %miles)
    kilos = miles * 1.60934
    return kilos

if __name__ == '__main__':
    main()

结果

MILES    KILOMETERS
-----    ----------
Miles: 46.00
Km: 74.02964
Miles: 16.00
Km: 25.74944
Miles: 12.00
Km: 19.31208
Miles: 20.00
Km: 32.18680
Miles: 27.00
Km: 43.45218
Miles: 12.00
Km: 19.31208
Miles: 39.00
Km: 62.76426
Miles: 39.00
Km: 62.76426
Miles: 38.00
Km: 61.15492
Miles: 30.00
Km: 48.28020