Practical 3
Practical 3
Lab3 handouts
Writing a For Loop
Syntax
Range( )
Range allows us to count from one number to another while being able to define where to start
and end and how much we increment or decrement by.
Looping by Element
Continue Statement
Once a continue statement is hit, the current iteration stops and goes back to the top of the loop.
The output will result in “0, 1, 2, 4” because the continue statement is only read when num is
equal to the value of 3
Break Statemen
It allows us to break out of a loop at any point in time. The output will result in “0, 1, 2” because
we broke the loop completely when num was equal to 3.
Pass Statement
The pass statement is simply just a placeholder so that the program doesn’t break. Nothing
happens, but that’s a good thing. If you take the pass statement out completely, the program will
break because there needs to be some sort of code within the block.
Practice Program
Nested Loops
Practice Program
Slicing Lists
Slicing follows the same arguments as the range function start, stop, step:
Adding Items
When you need to add items to your lists, Python has two different methods for doing so.
.append( )
Append will always add the value within the parenthesis to the back of the list.
.insert( )
This method requires an index to insert a value into a specific location.
Removing Items
There are several ways to remove items from a list, the following are the main two methods.
.pop( )
By default, the pop method removes the last item in the list; however, you can specify an index
to remove as well.
.remove( )
The remove method allows us to remove items from a list based on their given value:
Sorting a List
sorted( )
.sort( )
The sort method is used for the same purpose that our previous sorted function is used for;
however, it will change the original list directly:
Practice Program
Creating Hangman
Final Design
1. Select a word to play with.
2. Ask user for input.
3. Check if guess is correct.
This is the main game play functionality. There are several other steps we need to perform before
actually running the game, like declaring game variables; however, this is the primary
functionality that we needed to lay out before we begin coding. Knowing this structure will allow
us to stay on track with our program.
Adding Imports
Checking a Guess
Clearing Output
Creating the Losing Condition