Stuck in a while loop while using if statement - python

I'm new to python and I'm trying to make a simple Guess the number game, and I'm stuck in an if statement in a while loop. here is the code.
I'm experiencing it at the Your guess it too high and the low one. I tried breaking it, but it simply stops the whole things
def guess_the_number():
number = random.randrange(20)
guessesMade = 0
print('Take a guess')
guess = input()
guess = int(guess)
while guessesMade < 6:
if guess < number:
print('Your guess is too low.')
if guess > number:
print('Your guess is too high.')
if guess == number:
break
if guess == number:
print'You got it in', guessesMade, 'guess(es)! Congratulaions!'
else:
print'I\'m sorry, the number was', number

You never increment guessesMade so guessesMade < 6 will always be True. You need to modify this value within your loop. You also need to move your prompt for user input into the loop
while guessesMade < 6:
guess = int(input('Take a guess'))
if guess < number:
print('Your guess is too low.')
guessesMade += 1
elif guess > number:
print('Your guess is too high.')
guessesMade += 1
else:
break

Related

How do I make two functions share a variable?

My assignment is to make a secret number, which is 26, and make a guessing game saying the guess is either "too low" or "too high". I made two functions, int_guess for if the input is an integer and not_int_guess for when the input is not an integer. The problem that i have though is when im counting the amount of guesses, i dont know how to make both functions share a count of how many guesses they inputted.
print("Guess the secret number! Hint: it's an integer between 1 and 100...")
secret_num = 26
guess = int(input("What is your guess? "))
def int_guess(guess):
count = 0
while guess != 26:
if guess > secret_num:
print("Too high!")
guess = int(input("What is your guess? "))
count += 1
elif guess < secret_num:
print("Too low!")
guess = int(input("What is your guess? "))
count += 1
else:
print("You guessed it! It took you", count, "guesses.")
def not_int_guess(guess,count):
print("Bad input! Try again: ")
guess = int(input("What is your guess? "))
while guess != 26:
if guess > secret_num:
print("Too high!")
guess = int(input("What is your guess? "))
elif guess < secret_num:
print("Too low!")
guess = int(input("What is your guess? "))
else:
print("You guessed it! It took you", count, "guesses.")
try:
int_guess(guess)
except:
not_int_guess(guess,count)
One part of the assignment that i need to have is a try and except, the problem is that the count will reset to zero if the except is used, but i need the count to carry over to the exception case. I tried carrying the "count" variable over to the not_int_guess by placing it like not_int_guess(guess,count) but that doesnt work for a reason i dont understand.
Instead of using two functions, use the try and except within the while loop. That way everything is much neater and more efficient (also good to define functions before any main code):
def int_guess(secret_num):
count = 0
guess = 0 #Just defining it here so everything in the function knows about it
while guess != secret_num:
try:
guess = int(input("What is your guess? "))
except ValueError as err:
print("Not a number! Error:", err)
continue #This will make the program skip anything underneath here!
if guess > secret_num:
print("Too high!")
elif guess < secret_num:
print("Too low!")
count += 1 #Adds to count
#This will run after the while loop finishes:
print("You guessed it! It took you", count, "guesses.")
#Main code:
print("Guess the secret number! Hint: it's an integer between 1 and 100...")
int_guess(26)
Like this, the function will run until the user has guessed the number no matter what they input, while also keeping count through any errors
You can use the count variable outside the functions to use it in both the variables globally.
I have also made some changes to the code to make it work properly
print("Guess the secret number! Hint: it's an integer between 1 and 100...")
secret_num = 26
count = 0
guess = 0
def int_guess(guess):
count = 0
while guess != 26:
guess = int(input("What is your guess? "))
if guess > secret_num:
print("Too high!")
count += 1
elif guess < secret_num:
print("Too low!")
count += 1
else:
print("You guessed it! It took you", count, "guesses.")
def not_int_guess(guess):
print("Bad input! Try again: ")
int_guess(guess)
try:
int_guess(guess)
except:
not_int_guess(guess)

Guess the Number Program Exits in 2nd Inputs

