You will learn how to loop over a Python list. Further, you will learn the power of a While loop. Finally, you will create a Hangman Game.
In this tutorial, you will:
By the end of the tutorial, you will have a strong grasp of iterating over lists, utilizing While loops effectively, and implementing a fun and interactive Hangman game. This hands-on experience will enhance your understanding of loops and equip you with practical programming skills.
Looping over a list can be done as follows (see more about lists here).
my_list = ['First', 'Second', 'Third']
for item in my_list:
print(item)
This can also be done over a string, which is a sequence.
s = "Rune"
for c in s:
print(c)
print("Inside loop")
print("Outside the loop")
Where we notice the syntax of how the indentation works. What is inside and outside the loop?
Notice that for-loops in Python loop over a predetermined length. In the above cases, the length of the list or the length of the string.
If you want a loop that is dependent on something inside the loop.
What do I mean? Let’s take an example.
value = 10
while value > 0:
value = int(input("Value? "))
As you see – this loop is dependent on input in the loop. If you type zero or a negative value, it will stop.
A description of the Hangman Game (see wiki for further details)
Let’s try to implement the Hangman Game
import random
words = ['father', 'enterprise', 'science', 'programming', 'resistance', 'fiction', 'condition', 'reverse', 'computer', 'python']
word = random.choice(words)
turns = 10
guesses = ''
while turns > 0:
print(f"Turns left: {turns}")
guessed_all = True
for c in word:
if c in guesses:
print(c, end=' ')
else:
print('_', end=' ')
guessed_all = False
print()
if guessed_all:
print("You won")
break
guess = input("Guess a character: ")
if guess in word:
guesses += guess
else:
turns -= 1
else:
print("You lost")
In the next lesson you will make a Simple Implementation of Caesar Cipher in Python.
If this is something you like and you want to get started with Python, then this is part of an 8 hours FREE video course with full explanations, projects on each level, and guided solutions.
The course is structured with the following resources to improve your learning experience.
See the full FREE course page here.
Why Value-driven Data Science is the Key to Your Success In the world of data…
Harnessing the Power of Project-Based Learning and Python for Machine Learning Mastery In today's data-driven…
Is Python the right choice for Machine Learning? Should you learn Python for Machine Learning?…
Learn Python by Creating 19 Projects Do you want to learn Python by creating projects?…
Implement a four-in-a-row game in Python On a high level, you will learn about the…
Implement a valid parentheses checker in Python Keep your skills sharp and start learning Python…