Search code examples
pythonpython-3.xnested-loops

What is a nested loop and how do I use it in example below?


I was given the following problem for my beginning python coding class. I have reached out to the professor, but he hasn't gotten back to me and this is due in 3.5 hours. If someone has a tutorial/guidance of how to start, that would be amazing. I do NOT expect anyone to write this code! I just need a bit of guidance! Thanks :)

Write a program in Python to prompt user to enter an integer between 10 and 3 inclusive and also a character. Then use these two values to display a box using the character entered with size of box determined by the number entered.

Here is a sample output:

Enter size of box:  4

Enter a character: %

%%%%

%%%%

%%%%

%%%%

Here is another possible output:

Enter size of box:  3

Enter a character: &

&&&

&&&

&&&

Your program will run only once but you must used repetition construct to draw the box using values entered.

Hint: It should be a nested loop. Each line printed is a loop so you will have loop inside loop construct; nested loop.

As before, you must test for invalid values and if so, display an error message and proceed to get a valid number.

Use your own test values here.


Solution

  • Solution

    Let's break the problem down into steps.

    1. First, we need to get an integer from the input, and make sure that the integer is either 3, 10, or any number in between. That's what 3 to 10 inclusive means.

    2. We then need to ask a user for a single character that will be used to print a box.

    3. After we've gotten the integer, and the character, we need to display a box made up of the character whose width and height are determined by the integer.

    For step one, we need to get input from the user. This can be done using the builtin function input(). It takes an optionally prompt as an argument, and returns the input as a string. So let's write that down:

    integer = input()
    

    Great. Now we need to convert the input to an integer, so it can be used in the rest of our program. This can be accomplished using the built-in function int(). We'll pass in your string, and it will convert it to an integer:

    integer = int(input('Enter a number: '))
    

    Step two is to get a character from the user. That's easy. We'll use input() once again to get a single character from the user. but since the input need to be a character, we shouldn't convert this value:

    character = input('Enter a character: ')
    

    Alright. This is what we have so far:

    integer = int(input('Enter a number: '))
    character = input('Enter a character: ')
    

    The last step is to print a box made of the value of character that has a width of integer and a height of integer. Now all we need to do is to print a row with integer number of characters integer number of times. This is where the nested for loop comes in.

    We know each row must be the width of integer. So we need to print character that many times. We can use the range() built-in function to do this. We pass in integer as an argument, and it will generate all of the numbers from 0 to integer:

    for _ in range(integer):
        print(character, end="")
    

    The the reason we used the underscore in our for loop instead of an actual readable variable name, is because we don't need to use the values that the for loops would give us. We only care about repeating our code.

    The end="" part is telling the print() builtin function not to print a newline each time it is called, because we want all the character to be in one row. The print() before the for loop is to add some space between our prompts and the program output. Let's see what our program outputs so far:

    Enter a number: 5
    Enter a character: @
    
    @@@@@
    >>> 
    

    Great. The last thing to do is to print each row integer number of times. Since we know that executing the for loop above prints one row, we just need to execute it integer number of times to print integer rows. So we'll wrap that for loop inside of another for loop and use range() to execute the nested for loop integer number of times. We'll use print() once again, to add a newline between each row:

    print()
    for _ in range(integer):
        for _ in range(integer):
            print(character, end="")
        print()
    

    And that's it! Were done. Let's test our program:

    Enter a number: 7
    Enter a character: #
    
    #######
    #######
    #######
    #######
    #######
    #######
    #######
    >>> 
    

    As you can see, we're getting our expected output. Here is the final program:

    integer = int(input('Enter a number: '))
    character = input('Enter a character: ')
    
    print()
    for _ in range(integer):
        for _ in range(integer):
            print(character, end="")
        print()
    

    Error handling

    You may also need to implement error handling. This means making your program recover from the user entering invalid input. In this case, the only time invalid input could really be enetered is when we are asking the user for an integer. We need to:

    1. make sure the user enetered a valid number. And
    2. make sure that number is either 3, 10 or any number in between.

    To do this, we'll need a loop. This is so we can continue to ask the user for valid input, until they do so. We can use a while True loop. This means we'll keep looping until we break from the loop.

    while True:
    

    Now we need to make sure the user entered a valid number. We can use a try/except block. The way a try/except block works is that we put a block of code in the try portation that may raise an error. if no error is raised, we continue in the program normally. If an error is raised however, Python will jump to the except block and the code in there will be executed.

    In our case we'll try to convert the users input to an integer. If this fails a ValueError will be raised. So we need to catch that error message and print it to the user:

    while True:
        try:
            integer = int(input())
        except ValueError:
            print('Please enter a number')
    

    All that's left is to test if the integer entered is in the correct range. If so, we'll break from our loop and continue with the program. If not, we'll display an error message and try again. Here is how that would look:

    while True:
        try:
            integer = int(input('Enter a number: '))
            if integer >= 3 and integer <= 10:
                break
            print('Please enter a number between 3 and 10 inclusive')
        except ValueError:
            print('Please enter a number')
    
    character = input('Enter a character: ')
    
    print()
    for _ in range(integer):
        for _ in range(integer):
            print(character, end="")
        print()
    

    Here is how the above would look in the full program:

    And here is a demo:

    Enter a number: -23
    Please enter a number between 3 and 10 inclusive
    Enter a number: a
    Please enter a number
    Enter a number: 11
    Please enter a number between 3 and 10 inclusive
    Enter a number: 10
    Enter a character: #
    
    ##########
    ##########
    ##########
    ##########
    ##########
    ##########
    ##########
    ##########
    ##########
    ##########
    >>> 
    

    For more resources about error handling in a program, see the question: Asking the user for input until they give a valid response.