really a beginner here. I was following "Automate the Boring Stuff with Python" book and the author makes you write a short "guess the number" program. The book gives a solution but I wanted to pursue my own one. I do not know why this program exits on 2nd input. Can you tell me whats wrong with it, I was not able to figure it out even though its a pretty basic code.
import random
secretNumber = random.randint(1,20)
print("I got a number in my mind from 1 to 20")
guess = int(input("Take a guess."))
numberOfTries = 0
if guess < secretNumber:
print("Your guess is lower than my number")
numberOfTries = numberOfTries + 1
int(input("Take a guess."))
elif guess > secretNumber:
print("Your guess is higher than my number")
numberOfTries =+ 1
guess = int(input("Take a guess."))
if guess == secretNumber:
print("You guessed right!")
print("You found my number in" + str(numberOfTries))
It is because you need to put the guessing part in a loop. So far you only have a single instance of checking your guessed value against the correct value. Thus:
secretNumber = random.randint(1,20)
guess = int(input("Take a guess."))
while guess != secretNumber:
# logic from above
# . . . .
guess = int(input("Take a guess."))
Here's the code properly formatted:
import random
secretNumber = random.randint(1,20)
print("I got a number in my mind from 1 to 20")
guess = -1
numberOfTries = 0
while guess != secretNumber:
# inserted space after input
guess = int(input("Take a guess: "))
if guess < secretNumber:
print("Your guess is lower than my number")
# changed to +=
numberOfTries += 1
# removed input()
elif guess > secretNumber:
print("Your guess is higher than my number")
# changed the =+ to +=
numberOfTries += 1
if guess == secretNumber:
print(f"You guessed right!\nYou found my number in {numberOfTries} tries!")
I suggest not copy-pasting but reading the comments and understanding the changes.
Furthermore, here is a bit more advanced code (just the while loop part):
while guess != secretNumber:
guess = int(input("Take a guess: "))
if guess != secretNumber:
if guess > secretNumber:
higher_lower = "higher"
else:
higher_lower = "lower"
numberOfTries += 1
print(f"Your guess is {higher_lower} than my number")
Good luck with python!

Python Why does my code result in an infinite loop?

So, I am learning Python 3. I tried writing a script that asks you to guess a number from 1 to 20.
Now I know that this is not the best way of doing it, but when I run the code it goes into an infinite loop.
What causes that? What did I do wrong? The purpose of my question is to understand my mistake and the process that leads to that.
Thank you guys.
# Defining the function inside which the verification happens
def guesst(secretNumber, inputNumber):
numberOfGuesses = 0
if inputNumber >= 1 and inputNumber <= 20:
while inputNumber:
if inputNumber > secretNumber:
numberOfGuesses += 1
print('Your guess is too high.')
elif inputNumber < secretNumber:
numberOfGuesses += 1
print('Your guess is too low.')
elif inputNumber == secretNumber:
print('Your guess is correct, congratulations! You\'ve my number in ', numberOfGuesses, 'guesses.')
break
else:
print('Please enter a number between 1 and 20')
# Defining the variables used by the function
secretNumber = 11
inputNumber = int(input('I\'m thinking of a number between 1 and 20, try to guess which one: '))
# Calling in the function
guesst(secretNumber, inputNumber)
# -------------------------------------------------------
# I just changed my code to this and it worked, thank you!
# -------------------------------------------------------
def guesstt(secretNumber):
numberOfGuesses = 0
while secretNumber:
inputNumber = int(input('I\'m thinking of a number between 1 and 20, try to guess which one: '))
if inputNumber >= 1 and inputNumber <= 20:
if inputNumber > secretNumber:
numberOfGuesses += 1
print('Your guess is too high.')
elif inputNumber < secretNumber:
numberOfGuesses += 1
print('Your guess is too low.')
elif inputNumber == secretNumber:
print('Your guess is correct, congratulations! You\'ve my number in ', numberOfGuesses, 'guesses.')
break
else:
print('Please enter a number between 1 and 20')
secretNumber = 11
guesstt(secretNumber)
Read these two lines:
if inputNumber >= 1 and inputNumber <= 20:
while inputNumber:
The while loop body doesn't change inputNumber.
If it is in the range 1..10, or 12..20,
your loop amounts to while True: and it will run forever.
You probably want the if test on the inside of the loop,
and you definitely want the value to change by the time
you come back to evaluate the looping condition,
for example by inputing a new value.
The secretNumber does not change? Use numberOfGuesses in the if and elif
The variable inputNumber isn't updated within the while loop.
Try adding:
inputNumber = int(input("please try again"))
Or something to the effect that will allow the user to update their guess before the following iteration.
Try this
def guesst(secretNumber):
numberOfGuesses = 0
while True:
inputNumber = int(input('I\'m thinking of a number between 1 and 20, try to guess which one: '))
if inputNumber > secretNumber:
numberOfGuesses += 1
print('Your guess is too high.')
elif inputNumber < secretNumber:
numberOfGuesses += 1
print('Your guess is too low.')
elif inputNumber == secretNumber:
print('Your guess is correct, congratulations! You\'ve my number in ', numberOfGuesses, 'guesses.')
break
else:
print('Please enter a number between 1 and 20')
# Defining the variables used by the function
snum = 11
guesst(snum)
When the while loop repeats, you'll need to collect input from the user again, so your input statement should be in the while loop, not outside the function.
Your if statement should also be within the while loop.

