Countdown the chances in loop for guessing game - python

I made five chances for the guesser to guess the random number. Every time the guesser did wrong, I want to print:
Nice try, guess again (try bigger), you get {x} chance left.
The x is a countdown, so the first wrong guess will say you get 4 chances left, then another wrong, three chances left, and so on. How can I do that? Or, how to add a loop on the x.
So this is my unsuccessful code:
import random
secret_num = random.randint(1, 20)
print('Guess the number from 1-20 (you get 5 chances)')
for guess_chance in range(1, 6):
guess = int(input("Input guess number: "))
if guess < secret_num:
x = 5
x -= 1
print(f'Nice try, guess again (try bigger), you get {x} chance left.')
elif guess > secret_num:
x = 5
x -= 1
print(f'Nice try, guess again (try smaller), you get {x} chance left.')
else:
break
if guess == secret_num:
print('Congratz, you guess correctly in' + str(guess_chance) + 'times.')
else:
print('Nope, the correct number is ' + str(secret_num) + '.')

You need to do x = 5 before for guess_chance in range...) and remove it from inside the loop.
print('Guess the number from 1-20 (you get 5 chances)')
x = 5
for guess_chance in range(1, 6):
guess = int(input("Input guess number: "))
if guess < secret_num:
x -= 1
print(f'Nice try, guess again (try bigger), you get {x} chance left.')
elif guess > secret_num:
x -= 1
print(f'Nice try, guess again (try smaller), you get {x} chance left.')
else:
break
Otherwise, each guess you are resetting it to 5 tries and then subtracting one... which presumably always shows 4 tries...
There are many other ways to solve this... I just picked the one that changed your code the least
and when combined with your range this is a bit redundant
x = 6 - guess_chance would work
as would just iterating the range in reverse

Related

Guess 4 digit combination game

I am trying a similar thing like this: 4 Digit Guessing Game Python . With little changes.
The program generates random numbers between 999 and 10000.User after every failed attempt gets how many numbers he guess in the right spot and how many numbers he got right but didn't guess position correctly.
Etc. a random number is 3691 and the user guess is 3619. He gets 2 numbers in the correct position (3 and 6) and also 2 numbers correct but in the wrong position (1 and 9).
There is no output when for numbers he didn't guess and guessing is repeating until all 4 digits are guessed in the right spot.
My idea is we save digits of the random number to a list and then do the same thing with user guess number. Then we compare the first item of both lists etc. combination_list[0] == guess_ist[0] and if it's correct we add +1 on counter we call correct.
The problem is I don't have an idea for numbers that are guessed correctly but are not in the correct position.
import random
combination = random.randint(1000, 9999)
print(combination)
digits_combination, digits_guess= [], []
temp = combination
while temp > 0:
digits_combination.append(temp % 10)
temp //= 10
digits_combination.reverse()
print(digits_combination)
guess= int(input("Your numbers are? "))
while not 999 < pokusaj < 10000:
pokusaj = int(input("Your numbers are? "))
if guess!= combination:
while guess> 0:
digits_guess.append(guess% 10)
guess//= 10
digits_guess.reverse()
if guess == combination:
print("Your combination is correct.")
correct_position= 0
correct= 0
test = digits_combination[:] # I copied the list here
while guess!= combination:
while guess> 0:
digits_guess.append(guess% 10)
guess //= 10
digits_guess.reverse()
if digits_guess[0] == test[0]:
correct_position += 1
I have this solution. I suggestion you to cast to string and after cast to list to get a list of number digits instead to use a while loop. For the question you can try to use "in" keywords to check if number in digits_combination but not in right position.
import random
combination = random.randint(1000, 9999)
print(combination)
digits_combination = list(str(combination))
guess= int(input("Your numbers are? "))
while not 999 < guess < 10000:
guess = int(input("Your numbers are? "))
digits_guess = list(str(guess))
if guess == combination:
print("Your combination is correct.")
correct_position = 0
correct = 0
for index, value in enumerate(digits_guess):
if value == digits_combination[index]:
correct_position += 1
elif value in digits_combination:
correct += 1

Python: Can't figure out why my loop skips the right answer

