0

The user should be able to enter what they want to do a timestable chart up to, and then the program will generate a well laid out chart. It should not allow the user to input a number below 1. It should ask them if they want to do another timestables chart after. Note that you should be nested loops. Pay close attention to formatting.

Example input/output


What timestables do you want to do? 5

    1   2   3   4   5   
    ----------------------------------
1 * 1   2   3   4   5   
2 * 2   4   6   8   10  
3 * 3   6   9   12  15  
4 * 4   8   12  16  20  
5 * 5   10  15  20  25  

Do you want to do another timestables chart (y for yes)? y

What timestables do you want to do? -3

Not a valid number.
What timestables do you want to do? 7

    1   2   3   4   5   6   7   
    --------------------------------------------------
1 * 1   2   3   4   5   6   7   
2 * 2   4   6   8   10  12  14  
3 * 3   6   9   12  15  18  21  
4 * 4   8   12  16  20  24  28  
5 * 5   10  15  20  25  30  35  
6 * 6   12  18  24  30  36  42  
7 * 7   14  21  28  35  42  49  

Do you want to do another timestables chart (y for yes)? nooo

Hope you got smarter!

I am trying to write a code to make the output look like the above, but I am completely stuck on what to do. On the bottom is what I have as of now and I was wondering if anyone can help me figure out how to write this code. Thank you

column = int(input("What timestables do you want to do? "))
for x in range(1, column+1):
    print(x, sep="\t")
eddie
  • 41
  • 1
  • 6

3 Answers3

1

This should generate the main part of the table correctly, but it will get messy if you try to print a timestable with large numbers (not sure why you would :-))

size = int(input("Please enter the size of the table: "))
# list comprehension to make 2d list
arr = [[i for i in range(1, size+1)] for j in range(size)]
# this multiplies all the numbers in the 2d list so they can be printed later
for i in range(len(arr)):
    for j in range(len(arr[i])):
        arr[i][j] = (i+1)*(j+1)
# print list
for i in range(len(arr)):
    print(str("{:2.2g}".format(i+1)) + " * " + str("{:2.2g}".format(i+1)) + "  ", end="")
    for j in range(len(arr[i])):
        print(str("{:2.2g}".format(arr[i][j])) + " ", end="")
    # newline
    print()

The important part is the str("{:2.2g}".format(i+1)). It formats the decimal to 2 places, and the g removes the zeroes. Check out Python Decimals format

Community
  • 1
  • 1
0

There is end= argument that you can pass to the print function. Normally print will add \n to the end. For your case, passing a tab is a good choice:

print(x, end='\t')
James
  • 32,991
  • 4
  • 47
  • 70
0

By default the print function adds a "\n". You can change passing the argument , end ="") or , end ="\t"). Check this link it may help.

Community
  • 1
  • 1