How to fix guessing game

The objective is to create a simple program that generates a number between 1 and 100, it will then ask the user to guess this, if they guess outside of the number range it should tell them to guess again, if not it should tell them whether their guess was too high or too low, prompting them to guess again. Once they do guess the correct number it should tell them they've won and the number of tries it took for them to guess it correctly.
Here is what I have so far
import random
def play_game():
number = random.randint(1, 100)
print("Guess a number between 1 and 100 inclusive.")
count = 1
while True:
guess = int(input("Your guess: "))
if guess > 0 and guess <= 100:
#the age is valid
return play_game
else:
print("Invalid number.")
return play_game()
if guess < number:
print("Too low.")
elif guess > number:
print("Too high.")
elif guess == number:
print("You won! You guessed it in " + str(count) + " tries.\n")
return
count+=1
play_game()
The issue I'm currently running into is when it checks to see if their guess was between 1-100 instead of moving on to weather or not their number was too how or to low, it stays and loops.
If anyone could help me with this issue and review the code in general I'd appreciate it.
I think the problem is with some indentation and some logical problems in the flow.
When you call play_game() from inside the game, it starts a completely different game
with different random_number.
A good code that satisfies your condition might look like the following
import random
def play_game():
number = random.randint(1, 100)
print("Guess a number between 1 and 100 inclusive.")
count = 1
while True:
guess = int(input("Your guess: "))
if guess > 0 and guess <= 100:
if guess < number:
print("Too low.")
elif guess > number:
print("Too high.")
elif guess == number:
print("You won! You guessed it in " + str(count) + " tries.\n")
return
count+=1
else:
print("Invalid number.")
play_game()
You could re-adjust your code:
1. if no. within range, run your high, low, match checks
2. break if guess matches the no
import random
def play_game():
number = random.randint(1, 100)
print("Guess a number between 1 and 100 inclusive.")
count = 0
while True:
count += 1
guess = int(input("Your guess: "))
if guess > 0 and guess <= 100:
#the age is valid
if guess < number:
print("Too low.")
elif guess > number:
print("Too high.")
elif guess == number:
print("You won! You guessed it in " + str(count) + " tries.\n")
break
else:
print("Invalid number, try again")
play_game()
The issue you are running into is because of incorrect indentation. The if-else statements that check whether the number is within the valid range are at the same indentation level as the while loop and thus are not executed within it. Simply indenting should fix the problem.
Furthermore, you have called play_game without parenthesis, making it incorrect syntax for a function call. However, rather than checking if the number is greater than 0 and lesser than 100, it would more optimal to check whether number is lesser than 0 or greater than 100, and if that is the case, print invalid number and call play_game().
It would look something like this:
while True:
if guess < 0 and guess > 100:
print ("Invalid number.")
return play_game()
The rest of your code looks good. I've also attached the link on the section of indentations of the Python documentation here.

Number guessing game

import random
def guess_number():
numb = random.randrange (10) +1
guessestaken = 0
guess = input("whats your number")
while (guess != numb):
if (guess > numb):
print "too low"
elif(guess < numb):
print "too high"
else:
input("whats your next numb")
tries += 1
I am making a number guessing game with range 1 to 10 and I need help on getting the loop to stop. when I guess the number it keeps going
Here's a working example of what you're trying to do:
import random
guessesTaken = 0
number = random.randint(1, 20)
print('I am thinking of a number between 1 and 20.')
while guessesTaken < 6:
print('Take a guess.\n')
guess = input()
guess = int(guess)
guessesTaken = guessesTaken + 1
if guess < number:
print('Your guess is too low.')
if guess > number:
print('Your guess is too high.')
if guess == number:
break
if guess == number:
guessesTaken = str(guessesTaken)
print('Good job, You guessed my number in ' + guessesTaken + ' guesses!')
if guess != number:
number = str(number)
print('Nope. The number I was thinking of was ' + number)
You never reassign guess within the loop, so the truth value of guess != numb never changes. Put guess = before the input() call within the loop, or restructure it to a while True: ... break layout. Also, you only give the user another chance to guess the number if they get it exactly correct. Read through your code slowly and try to follow along with what the interpreter is doing.

Categories

Resources