if goes through while closing - python

import random
answer = random.randrange(1,100)
guess = 101
while int(guess) != 0 :
guess = input('Enter a number between 1 and 100 or enter 0 to exit: ')
guess = int(guess)
if guess < answer :
print('Too low')
elif guess > answer :
print('Too high')
else:
print('Correct')
print('Game closed')
I have to make a random number guessing game and to close the game you enter 0 it is supposed to print game closed which it does however it also prints the if < since 0 is always going to be lower than the guess how would i get it to not include the if <

You need to rank your conditions in the order of preference. What takes the highest precedence? You'd want if guess == answer to be your first priority, because if that's the case then there's no need to check anything else and your program is done. What's your second priority? If 0 is typed then the game ends.
In other words, start with the more specific conditions (not something as broad as guess > answer).
Reframe your conditional statements as such:
if guess == answer:
print('Correct')
break
elif guess == 0:
print('Game closed')
elif guess > answer:
print('Too high')
else:
print('Too low')
You also need to set guess to 0 to break out of the loop (or just add a break as I've done here)

Re-formulate your code a bit:
import random
answer = random.randrange(1,100)
while True :
guess = int(input('Enter a number between 1 and 100 or enter 0 to exit: '))
if guess == 0:
print('Game closed')
break
elif guess < answer :
print('Too low')
elif guess > answer :
print('Too high')
else:
print('Correct!')
break

Related

Is there any way I can make my python number guesser more efficient?

So I have a game where you have to guess a number the code picks at random (I was looking at project ideas), before taking a look at the answer I want to know if there is a more efficient to store the if's? I do think there might be a way to merge them into one single block and delete the others.
def guess(x): # this is a number generator
ran_num = random.randint(1, x)
guess = int(input('type number guess from 1 to {} '.format(x)))
attempt_num = 4
if attempt_num < 1:
print('game over')
exit()
elif guess < ran_num:
(print('your guess was a bit low'))
elif guess > ran_num:
print('your guess was all too high')
while guess != ran_num:
guess = int(input('oh no, your number is incorrect, please type that again, you gots {} attempts left '.format(attempt_num)))
attempt_num -= 1
if attempt_num < 1:
print('game over')
exit()
elif guess < ran_num:
(print('your guess was a bit low'))
elif guess > ran_num:
print('your guess was all too high')
if guess == ran_num:
print("success")
guess(5)
Just ask for the guess inside the loop. You can use a for loop to iterate 4 times.
def guess(x): # this is a number generator
ran_num = random.randint(1, x)
for attempt_num in range(4, 0, -1):
guess = int(input('type number guess from 1 to {}, you gots {} attempts left '.format(x, attempt_num)))
elif guess < ran_num:
(print('your guess was a bit low'))
elif guess > ran_num:
print('your guess was all too high')
else:
print("success")
break
else:
print('game over')
guess(5)
You have some repeated code, so it would be a good idea to just put the if-else blocks into a function, this will simplify your code.
I added a check_guess function, and made ATTEMPT_NUM global so we can reference it and update it in both functions.
import random
ATTEMPT_NUM = 4
def guess(x): # this is a number generator
global ATTEMPT_NUM
ran_num = random.randint(1, x)
guess = int(input('type number guess from 1 to {} '.format(x)))
check_guess(ran_num, guess)
while guess != ran_num:
guess = int(input('oh no, your number is incorrect, please type that again, you gots {} attempts left '.format(ATTEMPT_NUM)))
ATTEMPT_NUM -= 1
check_guess(ran_num, guess)
if guess == ran_num:
print("success")
def check_guess(ran_num, guess):
global ATTEMPT_NUM
if ATTEMPT_NUM < 1:
print('game over')
exit()
elif guess < ran_num:
(print('your guess was a bit low'))
elif guess > ran_num:
print('your guess was all too high')
guess(5)
I made this attempt. x was the max random number you could get, right? Combine everything in an infinite loop that only breaks after you win or you put wrong all the numbers.
def guess(x):
attempt_num = 5
ran_num = random.randint(1, x)
while True:
guess = int(input('type number guess from 1 to {} '.format(x)))
if guess == ran_num:
print ("congrats")
break
elif guess < ran_num:
(print('your guess was a bit low'))
attempt_num = attempt_num -1
elif guess > ran_num:
print('your guess was all too high')
attempt_num = attempt_num -1
print (attempt_num)
if attempt_num == 0:
print ("game over")
break
It wouldn't hurt if you do a small check in the input to avoid the user putting anything else than a number, though.

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!')

Problem With Number Guessing Game Giving Wrong answer [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
I recently made a number guessing game and whenever I guess or lower than the randomnum it will acuratley say if it is higher or lower but if you try to keep guessing it keeps spitting out the same answer even if you get it right. I even made the code print the answer troughout the code just to make sure the value doesnt change.
import random
randomnum = random.randint(1, 100)
print(randomnum)
number = 0
wttg = input("welcome to the guesing game! \ntype y to start!")
if wttg == ("y"):
playinp = input("Guess a number between 1 and 100! \nGet it right and you win!\nwould you like to play on easy mode? (10 guesses)\nor hard mode? (3 guesses) E/H")
else:
print("oops! Thats not a correct input! Restart the code to try again! :\\")
if playinp == ("e"):
guessnum = int(input("OK, easy mode selected \nGuess..."))
while number < 10:
if guessnum == (randomnum):
print("Congratulations! You are the winner! Restart code to play again!")
break
else:
if guessnum > randomnum:
guessnum == int(input("Guess Lower"))
number = (number + 1)
if guessnum < randomnum:
guessnum == int(input("Guess Higher"))
number = (number + 1)
if number == 10:
print("You lost boohoo. what are you guna cry?")
elif playinp == ("h"):
guessnum = int(input("OK, hard mode selected \nGuess..."))
while number < 2:
if guessnum == (randomnum):
print("Congratulations! You are the winner! Restart code to play again!")
break
else:
if guessnum > randomnum:
guessnum == int(input("Guess Lower"))
number = (number + 1)
if guessnum < randomnum:
guessnum == int(input("Guess Higher"))
number = (number + 1)
print(randomnum)
if number == 2:
print("You lost boohoo. what are you guna cry?")
else:
print("oops! Thats not a correct input! Restart the code to try again!:\\")
I created a working version of your code and I will summarize the changes that I made so you can replicate this on your own.
The reason why your code doesn't update the guessnum variable is because you're doing
guessnum == int(input("Guess Lower"))
The double equal sign, ==, is a comparison operator so you are only checking if guessnum is equivalent to the input. Instead, use a single equal sign = which assigns the value of the input to the guessnum variable.
First off, from a code cleanliness perspective, you don't need parenthesis around comparisons. So instead of if wttg == ("y"):, you can just do if wttg == "y":.
You had the right idea for using a while loop but you didn't finish that code. In the future, if you want to test your code without it breaking, you can use a python pass statement. I added a condition that checks if guessnum does not equal randomnum so that we can avoid using a break statement.
Instead of doing number = (number + 1), you can use the += operator which does the same thing but is a shorthand notation. More info here.
Last thing is I did playinp.lower() == "e" and playinp.lower() == "h". This makes sure that users can type in both capital letters and lowercase letters which makes your game more user-friendly.
I updated the range of random.randint() to (1, 101) because Python ranges are non-inclusive of the last number. For example, if you print (list(range(1,10)) you will get [1, 2, 3, 4, 5, 6, 7, 8, 9].
I made quite a few more changes so feel free to ask me any more questions. :D
import random
randomnum = random.randint(1, 101)
print(randomnum)
number = 0
wttg = input("welcome to the guesing game! \ntype y to start!")
if wttg == "y":
playinp = input("Guess a number between 1 and 100! \nGet it right and you win!\nwould you like to play on easy mode? (10 guesses)\nor hard mode? (3 guesses) [E/H]")
else:
print("oops! Thats not a correct input! Restart the code to try again! :\\")
if playinp.lower() == "e":
print("OK, easy mode selected")
guessnum = int(input("Guess..."))
number += 1
while number < 10 and guessnum != randomnum:
if guessnum > randomnum:
guessnum = int(input("Guess Lower"))
else: # guessnum < randomnum
guessnum = int(input("Guess Higher"))
number += 1
if guessnum == (randomnum):
print("Congratulations! You are the winner! Restart code to play again!")
elif number == 10:
print("You lost boohoo. what are you guna cry?")
elif playinp.lower() == "h":
print("OK, hard mode selected")
guessnum = int(input("Guess..."))
number += 1
while number < 3 and guessnum != randomnum:
if guessnum > randomnum:
guessnum = int(input("Guess Lower"))
else: # guessnum < randomnum
guessnum = int(input("Guess Higher"))
number += 1
if guessnum == (randomnum):
print("Congratulations! You are the winner! Restart code to play again!")
elif number == 3:
print("You lost boohoo. what are you guna cry?")
else:
print("oops! Thats not a correct input! Restart the code to try again!:\\")
Above, I replicated your code structure but if you want to make the code cleaner, you can use the following code
import random
randomnum = random.randint(1, 101)
print(randomnum)
number = 0
wttg = input("welcome to the guesing game! \ntype y to start!")
if wttg.lower() == "y":
playinp = input("Guess a number between 1 and 100! \nGet it right and you win!\nwould you like to play on easy mode? (10 guesses)\nor hard mode? (3 guesses) [E/H]")
else:
print("oops! Thats not a correct input! Restart the code to try again! :\\")
if playinp.lower() == "e" or playinp.lower() == "h":
print("OK, easy mode selected" if playinp.lower() == "e" else "OK, hard mode selected")
max = 10 if playinp.lower() == "e" else 3
guessnum = int(input("Guess..."))
number += 1
while number < max and guessnum != randomnum:
if guessnum > randomnum:
guessnum = int(input("Guess Lower"))
else: # guessnum < randomnum
guessnum = int(input("Guess Higher"))
number += 1
if guessnum == (randomnum):
print("Congratulations! You are the winner! Restart code to play again!")
elif number == max:
print("You lost boohoo. what are you guna cry?")
else:
print("oops! Thats not a correct input! Restart the code to try again!:\\")
Inside of the if statements where you check if guessnum is lower or higher than randomnum, you aren't updating the value of guesnum. For example, if the guess is too high, you're doing guessnum == int(input("Guess Lower")) which just checks if guessnum is equal to the input or not. You want guessnum = int(input("Guess Lower")) which actually sets the value.

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")

random number generator, number guess. What is wrong with my code? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I have this basic code and what I want it to do is choose a random number, then it would ask the user to input a number from 0 to 100, the would give back results based on the number, such as number is too low or high. I keep switching things around but always get an error, this for 2.7:
import random
randomNumber = random.randrange(0,100)
guess = -1
guess = int(input('Enter a number between 0 and 100: ')
guess != randomNumber:
if guess < randomNumber
print('Your guess is too low.')
elif guess > randomNumber:
print('Your guess is too high.')
print('You win!')
First, you define guess twice. Just define it once. There is no need to make guess be equal to -1 if that won't be the original value anyways. Second, I believe you want to use a while loop to keep checking if the user has guessed the correct number. In this case, add another guess into the while loop to allow the player to continue guessing and to keep proper syntax.
Don't let the player win always with another condition. Use colons after each if/elif statement as well. As you are comparing a string (the input) and an integer, change the input() to int(input()). The final code should be something like:
import random
randomNumber = random.randrange(0, 100)
guess = None # Define guess
while guess != randomNumber: # Create loop
guess = int(input("Enter a number between 0 and 100")) # Change guess
if guess < randomNumber:
print "Your guess is too low."
elif guess > randomNumber:
print "Your guess is too high."
elif guess == randomNumber:
print "You win!" # Win message under correct condition
break # Exit the loop as game is finished
You're missing a colon after your if statement. You're also printing You win! regardless of the outcome. Put that inside an else statement. You don't need this line guess != randomNumber:, and you don't need guess=-1, and finally you're missing a closing paren as mentioned in comments.
import random
randomNumber = random.randrange(0,100)
guess = None
while guess != randomNumber:
guess = int(input('Enter a number between 0 and 100: '))
if guess == randomNumber:
break
elif guess < randomNumber:
print('Your guess is too low.')
elif guess > randomNumber:
print('Your guess is too high.')
print('You win!')
As usual, commenting your code reveals the error instantly
import random
# Pick a number between 0 and 99
randomNumber = random.randrange(0,100)
# initialize guess (hint: why?)
guess = -1
# Ask the user to guess a number (hint: balanced parentheses help)
guess = int(input('Enter a number between 0 and 100: ')
# What is this line supposed to be? Looks like the beginning of a loop here, but what kind?
guess != randomNumber:
# If the guess is less than the number, then tell the user
if guess < randomNumber
print('Your guess is too low.')
# Otherwise if the guess is higher than the number, tell the user
elif guess > randomNumber:
print('Your guess is too high.')
# Regardless, win the game. Wait whuh..?
print('You win!')
Try the following code:
import random
randomNumber = random.randrange(0,100)
guess = int(input("Enter a number between 0 and 100:"))
if guess < randomNumber:
print('Your guess is too low.')
elif guess > randomNumber:
print('Your guess is too high.')
else:
print('You win!')
(EDIT - removed some unecessary lines)
missing some formatting, and there's a few lines (guess != randomNumber:) that don't really do anything (and in that case, the colon would cause a SyntaxError).
import random
randomNumber = random.randrange(0,100)
guess = int(input('Enter a number between 0 and 100: '))
if guess < randomNumber:
print('Your guess is too low.')
elif guess > randomNumber:
print('Your guess is too high.')
else: # assuming you only want to print this if they guessed right
print('You win!')

Categories