I decided to make a small project to test my skills as I continue to learn Python in my free time.
The game consists of the user guessing the right number that is randomly generated within a certain amount of tries. The user first enters the range of numbers they want to guess from. Then they get their first try at guessing the right number (I have the randomly generated number displayed on purpose to test my code as I continue). I cannot figure out why when I enter the same number as the randomly generated number, I get the error that would pop up when you guess the wrong number. But if I enter that same number after I am prompted to guess for the randomly generated number again, I get a success note prompted to me. I've been trying different variations all day.
import random
print("Guessing Game")
rangeAmount = int(input("From 1 to what number do you want to guess from (Maximum amount is 50)? "))
correctNum = random.randint(1, rangeAmount)
wrongCount = 0
userScore = 0
print("-" * 50)
while rangeAmount:
if 1 < rangeAmount < 10:
guesses = 3
print("Guesses allowed: 3")
break
if 1 < rangeAmount < 20:
guesses = 4
break
if 1 < rangeAmount < 30:
guesses = 5
break
if 1 < rangeAmount < 40:
guesses = 6
break
if 1 < rangeAmount < 50:
guesses = 7
break
print("Correct number: " + str(correctNum))
print("Guess amount: " + str(guesses))
print("-" * 50)
userGuess = input("Make a guessing attempt for the correct number: ")
while userScore != 3:
if wrongCount != guesses:
if userGuess is correctNum:
userScore += 1
print("You got the right answer")
break
else:
wrongCount += 1
print("Current guess count: {}".format(wrongCount))
userGuess = int(input("Wrong answer, try again: "))
if wrongCount == guesses:
print("Out of guesses, score is : {}".format(userScore))
userScore -= 1
break
if userScore == 3:
print("You won the game!")
Output:
Guessing Game
From 1 to what number do you want to guess from (Maximum amount is 50)? 23
--------------------------------------------------
Correct number: 5
Guess amount: 5
--------------------------------------------------
Make a guessing attempt for the correct number: 5
Current guess count: 1
Wrong answer, try again: 5
You got the right answer
Process finished with exit code 0
First, your maximum range is 50, but it is not included in your first while loop (ends at 49), change the last line to <= 50. You can remove the while loop, and change the if statements to if/elifs. Second, your indentation is off in the while userScore != 3: loop, but that could just be a copy/paste error.
And now for the most likely cause of the error,
userGuess = input("Make a guessing attempt for the correct number: ")
is a string, don't forget to make it an int before you compare it to another int.

what is causing reference before assignment errors in below code?

