Search code examples
pythonpython-3.xloopsnested-loops

Addition Table: Python3+


For the question below I done what I can shown in , but don't really know where to go from there. I just started working with end values and am probably going to destroy this small code farther.

https://i.sstatic.net/QIuJt.png


# Inputs
range_start = int(input("Enter start value:"))
range_end = int(input("Enter end value:"))

# Calculations
for loop in range(range_start, range_end + 1):
answer = range_start + loop
print("{}|".format(loop), "{}".format(answer))

Solution

  • Here's the code I came up with. The main part of the script is that it uses str.format to allow for easier formatting with the numbers for the table. print_overall gets output strings from output. After printing the list of columns and the dashed line, print_overall prints row by row. I recommend checking out "6.1.3. Format String Syntax" in the docs for more info. about str.format.

    def output(values = None, row_num = None):
        res = ""
        if not row_num:
            res += " " * 2
        else:
            res += row_num + "|"    
        for i in values:
            res += "{:5}".format(i) #{:5} allows for filler space when string length < 5
        return res
    
    def print_overall(rnge):
        print(output(rnge))
        print(output(["-"*5]*len(rnge)))
        for row_num in rnge:
                    #for every row number, make an list that maps values
                    #where all the column numbers are added to the current row number
            lst = list(map(lambda col_num: row_num + col_num, rnge))
            print(output(lst, row_num = str(row_num)))
    
    
    range_start = int(input("Enter start value:"))
    range_end = int(input("Enter end value:"))
    
    input_range = range(range_start, range_end+1) #+1 because range is exclusive at endpoint
    print_overall(input_range)