How to break out of this loop? - python

Write a Python program to guess a number between 1 to 9. Go to the editor
Note : User is prompted to enter a guess. If the user guesses wrong then the prompt appears again until the guess is correct, on successful guess, user will get a "Well guessed!" message, and the program will exit.
Edit:- i want to print a message everytime a wrong number is input. However i am getting that message even if i write the correct number.
target_num = 3
guess_num = ""
while target_num != guess_num:
guess_num = int(input('Guess a number between 1 and 10 until you get it right : '))
print("wrong guess")
print('Well guessed!')`

You will want to use to break keyword like so:
target_num=3
while True:
guess_num = int(input('Guess a number between 1 and 10 until you get it right : '))
if guess_num == target_num:
break
print("wrong guess")
print('Well guessed!')
Alternatively, if you don't want to use break you could use:
target_num=3
guess_num=""
while guess_num != target_num:
guess_num = int(input('Guess a number between 1 and 10 until you get it right : '))
if guess_num != target_num:
print("wrong guess")
print('Well guessed!')

Related

Beginners Coding Error, While Loop Triggering 2 Messages

I am a beginner that just started learning python this Monday and one of the first hurdles I am getting into is while loops. I was trying to code a number guessing game and when I enter the correct answer it will give me "Wrong Guess" and "Correct Guess" as outputs. I have been staring at this problem wondering why this is happening but I can't figure it out. Can someone explain why this is happening? Thanks in advance!
secret_number = 9
guess = ''
i = 0
while guess != 9 and i < 3:
guess = int(input("Guess Number: "))
i += 1
print('Wrong Guess!')
if guess == 9:
print('Your Correct!')
if i == 3:
print('You lost!')
You need to trace your code line by line. Even if your answer was correct, the print('Wrong Guess!') would still execute.
Instead, I would check if the answer is correct inside the loop.
Note: there's a bug in your code - you should be using secret_number variable instead of explicitly writing 9.
You should also only add i for wrong guesses to prevent saying you lost although you did it in 3 tries.
while guess != secret_number and i < 3:
guess = int(input("Guess Number: "))
if guess == secret_number :
print('Your Correct!')
else:
print('Wrong Guess!')
i += 1
You were getting both the messages together when you entered 9 as the input because the input statement and the Wrong Guess statement are both in the same while loop. Meaning once the code asks you to guess a number, it would then increment i and then print Wrong Guess. Only after doing all three it would go back and check for the conditions of the while loop. Because the conditions fail, for guess = 9 the next lines of code are implemented. which give you the Correct Guess output.
To get the desired output do this,
secret_number = 9
guess = ''
i = 0
while True:
if i < 3:
guess = int(input("Guess Number: "))
if guess == secret_number:
print("Correct Guess")
break
else:
print("Wrong Guess")
i += 1
else:
print("You've run out of lives.")
break
This is another way to get what you're looking for:
secret_number = 9
guess = ''
i = 0
while guess!= secret_number and i<3:
guess = int(input("Guess Number:"))
if guess == secret_number:
print("Your Correct!")
break
print("Wrong Guess!")
i+=1
if i == 3:
print('You Lost!')

Python while loop number guessing game with limited guesses

For a class assignment, I'm trying to make a number guessing game in which the user decides the answer and the number of guesses and then guesses the number within those limited number of turns. I'm supposed to use a while loop with an and operator, and can't use break. However, my issue is that I'm not sure how to format the program so that when the maximum number of turns is reached the program doesn't print hints (higher/lower), but rather only tells you you've lost/what the answer was. It doesn't work specifically if I choose to make the max number of guesses 1. Instead of just printing " You lose; the number was __", it also prints a hint as well. This is my best attempt that comes close to doing everything that this program is supposed to do. What am I doing wrong?
answer = int(input("What should the answer be? "))
guesses = int(input("How many guesses? "))
guess_count = 0
guess = int(input("Guess a number: "))
guess_count += 1
if answer < guess:
print("The number is lower than that.")
elif answer > guess:
print("The number is higher than that")
while guess != answer and guess_count < guesses:
guess = int(input("Guess a number: "))
guess_count += 1
if answer < guess:
print("The number is lower than that.")
elif answer > guess:
print("The number is higher than that")
if guess_count >= guesses and guess != answer:
print("You lose; the number was " + str(answer) + ".")
if guess == answer:
print("You win!")
What about something like this?
answer = int(input("What should the answer be? "))
guesses = int(input("How many guesses? "))
guess_count = 1
guess_correct = False
while guess_correct is False:
if guess_count < guesses:
guess = int(input("Guess a number: "))
if answer < guess:
print("The number is lower than that.")
elif answer > guess:
print("The number is higher than that")
else: # answer == guess
print("You win!")
break
guess_count += 1
elif guess_count == guesses:
guess = int(input("Guess a number: "))
if guess != answer:
print("You lose; the number was " + str(answer) + ".")
if guess == answer:
print("You win!")
break
It's very similar to your program, but has a couple break statements in there. This tells Python to immediately stop execution of that loop and go to the next block of code (nothing in this case). In this way you don't have to wait for the program to evaluate the conditions you specify for your while loop before starting the next loop. If this helped solve your problem, it'd be great of you to click the checkmark by my post

Python Guessing Game Reject Invalid User Input

I'm taking my first-ever Python class and, like most Python classes, the last assignment is to create a guessing game from 1-100 that tracks the number of VALID tries. The element that I just cannot get (or find here on stackoverflow) is how to reject invalid user input. The user input must be whole, positive digits between 1 and 100. I can get the system to reject everything except 0 and <+ 101.
The only things I can think to do end up telling me that you can't have operators comparing strings and integers. I keep wanting to use something like guess > 0 and/or guess < 101. I've also tried to create some sort of function, but can't get it to work right.
# Generate random number
import random
x = random.randint(1,100)
# Prompt user for input
print("I'm thinking of a number from 1 to 100")
counter = 0
while True:
guess = input("Try to guess my number: ")
# Check if input is a positive integer and is not 0 or >=101
# this line doesn't actually stop it from being a valid guess and
# counting against the number of tries.
if guess == "0":
print(guess, "is not a valid guess")
if guess.isdigit() == False:
print(guess, "is not a valid guess")
else:
counter += 1
guess = int(guess)
# Begin playing
if guess > x:
print(guess, "is too high.")
elif guess < x:
print(guess, "is too low.")
else:
print(guess, "is correct! You guessed my number in", counter, "tries!")
import random
x = random.randint(1,100)
# Prompt user for input
print("I'm thinking of a number from 1 to 100")
counter = 0
while True:
guess = input("Try to guess my number: ")
try:
guess = int(guess)
if(100 > guess > 0):
counter += 1
guess = int(guess)
# Begin playing
if guess > x:
print(guess, "is too high.")
elif guess < x:
print(guess, "is too low.")
else:
print(guess, "is correct! You guessed my number in", counter, "tries!")
break
else:
print("Number not in range between 0 to 100")
except:
print("Invalid input")
# Generate random number
import random
x = random.randint(1,100)
# Prompt user for input
print("I'm thinking of a number from 1 to 100")
counter = 1
while True:
try:
guess = int(input("Try to guess my number: "))
if guess > 0 and guess < 101:
print("That's not an option!")
# Begin playing
elif guess == x:
print(guess, "is correct! You guessed my number in", counter, "tries!")
break
elif guess > x:
print(guess, "is too high.")
elif guess < x:
print(guess, "is too low.")
else:
counter += 1
except:
print("That's not a valid option!")
My instructor helped me out. (I posted to keep from needing that from the guy who's giving me the grade.) Here is what we came up with. I'm posting it to help out any future Python learner that may have this particular rejecting user input problem.
Thank you guys for posting SO FAST! Even though I needed the instructor's help, I would've looked even more incompetent without your insights. Now I can actually enjoy my holiday weekend. Have a great Memorial Day weekend!!!
import random
x = random.randint(1,100)
print("I'm thinking of a number from 1 to 100.")
counter = 0
while True:
try:
guess = input("Try to guess my number: ")
guess = int(guess)
if guess < 1 or guess > 100:
raise ValueError()
counter += 1
if guess > x:
print(guess, "is too high.")
elif guess < x:
print(guess, "is too low.")
else:
print(guess, "is correct! You guessed my number in", counter, "tries!")
break
except ValueError:
print(guess, "is not a valid guess")

I'm trying to write a number guessing game in python but my program isn't working

The program is supposed to randomly generate a number between 1 and 10 (inclusive) and ask the user to guess the number. If they get it wrong, they can guess again until they get it right. If they guess right, the program is supposed to congratulate them.
This is what I have and it doesn't work. I enter a number between 1 and 10 and there is no congratulations. When I enter a negative number, nothing happens.
import random
number = random.randint(1,10)
print "The computer will generate a random number between 1 and 10. Try to guess the number!"
guess = int(raw_input("Guess a number: "))
while guess != number:
if guess >= 1 and guess <= 10:
print "Sorry, you are wrong."
guess = int(raw_input("Guess another number: "))
elif guess <= 0 and guess >= 11:
print "That is not an integer between 1 and 10 (inclusive)."
guess = int(raw_input("Guess another number: "))
elif guess == number:
print "Congratulations! You guessed correctly!"
Just move the congratulations message outside the loop. You can then also only have one guess input in the loop. The following should work:
while guess != number:
if guess >= 1 and guess <= 10:
print "Sorry, you are wrong."
else:
print "That is not an integer between 1 and 10 (inclusive)."
guess = int(raw_input("Guess another number: "))
print "Congratulations! You guessed correctly!"
The problem is that in a if/elif chain, it evaluates them from top to bottom.
Move the last condition up.
if guess == number:
..
elif other conditions.
Also you need to change your while loop to allow it to enter in the first time. eg.
while True:
guess = int(raw_input("Guess a number: "))
if guess == number:
..
then break whenever you have a condition to end the game.
The problem is that you exit the while loop if the condition of guessing correctly is true. The way I suggest to fix this is to move the congratulations to outside the while loop
import random
number = random.randint(1,10)
print "The computer will generate a random number between 1 and 10. Try to guess the number!"
guess = int(raw_input("Guess a number: "))
while guess != number:
if guess >= 1 and guess <= 10:
print "Sorry, you are wrong."
guess = int(raw_input("Guess another number: "))
elif guess <= 0 and guess >= 11:
print "That is not an integer between 1 and 10 (inclusive)."
guess = int(raw_input("Guess another number: "))
if guess == number:
print "Congratulations! You guessed correctly!"

How to add a loop to my python guessing game?

So I am very new to python as I spend most of my time using HTML and CSS. I am creating a small project to help me practice which is a number guessing game:
guess_number = (800)
guess = int(input('Please enter the correct number in order to win: '))
if guess != guess_number:
print('Incorrect number, you have 2 more attempts..')
guess2 = int(input('Please enter the correct number in order to win: '))
if guess2 != guess_number:
print('Incorrect number, you have 1 more attempts..')
guess2 = int(input('Please enter the correct number in order to win: '))
if guess2 != guess_number:
print()
print('Sorry you reached the maximum number of tries, please try again...')
else:
print('That is correct...')
elif guess == guess_number:
print('That is correct...')
So my code currently works, when run, but I would prefer it if it looped instead of me having to put multiple if and else statements which makes the coding big chunky. I know there are about a million other questions and examples that are similar but I need a solution that follows my coding below.
Thanks.
Have a counter that holds the number of additionally allowed answers:
guess_number = 800
tries_left = 3
while tries_left > 0:
tries_left -= 1
guess = int(input('Please enter the correct number in order to win: '))
if guess == guess_number:
print('That is correct...')
break
else:
print('Incorrect number, you have ' + str(tries_left if tries_left > 0 else 'no') + ' more attempts..')
If you don't know how many times you need to loop beforehand, use a while loop.
correct_guess = False
while not correct_guess:
# get user input, set correct_guess as appropriate
If you do know how many times (or have an upper bound), use a for loop.
n_guesses = 3
correct_guess = False
for guess_num in range(n_guesses):
# set correct_guess as appropriate
if correct_guess:
# terminate the loop
print("You win!")
break
else:
# if the for loop does not break, the else block will run
print("Out of guesses!")
You will get an error, TypeError: Can't convert 'int' object to str implicitly if you go with the answer you have selected. Add str() to convert the tries left to a string. See below:
guess_number = 800
tries_left = 3
while tries_left > 0:
tries_left -= 1
guess = int(input('Please enter the correct number in order to win: '))
if guess == guess_number:
print('That is correct...')
break
else:
print('Incorrect number, you have ' + (str(tries_left) if tries_left > 0 else 'no') + ' more attempts..')

Categories