While loops, if-else statements: Guess my number game - python

I'm a beginner using python, and am writing a "guess my number game". So far I have everything working fine. The computer picks a random number between 1 and 3 and asks the player to guess the number. If the guess is higher than the random number, the program prints "Lower", and vice versa. The player only has 5 tries, and when they run out, the player gets a message and the game ends. If the player guesses correctly, they are congratulated and the game ends. However, sometimes when the number is guessed correctly, the program doesn't print the congratulatory message and I can't figure out why...
import random
print("\tWelcome to 'Guess My Number'!:")
print("\nI'm thinking of a numer between 1 and 100.")
print("Guess carefully, you only have 5 tries!.\n")
#sets initial values
the_number = random.randint(1,3)
guess = int(input("Take a guess: "))
tries = 1
guesses = 4
#guessing loop
while guess != the_number:
if guess > the_number:
print("Lower...")
elif guesses <= 0:
print("Sorry, you're out of guesses! Try again...")
break
elif guess < the_number:
print("Higher...")
guess = int(input("Take a guess: "))
tries += 1
guesses -= 1
if guess == the_number:
print("You guessed it! The number was", the_number)
print("And it only took you", tries, "tries!\n")

To answer your original question about the lack of congratulatory message for correct number, end the code with input(), to ensure it does not terminate before displaying the last message.
Order of calculation:
give input guess
reduce guesses (starting at 5), increase tries (starting at 1)
immediate break if guesses == 0
evaluate guess (lower, higher or equal, which would end while loop)
import random
print("\tWelcome to 'Guess My Number'!:")
print("\nI'm thinking of a numer between 1 and 3.")
print("Guess carefully, you only have 5 tries!.\n")
#sets initial values
the_number = random.randint(1,3)
guess = int(input("Take a guess: "))
tries = 1
guesses = 5
#guessing loop
while guess != the_number:
tries += 1
guesses -= 1
if guesses == 0:
print("Sorry, you're out of guesses! Try again...")
break
elif guess > the_number:
print("Lower...")
elif guess < the_number:
print("Higher...")
guess = int(input("Take a guess: "))
if guess == the_number:
print("You guessed it! The number was", the_number)
print("And it only took you", tries, "tries!\n")
input()

Assuming everything else works, un-indent the final check. You can't check guess == the_number while it isn't equal
#guessing loop
while guess != the_number:
# do logic
# outside guessing loop
if guesses > 0:
print("You guessed it! The number was", the_number)
print("And it only took you", tries, "tries!\n")

If you guess the number in your first try, the program will require another guess nevertheless since
guess = int(input("Take a guess: "))
tries += 1
guesses -= 1
comes before
if guess == the_number:
print("You guessed it! The number was", the_number)
print("And it only took you", tries, "tries!\n")
when you already asked for a guess outside the loop. You should only ask for input inside the loop:
the_number = random.randint(1,3)
tries = 0
guesses = 5
#guessing loop
guess = None
while guess != the_number:
guess = int(input("Take a guess: "))
tries += 1
guesses -= 1
if guess > the_number:
print("Lower...")
elif guess < the_number:
print("Higher...")
if guess == the_number:
print("You guessed it! The number was", the_number)
print("And it only took you", tries, "tries!\n")
if guesses <= 0:
print("Sorry, you're out of guesses! Try again...")
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!

My iteration doesn't work when it runs after the first time

