Guess the number game optimization (user creates number, computer guesses) - python

I am very new to programming so I decided to start with Python about 4 or 5 days ago. I came across a challenge that asked for me to create a "Guess the number" game. After completion, the "hard challenge" was to create a guess the number game that the user creates the number and the computer (AI) guesses.
So far I have come up with this and it works, but it could be better and I'll explain.
from random import randint
print ("In this program you will enter a number between 1 - 100."
"\nAfter the computer will try to guess your number!")
number = 0
while number < 1 or number >100:
number = int(input("\n\nEnter a number for the computer to guess: "))
if number > 100:
print ("Number must be lower than or equal to 100!")
if number < 1:
print ("Number must be greater than or equal to 1!")
guess = randint(1, 100)
print ("The computer takes a guess...", guess)
while guess != number:
if guess > number:
guess -= 1
guess = randint(1, guess)
else:
guess += 1
guess = randint(guess, 100)
print ("The computer takes a guess...", guess)
print ("The computer guessed", guess, "and it was correct!")
This is what happened on my last run:
Enter a number for the computer to guess: 78
The computer takes a guess... 74
The computer takes a guess... 89
The computer takes a guess... 55
The computer takes a guess... 78
The computer guessed 78 and it was correct!
Notice that it works, however when the computer guessed 74, it then guessed a higher number to 89. The number is too high so the computer guesses a lower number, however the number chosen was 55. Is there a way that I can have the computer guess a number that is lower than 89, but higher than 74? Would this require additional variables or more complex if, elif, else statements?
Thank you Ryan Haining
I used the code from your reply and altered it slightly so the guess is always random. If you see this, let me know if this is the best way to do so.
from random import randint
def computer_guess(num):
low = 1
high = 100
# This will make the computer's first guess random
guess = randint(1,100)
while guess != num:
print("The computer takes a guess...", guess)
if guess > num:
high = guess
elif guess < num:
low = guess + 1
# having the next guess be after the elif statement
# will allow for the random guess to take place
# instead of the first guess being 50 each time
# or whatever the outcome of your low+high division
guess = (low+high)//2
print("The computer guessed", guess, "and it was correct!")
def main():
num = int(input("Enter a number: "))
if num < 1 or num > 100:
print("Must be in range [1, 100]")
else:
computer_guess(num)
if __name__ == '__main__':
main()

what you are looking for is the classic binary search algorithm
def computer_guess(num):
low = 1
high = 100
guess = (low+high)//2
while guess != num:
guess = (low+high)//2
print("The computer takes a guess...", guess)
if guess > num:
high = guess
elif guess < num:
low = guess + 1
print("The computer guessed", guess, "and it was correct!")
def main():
num = int(input("Enter a number: "))
if num < 1 or num > 100:
print("Must be in range [1, 100]")
else:
computer_guess(num)
if __name__ == '__main__':
main()
The algorithm works by selecting a low and high limit to start with (in your case low=1 and high=100). It then checks the midpoint between them.
If the midpoint is less than number, the midpoint becomes the new lower bound. If the midpoint is higher, it becomes the new upper bound. After doing this a new midpoint is generated between the upper and lower bound.
To illustrate an example let's say you're looking for 82.
Here's a sample run
Enter a number: 82
The computer takes a guess... 50
The computer takes a guess... 75
The computer takes a guess... 88
The computer takes a guess... 82
The computer guessed 82 and it was correct!
So what's happening here in each step?
low = 1, high = 100 => guess = 50 50 < 82 so low = 51
low = 51, high = 100 => guess = 75 75 < 82 so low = 76
low = 76, high = 100 => guess = 88 88 > 82 so high = 88
low = 76, high = 88 => guess = 82 82 == 82 and we're done.
Note that the time complexity of this is O(lg(N))

