I'm new to Python. I'm trying to write a small game that asks the end user to pick a number from 1 to 1000 and keep it in their head (the number is not provided to the program). The program should be able to find the number within 10 guesses. As I typically do, I went down the wrong path. My program works most of the time, but there are occasions where it does not find the number in under 10 guesses. Here is my code:
# script to guess a user's number between 1 and 1000 within 10 guesses
# import random so we can use it to generate random numbers
from random import randint
# Variables
lowerBound = 1
upperBound = 1000
numGuesses = 1
myGuess = 500
failed = False
# Welcome Message
print("#####################################################################################################"
"\n# #"
"\n# Please think of a number between 1 and 1000. I will attempt to guess the number in 10 tries. #"
"\n# #"
"\n#####################################################################################################")
while numGuesses <= 10:
# if the lower and upper bounds match we've found the number
if lowerBound == upperBound:
print(f"\nYour number is {str(lowerBound)}. It took me '{str(numGuesses)} guesses!")
break
print(f"\nIs the number {str(myGuess)}? If correct, type CORRECT. If low, type LOW. If high, type HIGH.")
# uncomment for var output
# print(f"\nGuesses = {str(numGuesses)}\nLower bound = {str(lowerBound)}\nUpper bound = {str(upperBound)}")
userFeedback = input("\nResponse: ").upper()
if userFeedback == 'HIGH':
print(f"\nGuess #{str(numGuesses)} was too high")
if numGuesses == 10:
failed = True
break
upperBound = myGuess - 1
myGuess = randint(lowerBound, upperBound)
elif userFeedback == 'LOW':
print(f"\nGuess #{str(numGuesses)} was too low")
if numGuesses == 10:
failed = True
break
lowerBound = myGuess + 1
myGuess = randint(lowerBound, upperBound)
elif userFeedback == 'CORRECT':
print(f"\nYour number is {str(myGuess)}! It took me {str(numGuesses)} guesses!")
break
numGuesses += 1
if failed:
print(f"\nMy final guess of {str(myGuess)} was not correct. I wasn't able to guess your number in 10 tries.")
It seems clear (now) that the way I'm whittling down the numbers is not going to work. I had originally thought to ask if it was 500 and, if lower, ask if it was 250. If lower again, ask if it was 125, and so on. If higher, ask if it was 750, 875 and so on. Is that the correct approach here?
I've been thinking about this too long and I believe I've cooked my brain. Thanks!
myGuess = int(math.ceil((myGuess) / 2))
is not correct.
If you have narrowed down the range to between 6 and 8 and you were guessing 7, your previous code would call 4 instead which is outside your search range.
if userFeedback == 'HIGH':
print(f"\nGuess #{numGuesses} was too high")
upperBound = myGuess - 1
elif userFeedback == 'LOW':
print(f"\nGuess #{numGuesses} was too low")
lowerBound = myGuess + 1
myGuess = int(lowerBound + ((upperBound - lowerBound) / 2))
I've updated my code and I think I have it. Thanks for the tips.
# script to guess a number between 1 and 1000 within 10 guesses
# Variables
lowerBound = 1
upperBound = 1000
numGuesses = 1
myGuess = 500
# Welcome Message
print("#####################################################################################################"
"\n# #"
"\n# Please think of a number between 1 and 1000. I will attempt to guess the number in 10 tries. #"
"\n# #"
"\n#####################################################################################################")
while numGuesses <= 10:
# uncomment next line for var output
# print(f"\nGuesses = {numGuesses}\nLower bound = {lowerBound}\nUpper bound = {upperBound}")
print(f"\nIs the number {myGuess}? If correct, type CORRECT. If low, type LOW. If high, type HIGH.")
userFeedback = input("\nResponse: ").upper()
if userFeedback == 'HIGH':
print(f"\nGuess #{numGuesses} was too high")
upperBound = myGuess
myGuess = (lowerBound + myGuess) // 2
elif userFeedback == 'LOW':
print(f"\nGuess #{numGuesses} was too low")
lowerBound = myGuess
myGuess = (upperBound + myGuess + 1) // 2
elif userFeedback == 'CORRECT':
print(f"\nYour number is {myGuess}! It took me {numGuesses} guesses!")
break
numGuesses += 1
Related
This is a guessing game, the variable ans here become type str at the while loop and cause an error. TypeError: '<' not supported between instances of 'str' and 'int'. Why is ans a str
import random
def guess(x):
ansnum = random.randint(1,x)
ans = 0
chance = 0
limit = 4
while ans!= ansnum and chance < limit :
ans = input(f"Guess between 1 and {x}: ")
chance += 1
if ans < ansnum:
print("close,too low")
else:
print ("close,too high")
else:
print("You Guess IT")
guess(10)
At first indeed you initialize it with 0, but it overlapped with the input() inside the loop thats returns a string, so the initialization doesn't mean anything. To solve it you have to cast the input to integer
import random
def guess(x):
ansnum = random.randint(1,x)
ans = 0
chance = 0
limit = 4
while ans!= ansnum and chance < limit :
ans = int(input(f"Guess between 1 and {x}: "))
chance += 1
if ans < ansnum:
print("close,too low")
else:
print ("close,too high")
else:
print("You Guess IT")
guess(10)
Problem: (Python) Write a program that asks the user to guess a random number between 1 and 10. If they guess right, they get 10 points added to their score, and they lose 1 point for an incorrect guess. Give the user five numbers to guess and print their score after all the guessing is done.
fs: I already have this code below, my problem now is how do I limit it to 5 attempts, also how to add "score system" like they get 10 points added to their score if they guess right, and they lose 1 point for an incorrect guess.
My code:
import random
target_num, guess_num = random.randint(1, 10), 0
while target_num != guess_num:
guess_num = int(input('Guess a number between 1 and 10 until you get it right : '))
print('Well guessed!')
Use attempt variable to track how many times the user has guessed.
Use score variable to track the accumulated score from guessing.
import random
target_num, guess_num = random.randint(1, 10), 0
attempt = 0
score = 0
while attempt < 5:
attempt += 1
guess_num = int(input('Guess a number between 1 and 10: '))
if target_num == guess_num:
score += 10
print('Correct! You get +10 points')
else:
score -= 1
print('Wrong! You get -1 point')
print("Your score: ", score, " points.")
You should do it like this -
import random
target_num, guess_num, tries, score= random.randint(1, 10), 0, 5, 0
for i in range(tries):
guess_num = int(input('Guess a number between 1 and 10 until you get it right : '))
if guess_num == target_num:
print('Well guessed!')
score+=10
else:
score-=1
print(f'Your final score is {score}')
So , the compiler returns a syntax error for my if loop in this code, I am very new to Python any & all help will greatly be appreciated.
enter code lower_number = int(input('Enter the lower number'))
higher_number = int(input('Enter the higher number'))
r = random.randint(higher_number,last_number)
print("you have got only ", round(math.log(upper - lower + 1, 2)) ," chances")
count = 0
while count < math.log(upper - lower + 1, 2) :
count = count + 1
guess = int(input("Type your guess here")
#the next line is the line that returns the error
if r == guess :
print("wow you genius")
break;
elif guess < x :
print("not high enough")
elif guess > x :
print("too high ")
if count > math.log(upper - lower + 1, 2):
print("sorry, try next time")
As #Gulzar correctly suggested, you have several indentation errors and your code is not complete, so it's difficult for us to reproduce your use case.
Nevertheless this might help you:
count = 0
while count < math.log(upper - lower + 1, 2) :
count = count + 1
guess = int(input("Type your guess here"))
#the next line is the line that returns the error
if r == guess :
print("wow you genius")
break
elif guess < x :
print("not high enough")
elif guess > x :
print("too high ")
if count > math.log(upper - lower + 1, 2):
print("sorry, try next time")
The problems in your while loop were:
indentation (pay attention, it is fundamental in python)
a missing parenthesis in the line guess = int(input("Type your guess here"))
I have started a python beginner project where the computer guesses the user's number by entering whether it's higher or lower than x. However, I have managed the first part but my program stops and does not carry on. My guess is that I need to include a loop somewhere to repeat the nextguess() within the code but I cannot figure out where.
This is my code:
maxnum = 1000
min = 1
guess = 500
print("1 = Higher 2 = Lower 3 = Correct")
print("Pick a number dont tell me what it is!")
print("The highest number you can pick is:",maxnum)
print("The lowest number you can pick is:",min)
print("Is it higher or lower than:",guess)
maxnum = maxnum +1;
choice = input()
choiceprop = int(choice)
def nextguess():
guess = (maxnum + min) / 2
print("Is it lower or higher than:", guess)
if choiceprop == 1:
min = guess
nextguess()
maxnum = maxnum +1;
if choiceprop == 2:
maxnum = guess
nextguess()
maxnum = maxnum +1;
if choiceprop == 3:
print("nice!");
Looks like you're trying to use binary search to zero down on the user's number, you'll need to keep an eye on how numbers are rounded and how you shift your boundaries in response to the user's input.
As far as keeping it going beyond the first input, you'll need to put the portions that take the user's input and makes the next guess in a while loop, making sure you have a code stop condition or logic within the loop body to prevent it from looping infinitely.
Here's an example of how it could be done:
import math
def main():
min = 0
max = 1000
print("Pick a number dont tell me what it is!")
print("The highest number you can pick is:", max)
print("The lowest number you can pick is:", min)
while max >= min:
guess = math.ceil((max + min) / 2)
print("Is it higher or lower than: ", guess)
print('1. Higher')
print('2. Lower')
print('3. Correct')
choiceprop = int(input('Option: '))
if choiceprop == 1:
min = guess + 1 # guess can be excluded safely
elif choiceprop == 2:
max = guess - 1
else:
print('nice')
break
main()
Think about what part of the code needs to be repeated: it’s the part that asks for a next input, and generates a next guess.
That’s pretty much all of your code, except for the preamble, and the definition of nextguess:
def nextguess():
guess = (maxnum + min) / 2
print("Is it lower or higher than:", guess)
maxnum = 1000
min = 1
guess = 500
print("1 = Higher 2 = Lower 3 = Correct")
print("Pick a number dont tell me what it is!")
print("The highest number you can pick is:", maxnum)
print("The lowest number you can pick is:", min)
print("Is it higher or lower than:", guess)
while True:
choice = input()
choiceprop = int(choice)
if choiceprop == 1:
min = guess
elif choiceprop == 2:
maxnum = guess
elif choiceprop == 3:
print("nice!")
break
nextguess()
maxnum = maxnum + 1
However, this code still won’t work, because your logic for generating guesses is incorrect: why are you increasing maxnum? Surely the maximum can’t change. Next, your nextguess generates non-integral guesses. You need to restrict this to integer numbers.
Finally, nextguess also won’t change your global variable guess, you need to return your next guess, and assign it:
def nextguess(min, max):
guess = (min + max) // 2
print("Is it lower or higher than:", guess)
return guess
… and now, when calling nextguess you need to pass it a minumum and maximum bound.
With this change, you also don’t need to hard-code your initial guess: just call nextguess at the beginning.
def nextguess(min, max):
guess = (min + max) // 2
print("Is it lower or higher than:", guess)
return guess
max = 1000
min = 1
print("1 = Higher 2 = Lower 3 = Correct")
print("Pick a number dont tell me what it is!")
print("The highest number you can pick is:", max)
print("The lowest number you can pick is:", min)
while True:
guess = nextguess(min, max)
choice = int(input())
if choice == 1:
min = guess
elif choice == 2:
max = guess
elif choice == 3:
print("nice!")
break
guess = nextguess(min, max)
(PS: Don’t use ; in Python.)
A Python(3.7) beginner here. This guessing game gives range clues:
Cold
Warm
Hot
Depending on how close to answer player is.
Problem: how to add extra 3 incremental clues:
Colder
Warmer
Hotter
Colder is used if the next guess is further from answer.
Warmer is used if the next guess is closer to answer.
Hotter is used instead of Warmer if its in the Hot range.
The first guess produces the range clues Cold, Warm or Hot.
The subsequent guesses will produce incremetal clues Colder or Warmer/Hotter if while they land in same range as previous guess.
If they fall out of the range, the range clues Cold, Warm or Hot will be produced first and then Colder or Warmer/Hotter while in that range. in other words Cold, Warm or Hot range clues have higher priority than incremental Colder or Warmer/Hotter.
print("The secret number is somewhere between 0 and 100. You have 5 guesses.")
user_input = int(input('Make a guess '))
count = 0
while user_input is not 41 and count < 4:
count = count + 1
how_close_to_answer = 41 - user_input
if 5 < how_close_to_answer.__abs__() < 20:
user_input = int(input(f'Warm. Remaining guesses {5 - count} '))
elif how_close_to_answer.__abs__() >= 20:
user_input = int(input(f'Cold. Remaining guesses {5 - count} '))
else:
user_input = int(input(f'Hot. Remaining guesses {5 - count} '))
if user_input is not 41:
print('You Lose!')
else:
print('You Win!')
print(f"It took you {count + 1} guesses to get this correct.")
For example (in case of infinite guesses n):
player guesses = 10 , desired outcome 'Cold. Remaining guesses (n-1) '
next guess = 15 , desired outcome 'Warmer. Remaining guesses (n-2) '
next guess = 12 , desired outcome 'Colder. Remaining guesses (n-3) '
next guess = 36 , desired outcome 'Hot. Remaining guesses (n-4) '
next guess = 37 , desired outcome 'Hotter. Remaining guesses (n-5) '
next guess = 30 , desired outcome 'Warm. Remaining guesses (n-6) '
In 4. example - number 36 is Warmer than previous 12, but it also falls in the Hot range so the Hot clue is given instead.
in 6. example - number 30 is Colder than previous 37, but it also falls in the Warm range so the Warm clue is given instead.
I took num as a random generated number instead of 41.
import random
print("The secret number is somewhere between 0 and 100. You have 5 guesses.")
user_input = int(input('Make a guess '))
count = 0
num = random.randint(1,101)
while user_input is not num and count < 4:
#uncomment the line below to see random generated number
#print('Generated Random Number= '+str(num))
count = count + 1
how_close_to_answer = num - user_input
if abs(how_close_to_answer)>5 and abs(how_close_to_answer) <20 :
user_input = int(input(f'Warm. Remaining guesses {5 - count} '))
elif abs(how_close_to_answer) >= 20 :
user_input = int(input(f'Cold. Remaining guesses {5 - count} '))
else:
user_input = int(input(f'Hot. Remaining guesses {5 - count} '))
if user_input is not num:
print('You Lose!')
else:
print('You Win!')
print(f"It took you {count + 1} guesses to get this correct.")
As far as i understood , the above program generates a random number and you need to guess that number ,
if your guessed number is less then or equivalent to 5 digits closer to that random number it will tell you hot
if its greater than 5 and less than 20 then it will tell you warm
on greater than 20 it will give you cold
Hope this will help you !!
This is the closest I could get to what you asked for. The comments on your original question are worth a read in my opinion but I think this does exactly what you asked for in the question.
print("The secret number is somewhere between 0 and 100. You have 5 guesses.")
user_input = int(input('Make a guess '))
count = 0
last_distance = -1
while user_input is not 41 and count < 4:
count = count + 1
how_close_to_answer = (41 - user_input)
how_close_to_answer = how_close_to_answer.__abs__()
if how_close_to_answer <= 5 and last_distance > 5:
user_input = int(input(f'Hot. Remaining guesses {5 - count} '))
elif last_distance == -1:
if 5 < how_close_to_answer < 20:
user_input = int(input(f'Warm. Remaining guesses {5 - count} '))
elif how_close_to_answer >= 20:
user_input = int(input(f'Cold. Remaining guesses {5 - count} '))
elif how_close_to_answer <= 5:
user_input = int(input(f'Hot. Remaining guesses {5 - count} '))
else:
if how_close_to_answer < last_distance:
if how_close_to_answer <= 5:
user_input = int(input(f'Hotter. Remaining guesses {5 - count} '))
else:
user_input = int(input(f'Warmer. Remaining guesses {5 - count} '))
elif how_close_to_answer > last_distance:
user_input = int(input(f'Colder. Remaining guesses {5 - count} '))
last_distance = how_close_to_answer
if user_input is not 41:
print('You Lose!')
else:
print('You Win!')
print(f"It took you {count + 1} guesses to get this correct.")
Hope this is what helps