如何在python中正确对齐我的答案?

时间:2015-03-16 21:22:40

标签: python alignment

当我输入第一个,第二个和最后一个数字,以及总和和平均值时,如何正确对齐我的答案。

#create function 
def list_sum(num_list):
    #calculate and print out the sum of numbers
    the_sum = 0
    for i in num_list:
        the_sum = the_sum + i
    return the_sum

#accept 3 numbers and store them in variables
input_1 = float(raw_input("Input a number: ")) 
input_2 = float(raw_input("Input a second number: ")) 
input_3 = float(raw_input("Input the last number: "))  

#take list of inputs
list_of_inputs = [input_1, input_2, input_3]

#calculate and print out the sum of numbers
sum_of_input = list_sum(list_of_inputs)
print("The sum: {:.2f}".format(sum_of_input))

#calculate and print out the average of the numbers
the_average = (sum_of_input)/(len(list_of_inputs))
print("The average: {:.2f}".format(the_average))

#calculate and print out the percent of the total that each number represents
for input_in_list in list_of_inputs:
    percent_total = input_in_list/sum_of_input
    print("The percent of the total of each number: {:.2f}".format(percent_total))

1 个答案:

答案 0 :(得分:0)

如果我正确理解了您的问题,您只需在参数中添加空格raw_inputprint

#create function
def list_sum(num_list):
    #calculate and print out the sum of numbers
    the_sum = 0
    for i in num_list:
        the_sum = the_sum + i
    return the_sum

#accept 3 numbers and store them in variables
input_1 = float(raw_input("Input a number:        "))
input_2 = float(raw_input("Input a second number: "))
input_3 = float(raw_input("Input the last number: "))

#take list of inputs
list_of_inputs = [input_1, input_2, input_3]

#calculate and print out the sum of numbers
sum_of_input = list_sum(list_of_inputs)
print("The sum:     {:6.2f}".format(sum_of_input))

#calculate and print out the average of the numbers
the_average = (sum_of_input)/(len(list_of_inputs))
print("The average: {:6.2f}".format(the_average))

#calculate and print out the percent of the total that each number represents
for input_in_list in list_of_inputs:
    percent_total = input_in_list/sum_of_input
    print("The percent of the total of each number: {:6.2f}".format(percent_total))

输出

Input a number:        1
Input a second number: 2
Input the last number: 3
The sum:       6.00
The average:   2.00
The percent of the total of each number:   0.17
The percent of the total of each number:   0.33
The percent of the total of each number:   0.50

您已完成大部分工作,指定小数点后的2位数。我还在格式说明符中添加了一些随机总宽度(6)。此宽度包括小数点前的位数,小数本身以及后面的位数。