I briefly made the game which you need with follows:
import random
guess=int(input("Choose a number you want the computer to guess from 1-100: "))
turns=0
a=None
compguess=random.randint(1,100)
while turns<10 and 100>guess>=1 and compguess!=guess: #computer has 10 turns to guess number, you can change it to what you want
print("The computer's guess is: ", compguess)
if compguess>guess:
a=compguess
compguess=random.randint(1,compguess)
elif compguess<guess:
compguess=random.randint(compguess,a)
turns+=1
if compguess==guess and turns<10:
print("The computer guessed your number of:" , guess)
turns+=1
elif turns>=10 and compguess!=guess:
print("The computer couldn't guess your number, well done.")
input("")
This is a bit rusty, but you could improve it by actually narrowing down the choices so the computer has a greater chance of guessing the right number. But where would the fun in that be? Notice how in my code, if the computer guesses a number which is greater than than the number the user has inputed, it will replace 100 from the randint function with that number. So if it guesses 70 and its too high, it won't choose a number greater than 70 after that. I hope this helps, just ask if you need any more info. And tell me if it's slightly glitchy

This is how I went about mine...
__author__ = 'Ghengis Yan'
print("\t This is the age of the computer")
print("\n The computer should impress us... the Man")
import random
#User chooses the number
the_number = int(input("Human Choose a number between 0 and 100 "))
tries = 1
computer = random.randint(0,100)
# User choose again loop
while the_number > 100:
the_number = int(input("I thought Humans are smarter than that... \nRetype the number... "))
if the_number <= 100:
print("Good")
# Guessing Loop
while computer != the_number:
if computer > the_number:
print(computer, "lower... Mr. Computer")
else:
print(computer, "higher... Mr. Computer")
computer = int(random.randint(0,100))
tries += 1
print("Computer Congratulations... You beat the human! The Number was ", the_number)
print("It only took a computer such as yourself", tries, "tries to guess it right... pathetic")
input("\nPress the enter key to exit.")

What I did for the same challenge was:
1) Define a variable that records the max value input by guessing computer.
Ex:
max_guess_number = 0
2) Define another variable with the lowest guessed value.
Ex.
min_guess_number = 0
3) Added in the "if computer_guess > secret_number" clause the following code (I added -1 so that the computer wouldn't try to guess the already previously tried number):
max_guess_number = guess - 1
computer_guess = random.randint(min_guess_number, max_guess_number)
4) Added the following code in the "if computer_guess < secret_number":
min_guess_number = guess + 1
computer_guess = random.randint(min_guess_number, max_guess_number)
Worth noting is the fact that I set my while loop to loop until another variable "guess_status" changes into a value 1 (the default I set to 0). This way I actually saw the result when the while loop finished.

print 'Please think of a number between 0 and 100!'
low = 0
high = 100
while(True):
rand = (high+low)/2
print 'Is your secret number '+str(rand)+'?'
ans = raw_input("Enter 'h' to indicate the guess is too high. Enter 'l' to indicate the guess is too low. Enter 'c' to indicate I guessed correctly.")
if ans=='h':
high = rand
elif ans=='l':
low = rand
elif ans=='c':
print "Game over. Your secret number was:",rand
break
else:
print "Sorry, I did not understand your input"

You only need two new variables to keep track of the low and high limits :
low = 1
high = 100
while guess != number:
if guess > number:
high = guess - 1
else:
low = guess + 1
guess = randint(low, high)
print ("The computer takes a guess...", guess)

Try this:
import random
player = int(input("tap any number: "))
comp = random.randint(1, 100)
print(comp)
comp_down = 1
comp_up = 100
raw_input("Press Enter to continue...")
while comp != player:
if comp > player:
comp_up = comp - 1
comp = random.randint(comp_down, comp_up)
print(comp)
if comp < player:
comp_down = comp + 1
comp = random.randint(comp_down, comp_up)
print(comp)
if comp == player:
break