When I enter the correct word, it prints out congratulations, but when I enter it for the second or third try, it doesn't work
secret_word = "hello"
tries = 1
guess_word = input("Guess a word: ")
while tries < 3:
if secret_word != guess_word:
tries += 1
print("Sorry, word not found, you have", 4 - tries, "tries left")
guess_word = input("Guess a word")
if tries == 3:
print("Sorry, you are out of tries, better luck next time !!!")
break
else:
print("Congratulations! You've done it!")
break
In this section of code:
print("Sorry, word not found, you have", 4 - tries, "tries left")
guess_word = input("Guess a word")
if tries == 3:
print("Sorry, you are out of tries, better luck next time !!!")
you don't check to see whether the guess was right before telling the user they've lost. It might be easier if you base the loop on whether the guess was right, and use the tries counter to decide whether to break or continue:
secret_word = "hello"
tries = 0
while input("Guess a word: ") != secret_word:
tries += 1
if tries < 3:
print(f"Sorry, word not found, you have {3 - tries} tries left")
else:
print("Sorry, you are out of tries, better luck next time !!!")
break
else:
print("Congratulations! You've done it!")
It's better if you could put this line,
guess_word = input("Guess a word: ")
... in the while loop, so you wouldn't have 2 of the same lines.
You can also state the number of tries to 3 instead of 1. Set the number you want, and decrement downwards. To avoid code like, "4 - tries"
print("Sorry, word not found, you have", 4 - tries, "tries left")
secret_word = "hello"
tries = 3
while tries > 0:
guess_word = input("Guess a word: ")
if secret_word != guess_word:
tries -= 1
print("Sorry, word not found, you have", tries, "tries left")
if tries == 0:
print("Ran out of tries!")
break
else:
print("Congratulations! You've done it!")
break
Your current code only allows 2 tries to be made. The 3rd try even if you get it right, it will be thrown out. Let me know if there's anything wrong with my solution!
When you say while tries < 3 you only go up to 2 because thats the last whole number that's smaller than 3. If you want to include 3 you can change it to while tries <= 3
tries can never reach 3 as you have put while tries < 3
change it to tries<=3

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.

Python Number Guessing Game Need Help Avoiding Counting Duplicates in "Number of Guesses"

I am brand new to learning Python and am building a very simple number guessing game. The user guesses a number between 1-100, and are given feedback on whether their guess is too low or too high. When they guess the number correctly, the program tells them how many guesses they took. What I need help with: telling the user when they guessed a duplicate number if they have entered it already. I also want to exclude any duplicate guesses from the final guess count. What is the easiest way to do this?
Here is my game so far:
import random
print("Guess a number between 1-100")
the_number = random.randint(1, 100)
guess = int(input(""))
tries = 0
while guess != the_number:
if guess > the_number:
print("Lower")
if guess < the_number:
print("Higher")
guess = int(input("Guess again: "))
tries += 1
if guess == the_number:
print("You win! The number was", the_number)
print("And it only took you", tries, "tries!\n")
Keep track of the numbers guessed, only increasing if the user has not guessed a number already in our guessed set:
import random
print("Guess a number between 1-100")
the_number = random.randint(1, 100)
tries = 0
# store all the user guesses
guessed = set()
while True:
guess = int(input("Guess a number: "))
# if the guess is in our guesses set, the user has guessed before
if guess in guessed:
print("You already guessed that number!")
continue
# will only increment for unique guessed
tries += 1
if guess == the_number:
print("You win! The number was", the_number)
print("And it only took you", tries, "tries!\n")
break
elif guess > the_number:
print("Lower")
# if it's not == or >, it has to be <
else:
print("Higher")
# add guess each time
guessed.add(guess)
You also had some logic in regard to your ordering like taking a guess outside the loop which could have meant you never entered the loop if the user guessed first time.
this is how you should write the code.
import random
debug = True
def number_guessing():
previous_guesses = set()
tries = 0
print("Guess a number between 1-100")
random_number = random.randint(1, 100)
while True:
guess = int(input())
if guess in previous_guesses:
print("You already tried that number")
continue
previous_guesses.add(guess)
tries += 1
if random_number < guess:
print(f"Lower => previous attempts [{previous_guesses}] tries [{tries}]") if debug is True else None
elif random_number > guess:
print(f"Higher => previous attempts [{previous_guesses}] tries [{tries}]") if debug is True else None
elif guess == random_number:
print("You win! The number was", random_number)
print(f"And it only took you {tries} attempt{'s' if tries>1 else ''}!\n")
break
number_guessing()

Categories

Resources