I'm getting this error with refrenced before assignment and im not sure how to fix it.
I havent tried anything at the moment. It would be appreciated if this could be answered. (im just trying to fill up more words so it can be posted)
this is the error code i am getting:
number = int(number)
UnboundLocalError: local variable 'number' referenced before assignment
And this is the rest of my code
import random
import sys
again = True
while True:
myName = input('Hello, Enter your name to get started')
if myName.isdigit():
print('ERROR,Your Name is not a number, please try again')
print('')
continue
break
myName = str(myName.capitalize())
print('')
print('Hi {}, This is Guessing Game, a game where you have a certain amount of attempts to guess a randomly generated number. Each level has a different amount of attempts and a higher range of number. After each guess, press enter and the program will determine if your guess is correct or incorrect.' .format (myName))
print('--------------------------------------------------------------------------------')
while True:
level = input('{}, Please select a level between 1 and 3. Level 1 being the easiest and 3 being the hardest')
if not level.isdigit():
print('Please enter a number between 1 and 3. Do not enter a number in word form')
continue
break
def guessNumber(): # Tells the program where to restart if the user wants to play again
guessesTaken = 0
List = []
if level == 1:
number = random.randint (1, 16)
print('You chose Level 1, Guess a number a between 1 and 16, you have 6 guesses.')
allowedGuesses = 6
boundary = 16
if level == 2: # The code for level 2
number = random.randint (1,32)
print('You chose Level 2, Guess a number between 1 and 32, You have 8 guesses.')
allowedGuesses = 8
boundary = 32
if level == 3:
number = random.randint (1, 40)
print('You chose Level 3, Guess a number between 1 and 40, you have 10 guesses.')
allowedGuesses = 10
boundary = 40
if level == 4:
number = random.randint (1, 50)
print('You chose Level 4, Guess a number between 1 and 50, you have 10 guesses.')
allowedGuesses = 10
boundary = 50
if level == 5:
number = random.randint (1, 60)
print('You chose Level 5, Guess a number between 1 and 60, you have 10 guesses.')
allowedGuesses = 10
boundary = 60
guess = input()
guess = int(guess)
while guessesTaken < allowedGuesses:
guessesTaken = guessesTaken + 1
guessesLeft = allowedGuesses - guessesTaken
if guess < number:
List.append(guess)
print('Your guess is too low, You must guess a higher number, you have {} guesses remaining. You have guessed the numbers {}, Take another guess' .format (guessesLeft, List))
if guess > number:
List.append(guess)
print('Your guess is too high, You must guess a lower number, you have {} guesses remaining. You have guessed the numbers {}, Take another guess' .format (guessesLeft, List))
if guess > boundary:
List.append(guess)
print('You must input a number between 1 and 16. You have {} guesses remaining. You have guessed the numbers {}, Take another guess' .format (guessesLeft, List))
if guess == number:
List.append(guess)
print('Good Job {}!, You guessed my number in {} guesses. You guessed the numbers {}.' .format (myName, guessesTaken, List))
print('Your high score for your previous game was {}' .format(guessesTaken))
else:
number = int(number)
print('')
print('--------------------------------------------------------------------------------')
print('Sorry {}, Your gueses were incorrect, The number I was thinking of was {}. You guessed the numbers {}.' .format(myName, number, List))
guessNumber()
print('')
print('It is recommended to pick a harder level if you chose to progress')
print('')
while True:
again = input('If you want to play again press 1, if you want to stop playing press 2')
if not again.isdigit():
print('ERROR: Please enter a number that is 1 or 2. Do not enter the number in word form')
continue
break
if again == 1:
level + 1
guessNumber()
if again == 2:
print('Thanks for playing Guessing Game :)')
sys.exit(0)
In your code you are getting level as input and checking that if level is in between 1 to 5.
else you are trying number = int(number)
but you should write number = int(level).
Since level is a string rather than a number, none of the conditions like
if level == 1:
will succeed. So none of the assignments like number = random.randint (1, 16) ever execute, and number is never assigned.
Since if level == 5: doesn't succeed, it goes into the else: block, which starts with
number = int(number)
Since none of the other number assignments took place, this tries to use int(number) before the variable has been assigned, which doesn't work.
I'm not sure why you even have this assignment there. When number is assigned, it's always set to an integer, so there's no need to use int(number).
You need to use
level = int(level)`
after you confirm that it contains digits. And you need to do similarly with again.
There are a number of other problems with your code. For instance, the code that asks for the user's guess and checks it is inside the if level == 5: block, it should run in all the levels.
When you have a series of mutually exclusive tests, you should use elif for each successive test. If you just use if for each of them, and then use else: at the end, that else: will only apply to the last test, so it will be executed even if one of the early tests also succeeded.

Python. Variable in while loop not updating.

I'm very new to programming and I've encountered a problem with a basic guessing game I've been writing.
x is a random number generated by the computer. The program is supposed to compare the absolute value of (previous_guess - x) and the new guess minus x and tell the user if their new guess is closer or further away.
But the variable previous_guess isn't updating with the new value.
Any help would be appreciated.
Here is the code so far:
###Guessing Game
import random
n = 100
x = random.randint(1,n)
print("I'm thinking of a number between 1 and ", n)
##print(x) ## testing/cheating.
count = 0
while True:
previous_guess = 0 # Should update with old guess to be compared with new guess
guess = int(input("Guess the number, or enter number greater that %d to quit." % n))
count += 1
print(previous_guess)
print("Guesses: ", count)
if guess > n:
print("Goodbye.")
break
elif count < 2 and guess != x:
print("Unlucky.")
previous_guess = guess #####
elif count >= 2 and guess != x:
if abs(guess - x) < abs(previous_guess - x):
previous_guess = guess #####
print("Getting warmer...")
else:
previous_guess = guess #####
print("Getting colder...")
elif guess == x:
print("You win! %d is correct! Guessed in %d attempt(s)." % (x,count))
break
Your previous guess is being reinitialized every time you loop. This is a very common error in programming so it's not just you!
Change it to:
previous_guess = 0
while True:
#Rest of code follows
Things you should be thinking about when stuff like this shows up.
Where is your variable declared?
Where is your variable initialized?
Where is your variable being used?
If you are unfamiliar with those terms it's okay! Look em up! As a programmer you HAVE to get good at googling or searching documentation (or asking things on stack overflow, which it would appear you have figured out).
Something else that is critical to coding things that work is learning how to debug.
Google "python debug tutorial", find one that makes sense (make sure that you can actually follow the tutorial) and off you go.
You're resetting previous_guess to 0 every time the loop begins again, hence throwing away the actual previous guess. Instead, you want:
previous_guess = 0
while True:
guess = ....
You need to initialize previous guess before while loop. Otherwise it will be initialized again and again.
You have updated previous guess in multiple places. You can make it simpler:
import random
n = 100
x = random.randint(1,n)
print("I'm thinking of a number between 1 and ", n)
##print(x) ## testing/cheating.
count = 0
previous_guess = 0 # Should update with old guess to be compared with new guess
while True:
guess = int(input("Guess the number, or enter number greater that %d to quit." % n))
count += 1
print(previous_guess)
print("Guesses: ", count)
if guess > n:
print("Goodbye.")
break
elif count < 2 and guess != x:
print("Unlucky.")
elif count >= 2 and guess != x:
if abs(guess - x) < abs(previous_guess - x):
print("Getting warmer...")
else:
print("Getting colder...")
elif guess == x:
print("You win! %d is correct! Guessed in %d attempt(s)." % (x,count))
break
previous_guess = guess #####
You need to initialize previous guess before while loop Otherwise it will be initialized again and again. You have to set the value of previous guess to x the computer generator and when you move on after loop you have to update the previous guess to next simply like this:
Add before while { previous_guess = x }
Add After While { previous_guess += x }
###Guessing Game
import random
n = 100
x = random.randint(1,n)
print("I'm thinking of a number between 1 and ", n)
##print(x) ## testing/cheating.
count = 0
previous_guess = x
while True:
# Should update with old guess to be compared with new guess
previous_guess += x
guess = int(input("Guess the number, or enter number greater that %d to quit." % n))
count += 1
print(previous_guess)
print("Guesses: ", count)
if guess > n:
print("Goodbye.")
break
elif count < 2 and guess != x:
print("Unlucky.")
previous_guess = guess #####
elif count >= 2 and guess != x:
if abs(guess - x) < abs(previous_guess - x):
previous_guess = guess #####
print("Getting warmer...")
else:
previous_guess = guess #####
print("Getting colder...")
elif guess == x:
print("You win! %d is correct! Guessed in %d attempt(s)." % (x,count))
break
Picture When u win
Picture When u loose

Performing binary search to guess a random number, but the number of guesses not matching

I have written a simple guessing game and a method to guess it...
from gasp import *
number = random_between(1, 1000)
guesses = 0
while True:
guess = input("Guess the number between 1 and 1000: ")
guesses += 1
if guess > number:
print "Too high!"
elif guess < number:
print "Too low!"
else:
print "\n\nCongratulations, you got it in %d guesses!\n\n" % guesses
break
Now according to the question the max number of guesses should be equal to 11 if the proper strategy is used.I used binary search to get the right number, but the the number of guesses are never more than 10. To check I did the following and it produced a non terminating loop.
from gasp import *
guesses = 0
big = 1000
small = 1
while guesses != 11
number = random_between(1, 1000)
while True:
guess = (big + small) / 2
guesses += 1
if guess > number:
print "Too high!"
big = guess
elif guess < number:
print "Too low!"
small = guess
else:
print "\n\nCongratulations, you got it in %d guesses!\n\n" % guesses
break
So who is right am I making some mistake or the number of guesses required can't be more than 10 and the question is wrong.
>>> from math import log, ceil
>>> ceil(log(1000, 2))
10.0
Let's see:
A number between 1 and 1 requires 1 guess
A number between 1 and 3 requires 2 guesses at most
A number between 1 and 7 requires 3 guesses at most
A number between 1 and 15 requires 4 guesses at most
A number between 1 and 31 requires 5 guesses at most
...
In other words, n guesses are enough to cover the range from 1 to (2**n)-1.
For n=10, this range is from 1 to 1023. Since 1023 >= 1000, your conclusion about ten guesses is correct.
That said, the code you used to verify this conclusion is buggy, since it fails to re-initialize big and small and guesses whenever you move on to the next number. Also, instead of generating the numbers randomly, you could just test every number between 1 and 1000 and have a deterministic algorithm with finite runtime.

Categories

Resources