If you use the stuff in the chapter (guessing this is from the Dawson book) you can do it like this.
import random
#program allows computer to guess my number
#initial values
user_input1=int(input("Enter number between 1 and 100: "))
tries=1
compguess=random.randint(1, 100)
#guessing loop
while compguess != user_input1:
if compguess > user_input1:
print("Lower Guess")
compguess=random.randint(1, 100)
print(compguess)
elif compguess < user_input1:
print("Higher Guess")
compguess=random.randint(1, 100)
print(compguess)
tries += 1 #to have program add up amount of tries it takes place it in the while block
print("Good job Computer! You guessed it! The number was,", user_input1, \
" and it only took you", tries, " tries!")

import random
corr_num = random.randint(1,100)
player_tries = 0
com_tries = 0
while player_tries <5 and com_tries < 5:
player = int(input("player guess is "))
if player > corr_num:
print("too high")
player_tries +=1
if player < corr_num:
print("too low")
player_tries +=1
if player == corr_num:
print("Player wins")
break
computer = random.randint(1,100)
print("computer guess is ", computer)
if computer > corr_num:
print("too high")
com_tries = 0
if computer < corr_num:
print("too low")
com_tries = 0
if computer == corr_num:
print ("computer wins")
break
else:
print("Game over, no winner")**strong text**

import random
x = 1
y = 99
hads = random.randint(x,y)
print (hads)
javab = input('user id: ')
while javab != 'd':
if javab == 'b':
x = hads
hads = random.randint(x,y)
print(hads)
javab = input('user id: ')
else:
javab == 'k'
y = hads
hads = random.randint(x,y)
print(hads)
javab = input('user id: ')

This is the code that I created to simplify the problem you were facing a lot more.
num = int(input("Enter a number between 1 and 100: "))
low = 1
high = 100
guess = (low+high)//2
while guess != num:
guess = (low+high)//2
print("The computer takes a guess...", guess)
if guess > num:
high = guess
else:
low = guess + 1
print("The computer guessed", guess, "and it was correct!")

import random
userNum = int(input("What will the secret number be (1-100)? "))
attempts = 0
guess = 0
lowCap = 1
highCap = 100
while guess != userNum:
guess = random.randint(lowCap,highCap)
if guess > userNum:
highCap = guess
attempts += 1
elif guess < userNum:
lowCap = guess
attempts += 1
print("The computer figured out the secret number in", + attempts, "tries.")
I was doing a similar scenario today for an assignment and only now figured out how to make it easily cut down through the numbers by changing random.randint(1, 100) to random.randint(lowCap, highCap) which will change as the computer keep making guesses.

Related

I need help on a python guessing game

I need help changing the range and showing the user what the range is so they know if they are closer or not. I have given the description I have been given. On what I need to do . I have given the code that I have come up wit so far. Let me know if you need anything else from me.
Step 6 – Guiding the user with the range of values to select between
Add functionality so that when displaying the guess prompt it will display the current range
to guess between based on the user’s guesses accounting for values that are too high and too
low. It will start out by stating What is your guess between 1 and 100, inclusive?, but as
the user guesses the range will become smaller and smaller based on the value being higher
or lower than what the user guessed, e.g., What is your guess between 15 and 32,
inclusive? The example output below should help clarify.
EXAMPLE
----------------
What is your guess between 1 and 44 inclusive? 2
Your guess was too low. Guess again.
import random
import sys
def main():
print("Assignment 6 BY enter name.")
welcome()
play()
#Part 1
def welcome():
print("Welcome to the guessing game. I have selected a number between 1 and 100 inclusive. ")
print("Your goal is to guess it in as few guesses as possible. Let’s get started.")
print("\n")
def play():
''' Plays a guessing game'''
number = int(random.randrange(1,10))
guess = int(input("What is your guess between 1 and 10 inclusive ?: "))
number_of_guess = 0
while guess != number :
(number)
#Quit
if guess == -999:
print("Thanks for Playing")
sys.exit(0)
#Guessing
if guess < number:
if guess < number:
guess = int(input("Your guess was too low. Guess Again: "))
number_of_guess += 1
elif guess not in range(1,11):
print("Invalid guess – out of range. Guess doesn’t count. : ")
guess = int(input("Guess Again: "))
else:
guess = input("Soemthing went wrong guess again: ")
if guess > number:
if guess > number:
guess = int(input("Your guess was too high. Guess Again: "))
number_of_guess += 1
elif guess not in range(1,11):
print("Invalid guess – out of range. Guess doesn’t count. : ")
guess = int(input("Guess Again: "))
else:
guess = input("Soemthing went wrong guess again: ")
#Winner
if guess == number :
number_of_guess += 1
print("Congratulations you won in " + str(number_of_guess) + " tries!")
again()
def again():
''' Prompts users if they want to go again'''
redo = input("Do you want to play again (Y or N)?: ")
if redo.upper() == "Y":
print("OK. Let’s play again.")
play()
elif redo.upper() == "N":
print("OK. Have a good day.")
sys.exit(0)
else:
print("I’m sorry, I do not understand that answer.")
again()
main()
What you'll need is a place to hold the user's lowest and highest guess. Then you'd use those for the range checks, instead of the hardcoded 1 and 11. With each guess, if it's a valid one, you then would compare it to the lowest and highest values, and if it's lower than the lowest then it sets the lowest value to the guess, and if it's higher than the highest it'll set the highest value to the guess. Lastly you'll need to update the input() string to display the lowest and highest guesses instead of a hardcoded '1' and '10'.
You need to simplify a lot your code. Like there is about 6 different places where you ask a new value, there sould be only one, also don't call method recursivly (call again() in again()) and such call between again>play>again.
Use an outer while loop to run games, and inside it an inner while loop for the game, and most important keep track of lower_bound and upper_bound
import random
import sys
def main():
print("Assignment 6 BY enter name.")
welcome()
redo = "Y"
while redo.upper() == "Y":
print("Let’s play")
play()
redo = input("Do you want to play again (Y or N)?: ")
def welcome():
print("Welcome to the guessing game. I have selected a number between 1 and 100 inclusive. ")
print("Your goal is to guess it in as few guesses as possible. Let’s get started.\n")
def play():
lower_bound, upper_bound = 0, 100
number = int(random.randrange(lower_bound, upper_bound))
print(number)
guess = -1
number_of_guess = 0
while guess != number:
guess = int(input(f"What is your guess between {lower_bound} and {upper_bound - 1} inclusive ?: "))
if guess == -999:
print("Thanks for Playing")
sys.exit(0)
elif guess not in list(range(lower_bound, upper_bound)):
print("You're outside the range")
continue
number_of_guess += 1
if guess < number:
print("Your guess was too low")
lower_bound = guess
elif guess > number:
print("Your guess was too high")
upper_bound = guess
print("Congratulations you won in", number_of_guess, "tries!")

Project with a python loop program

My son has this project he has to do in python and is stuck.
He needs to make a number guessing game. The code must generate a random secret number between 0 and 10, then give the user 5 attempts to guess that number, each guess if not correct must indicate if it is higher or lower than the secret random number. After each guess the code needs to display text stating what has happened. The code also needs to store all guesses and display them at the end. Needs to be made using loop, if, elif, else and an array or list code.
The attempt so far is below
print("Hi there, lets play a little guessing game. Guess the number between 0 and 10")
from random import randint
x = [randint(0,10)]
counter = 0
guess = input("Enter guess:")
while counter < 5:
print("You have " + str(counter) + " guesses left")
counter = counter +1
if guess == x:
print("Congrats you got it")
break
elif guess > x:
print("Too high")
elif guess < x:
print("Too low")
else:
print("You lost")
break
Any help to correct my sons code would be appreciated as this project is due soon and he cannot access his tutor
This should do it. What the code does is explained in comments below.
You need to do x=randint(0,10) which will assign the random number to a variable, i.e x=4 rather than `x = [randint(0,10)], which assigns the random number to a list ,x=[4]```
Also you need to ask for a guess in the loop, instead of doing it only one before the loop started.
Also you would need to convert the string to an int for comparison i.e. guess = int(input("Enter guess:"))
print("Hi there, lets play a little guessing game. Guess the number between 0 and 10")
#Create a random number
from random import randint
x = randint(0, 10)
counter = 0
won = False
#Run 5 attempts in a loop
while counter<5:
#Get the guess from the user
guess = int(input("Enter guess:"))
counter = counter+1
#Check if the guess is the same, low or high as the random number
if guess == x:
print("Congrats you got it")
won = True
break
elif guess > x:
print("Too high")
elif guess < x:
print("Too low")
print("You have " + str(5 - counter) + " guesses left")
#If you didn't won, you lost
if not won:
print("The number was ", x)
print("You Lost")
So here are the corrections. So x has been initialized as array rather than an integer. So none of the comparisons with guess will be working. Also the counter logic is wrong. Rather than starting from zero, start from 5 which is the maximum number of chances and go from the reverse rather. Then at each if/elif loop append all the guesses and print it in the end.
Here is the corrected code
from random import randint
x = randint(0,10)
print(x)
counter = 5
guesses=[] #initalize an empty list to store all guesses
while counter != 0:
guess = input("Enter guess:")
if guess == x:
print("Congrats you got it")
guesses.append(guess)
break
elif guess > x:
print("Too high")
guesses.append(guess)
elif guess < x:
print("Too low")
guesses.append(guess)
else:
print("You lost")
break
counter = counter-1
print("You have " + str(counter) + " guesses left")
print(guesses)
Edit:
x = [randint(0,10)] wouldn't work as you are creating a list here instead of single guess
print("You have " + str(counter) + " guesses left") is also incorrect. You might instead set counter to 5 and check for counter > 0 and do counter -= 1, that way message can be fixed
Lastly to store all guesses you would need a variable
from random import randint
if __name__ == "__main__":
number_to_guess = randint(0,10)
guesses = []
for c in range(5,0,-1):
guessed = input("Enter guess:")
guessed = guessed.strip()
assert guessed.isnumeric()
guessed = int(guessed)
guesses.append(guessed)
if guessed == number_to_guess:
print("yes")
break
elif guessed > number_to_guess:
print("more")
else:
print("less")
c -= 1
print("pending guesses", c)
print("Expected - ", number_to_guess)
print("All guesses - ", guesses)

Python help (computer guess number)

I'm learning how to program in Python and I found 2 tasks that should be pretty simple, but the second one is very hard for me.
Basically, I need to make a program where computer guesses my number. So I enter a number and then the computer tries to guess it. Everytime it picks a number I need to enter Lower or Higher. I don't know how to do this. Could anyone advise me on how to do it?
For example (number is 5):
computer asks 10?
I write Lower
computer asks 4?
I write Higher
Program:
I already made a program which automatically says Higher or Lower but I want to input Lower or Higher as a user.
from random import randit
number = int(input("Number? "))
attempts = 0
guess = 0
min = 0
max = 100
while guess != number:
guess = randint(min,max)
print(guess,"?")
if guess < number:
print("Higher")
min = guess
elif guess > number:
print("Lower")
max = guess
attemps += 1
print("I needed", attempts, "attemps")
You may want to put in a case for if it doesn't match you input, also I think you need a case for when the guess finally equals the number, you may want to allow an input for "Found it!" or something like that.
from random import randint
number = int(input("Number? "))
attempts = 0
guess = 0
min = 0
max = 100
while guess != number:
guess = randint(min,max)
print(guess,"?")
answer = str(input("Higher/Lower? "))
if answer == 'Higher':
min = guess
elif answer == 'Lower':
max = guess
attempts += 1
print("I needed", attempts, "attempts")
from random import randit
attempts = 0
guess = 0
min = 0
max = 100
while guess != number:
number = int(input("Number? "))
guess = randint(min,max)
print(guess,"?")
if guess < number:
print("Higher")
min = guess
elif guess > number:
print("Lower")
max = guess
attemps += 1
print("I needed", attempts, "attemps")
problem is your using a loop but inputting value once at start of app . just bring input inside the while statement hope this help
from random import randint
print('choos a number in your brain and if guess is true enter y else any key choose time of guess: ')
print("define the range (A,B) :")
A = int(input("A: "))
B = int(input("B: "))
time = int(input("time:"))
while time != 0:
ran = randint(A, B)
inp = input(f"is this {ran} ?")
time -= 1
if inp == "y":
print("bla bla bla computer wins!")
break
print("NOPE!")
if time == 0:
print("computer game over!")
break
from random import *
number = int(input("Number? "))
attempts = 0
guess = 0
min = 0
max = 100
attemps =0
guess = randint(min,max)
while guess != number:
userInput=input(str(guess)+"?")
if userInput.lower()=="lower":
max=guess
elif userInput.lower()=="higher":
min=guess
attemps += 1
guess = randint(min,max)
print("I needed", attemps, "attempts to guess ur number ="+str(guess))
output:
Number? 5
66?lower
63?lower
24?lower
19?lower
18?lower
10?lower
4?higher
9?lower
6?lower
4?higher
I needed 10 attempts to guess ur number =5

I am required to create a python program that requires 3 attempts and 5 rounds, but instead allows infinite attempts

To start i am very new to programming as i am doing it as a course so please be patient with me please.This program instead allows infinite guesses until the correct answer and all rounds are printed at once instead round by round I just need guidance on what im doing wrong because I am failing to see what I did incorrect
import random
sides = 6 #number of sides for a die
userguess = -1 #user's guess, 1 - 6 inclusive
rolled = -1 #number rolled, 1 - 6 inclusive
computerpoints = 0 #computer's score, 0 - 5 max
humanpoints = 0 #human user's score, 0 - 5 max
rightguess = False #flag for correct guess
numguesses = 0 #counts the number of guesses per round
#RULES
print("Welcome to the Guess Game!\n\n RULES:")
print("1. We will play five rounds.")
print("2. Each round you will guess the number rolled on a six-sided die.")
print("3. If you guess the correct value in three or fewer tries\n"
" then you score a point, otherwise I score a point.")
print("4. Whoever has the most points after five rounds wins.")
#play five rounds
for r in range(1, 5):
#roll the die to start the round
print("\n\nROUND " , r)
print("-------")
random.seed(11)
rolled = random.randrange(sides)+1
print("The computer has rolled the die.")
print("You have three guesses.");
#loop gives user up to three guesses
numguesses = 0;
while numguesses < 3 and not rightguess:
#loop for input & validation: must be in range 1 to 6 inclusive
userguess = int(input("What is your guess [1-6]?"))
while userguess < 1 and userguess > 6:
userguess = int(input(" Please enter a valid guess [1-6]!"))
if rolled == userguess:
rightguess = True
print(" Correct!")
else:
print(" Incorrect guess.")
#if the user guessed right, they get a point
#otherwise the computer gets a point
if rightguess:
humanpoints = humanpoints + 1;
else:
computerpoints = computerpoints + 1;
#display the answer and scores
print("\n*** The correct answer was: " , rolled , " ***\n")
print("Scores:")
print(" You: \t\t" , humanpoints)
print(" Computer: \t" , computerpoints)
print("")
if computerpoints > humanpoints :
print("*** You Lose! ***")
else:
print("*** You Win! ***")
print("Thanks for playing the Guess Game!")
range(1, 5) returns the numbers 1, 2, 3, and 4, but not 5. So in order to have 5 rounds, you need to use range(1, 6)
You never increment numguesses, which means that the guessing loop will only end when the user has made the right guess.
I don't think you reset rightguess for successive rounds.
This is my corrected program, please reply if you see anything else that needs fixing please and thank you
import random
sides = 6 #number of sides for a die
userguess = -1 #user's guess, 1 - 6 inclusive
rolled = -1 #number rolled, 1 - 6 inclusive
computerpoints = 0 #computer's score, 0 - 5 max
humanpoints = 0 #human user's score, 0 - 5 max
rightguess = False #flag for correct guess
numguesses = 0 #counts the number of guesses per round
#RULES
print("Welcome to the Guess Game!\n\n RULES:")
print("1. We will play five rounds.")
print("2. Each round you will guess the number rolled on a six-sided die.")
print("3. If you guess the correct value in three or fewer tries\n"
" then you score a point, otherwise I score a point.")
print("4. Whoever has the most points after five rounds wins.")
#play five rounds
for r in range(1, 6):
#roll the die to start the round
print("\n\nROUND " , r)
print("-------")
random.seed(11)
rolled = random.randrange(sides)+1
print("The computer has rolled the die.")
print("You have three guesses.");
#loop gives user up to three guesses
numguesses = 0;
while numguesses < 3 and not rightguess:
#loop for input & validation: must be in range 1 to 6 inclusive
numguesses = numguesses + 1
userguess = int(input("What is your guess [1-6]?"))
while userguess < 1 and userguess > 6:
userguess = int(input(" Please enter a valid guess [1-6]!"))
if rolled == userguess:
rightguess = True
print(" Correct!")
else:
print(" Incorrect guess.")
#if the user guessed right, they get a point
#otherwise the computer gets a point
if rightguess:
humanpoints = humanpoints + 1;
else:
computerpoints = computerpoints + 1;
#display the answer and scores
print("\n*** The correct answer was: " , rolled , " ***\n")
print("Scores:")
print(" You: \t\t" , humanpoints)
print(" Computer: \t" , computerpoints)
print("")
if computerpoints > humanpoints :
print("*** You Lose! ***")
else:
print("*** You Win! ***")
print("Thanks for playing the Guess Game!")

Guessing algorithm does not seem to work, guessing number by Python

I am struggling with some simple algorithm which should make python guess the given number in as few guesses as possible. It seems to be running but it is extremely slow. What am I doing wrong. I have read several topics already concerning this problem, but can't find a solution. I am a beginner programmer, so any tips are welcome.
min = 1
max = 50
number = int(input(("please choose a number between 1 and 50: ")))
total = 0
guessed = 0
while guessed != 1:
guess = int((min+max)/2)
total += 1
if guess == number:
print("The number has been found in ",total," guesses!")
guessed = 1
elif guess > number:
min = guess + 1
elif guess < number:
max = guess - 1
Thanks
ps. I am aware the program does not check for wrong input ;)
Your logic is backwards. You want to lower the max when you guess too high and raise the min when you guess too low. Try this:
if guess == number:
print("The number has been found in ",total," guesses!")
guessed = 1
elif guess > number:
max = guess - 1
elif guess < number:
min = guess + 1
Apart from having the logic backwards, you should not be using min and max as variable names. They are python functions. You can also use while True and break as soon as the number is guessed.
while True:
guess = (mn + mx) // 2
total += 1
if guess == number:
print("The number has been found in {} guesses!".format(total))
break
elif guess < number:
mn = guess
elif guess > number:
mx = guess
You will also see by not adding or subtracting 1 from guess this will find the number in less steps.
from random import randint
print('choose a number in your brain and if guess is true enter y else any key choose time of guess: ')
print("define the range (A,B) :")
A = int(input("A: "))
B = int(input("B: "))
time = int(input("time:"))
while time != 0:
ran = randint(A, B)
inp = input(f"is this {ran} ?")
time -= 1
if inp == "y":
print("bla bla bla python wins!")
break
print("NOPE!")
if time == 0:
print("computer game over!")
break

Categories