Dungeon Coder


Echos in the Deep

User Input and Nested Loops

Okay, let's make things a bit more interesting by introducing the capacity to accept user input (aka: make our stuff interactive).

To do this, I will introduce the input() function. In the process, you'll also get a peek at what it's like to write what's called nested loops. Before I go on, play with the following python repl widget:

The first thing you might notice is the while True line. This specifies that the body of this while loop will run infinitely (there are always exceptions to this, which we will cover over time). Next, you see a simple print statement that - in this context - is called a prompt (we are prompting the user to enter some sort of input. Next you see the creation of a variable called shout which is set to whatever the user enters. How does the user enter input? That's what the input() function is for.

The next thing you might notice is that there is a for loop inside of our while loop. This for loop is known as the inner loop, while the while loop is called the outer loop. This means that each time through the outer loop (the while loop), the inner loop will run through each of its own iterations. In other words, for every one time throuh the while loop, this inner loop runs 3 times. This is what allows us to ask the user to say something and then echo that thing 3 times.


  1. Change our program so that it echos the user's input 5 times instead of 3 times.
  2. What happens if you change the number inside the range() portion of the for loop to a 7 instead of a 3?
  3. Replace the first print() line and the shout = input() line with the following single line:
    shout = input("Shout into the depths of the dungeon!")
  4. How did the output of our program change when you completed step 3?
  5. If you change that line you just added so that it is now the following:
    shout = input("Shout into the depths of the dungeon\n")
    How does the output change?

Join the Dungeon Crawl: A place for programmers to ponder, partake, and peruse postulations pertaining to programming, politics, potions, and pizza.

If you subscribe on Patreon, you will be granted access to the Dojo, a growing collection of quality computer science classes created and actively mantained and frequented by the Dungeon Master!

Become a Patron!


Contact: dungeon_master@dungeoncoder.com