Exercise 2: Loops

2. Create a guess game with the names of the colors. At each round pick a random color from a list and let a user guess it. When he does it, ask if he wants to play again. Keep playing until the user types "no."

I think this is going to be a very nice challenge. Good luck, and when you finish, come back here to see the solution. 

Solution to exercise.

Code:

import random

colors = ["white", "black", "yellow", "blue", "pink", "purple", "grey", "indigo"]

while True:
    color = colors[random.randint(0, len(colors) - 1)]
    guess = input("I'm thinking about a color, can you guess it: ")

    while True:
        if color == guess.lower():
            print("You guessed it! I was thinking about", color)
            break
        else:
            guess = input("Nope. Try again: ")

    play_again = input("Let's play again? Type 'no' to quit: ")

    if play_again.lower() == 'no':
        print("It was fun, thanks for playing!")
        break

Output:

>>> 
==== RESTART: C:\Users\ameny\OneDrive\Desktop\Python.course\Ex.loops2.py ====
I'm thinking about a color, can you guess it: red
Nope. Try again: white
Nope. Try again: blue
Nope. Try again: green
Nope. Try again: yellow
Nope. Try again: pink
Nope. Try again: grey
Nope. Try again: indigo
Nope. Try again: black
You guessed it! I was thinking about black
Let's play again? Type 'no' to quit: 

You can hit enter to see if it repeats, then you try again.

Let's try typing no to see what happens:

>>> 
==== RESTART: C:\Users\ameny\OneDrive\Desktop\Python.course\Ex.loops2.py ====
I'm thinking about a color, can you guess it: red
Nope. Try again: white
Nope. Try again: blue
Nope. Try again: green
Nope. Try again: yellow
Nope. Try again: pink
Nope. Try again: grey
Nope. Try again: indigo
Nope. Try again: black
You guessed it! I was thinking about black
Let's play again? Type 'no' to quit: no
It was fun, thanks for playing!
>>> 

Alright let me know in the comment section if you have further questions. See you in our next tutorial.










































dsssds

No comments:

Post a Comment

Python Programming Tutorial 15

 Error Handling Anytime we work with user input, we should make sure not only the data is valid and within the range we want, like what we d...