简体   繁体   中英

Python Nested Loops, If statement, and Function

I am tasked with using nested loops, an if statement, and a function to reproduce the following table precisely using Python. The X's must be consistent to the example. I am struggling immensely with using functions and other code. I understand that this 9x9 grid has x's in the range 3y-9y, and 4x-9x save for the 9, 9 grid.

My current code is:

for x in range (1, 10): for y in range (1, 10):
        print ( ' {:3}' . format(x * y), end = ' ')
    print()

Which produces the 9x9 grid. I do not understand how to add a function into this code to create the X's where appropriate.

Table requirements

The guidance "use a function" is pretty vague.

If I were writing this code, I would break it down like this.

Each time through the loop, you're going to print something , either a number or the letter x. So it makes sense (to me at least) to write a function that takes the two arguments x and y, decides what should be printed, and returns the value.

Then your main loop doesn't have to worry about what to print; it just calls that function over and over and prints whatever it said.

def what_should_i_print(x, y):
    # this function will use if/else to decide
    # whether to return 'x' or return x*y

for x in range (1, 10):
    for y in range (1, 10):
        thing = what_should_i_print(x, y)
        print ( ' {:3}' . format(thing), end = ' ')
    print()
for x in range (1, 10): 
    for y in range (1, 10):
        if (x == 9 and y == 9) or (y < 3) or (x < 4): 
            print ( ' {:3}' . format(x * y), end = ' ')    
        else: 
            print ('   X', end = ' ')
    print()

Output:

   1    2    3    4    5    6    7    8    9 
   2    4    6    8   10   12   14   16   18 
   3    6    9   12   15   18   21   24   27 
   4    8    X    X    X    X    X    X    X 
   5   10    X    X    X    X    X    X    X 
   6   12    X    X    X    X    X    X    X 
   7   14    X    X    X    X    X    X    X 
   8   16    X    X    X    X    X    X    X 
   9   18    X    X    X    X    X    X   81

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM