Home > other >  How do I format ter print statement to where Count, Sum, And average have the number below instead o
How do I format ter print statement to where Count, Sum, And average have the number below instead o

Time:06-06

Sum = 0
Count = 0
while True:
    data = input("Enter a number or press Enter to quit: ")
    if data == "":
        break
    Sum  = float(data) #ever
    Count  = 1
    print("Count",Count,"Sum",Sum,"Average", Sum / Count) # This statement is the one I need the solution, when printed it comes to side to side need it as the comment has it below I don't know exactly how to align it 
print("-"*38)      
print("The sum is", Sum / Count)
if Count > 0:
    print("The average is", Sum / Count) #how to allign this statement?


# Thank you!
#Count          Sum     Average
#4           335.00       83.75

CodePudding user response:

print("{:>15} {: >15} {: >15}\n{:>15} {: >15} {: >15}\n".format("Count","Sum","Average",Count,Sum,Sum/Count))

Output:

      Count             Sum         Average
        400              30              20

CodePudding user response:

I can give you three suggestions (code samples may follow):

  1. f-string (python format string)
  2. columnar (library for printing tabular data)
  3. column -t (shell program for formatting output)

Addendum: Now that I've read your code more closely, I see that it's interactive. Since it's interactive, column -t is out, since the prompts to the user will also be formatted. columnar is also not such a great way to go either, because it is typically provided a list of lists to format. That leaves you python format string (f-string or format() statement).

Here's an approach for printing using python format strings:

Sum = 0
Count = 0
while True:
    data = input("Enter a number or press Enter to quit: ")
    if data == "":
        break
    Sum  = float(data) #ever
    Count  = 1

    print("%-10s s s" % ("Count","Sum","Average") )
    print("%-10d .2f .2f" % (Count,Sum,Sum/Count) )

print("-"*38)      
print("The sum is", Sum )
if Count > 0:
    print("The average is", Sum / Count) #how to allign this statement?

CodePudding user response:

Sum = 0
Count = 0
while True:
    data = input("Enter a number or press Enter to quit: ")
    if data == "":
        break
    Sum  = float(data) #ever
    Count  = 1
    Avg = Sum/Count

    print(f"Count\t{'Sum'.rjust(len(str(Sum)))}\t{'Average'.rjust(len(str(Avg)))}")
    print(f"{Count:>5}\t{str(Sum).rjust(len(str(Sum)))}\t{str(Avg).rjust(len(str(Sum/Count)))}")
    # sdfsdfsd
print("-"*38)
print("The sum is", Sum / Count)
if Count > 0:
    print("The average is", Sum / Count) #how to allign this statement?
  • Related