Click here to Skip to main content
16,022,538 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
I'm making a number guessing game on Python for a school project and have come upon two problems that I cannot find a solution to. I have two questions but decided to post as one question in order to not spam code project.

How do I add a while true loop inside a while loop?
I found a neat trick where you can ask the game to keep asking for a number instead of ending the whole code when someone accidentally inserts a letter.

What I have tried:

I'm making a number guessing game on Python for a school project and have come upon two problems that I cannot find a solution to. I have two questions but decided to post as one question in order to not spam code project.

How do I add a while true loop inside a while loop?
I found a neat trick where you can ask the game to keep asking for a number instead of ending the whole code when someone accidentally inserts a letter.
Posted
Updated 25-Sep-19 17:34pm
v2

while True:
    try:
        guess = int(input("Guess which number I am thinking of: "))
    except ValueError:
        guess = print("That's not a number, guess a NUMBER!")
        continue
    else:
        break

print("hidden:", hidden, "guess:", guess)
if guess < hidden:
    print("Your guess is too low, you have ", GuessesLeft, " guesses left")
    if GuessesLeft==0:
        break
    else:
        continue
 
Share this answer
 
There are a number of issues with your code that needed tidying up. Firstly, you do not need def main(): at the beginning. Unlike compiled languages, python just starts at the beginning. I also added some print statements so you can see the progress, which is useful for debugging, and removed the duplicate bits, thus:
Python
import random

hidden = random.randint(1,100)  
print("hidden: ", hidden)

GuessesTaken = 0
while GuessesTaken < 6:
    GuessesTaken = GuessesTaken + 1;
    GuessesLeft = 6 - GuessesTaken;

    while True:
        try:
            guess = int(input("Guess which number I am thinking of: "))
        except ValueError:
            guess = print("That's not a number, guess a NUMBER!")
            continue
        else:
            break

    print("hidden:", hidden, "guess:", guess)
    if guess < hidden:
        print("Your guess is too low, you have ", GuessesLeft, " guesses left")
        if GuessesLeft==0:
            break
        else:
            continue

    elif guess > hidden:
        print("Your guess is too high, you have ", GuessesLeft, " guesses left")
        if GuessesLeft==0:
            break
        else:
            continue

    elif guess==hidden:
        print("Well done! That is the correct number")
        break
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900