Home > OS >  Computer should guess the number in my head in Python
Computer should guess the number in my head in Python

Time:06-08

So I'm new to programming and I'm trying to write a program where I have a number in my head and the computer must guess it until I say that it has guessed right! The computer should choose a random number between 1 to 99 and show it to me, If the number is correct I should type "c" to prove that it's correct, if the number in my head is smaller I should write "s" to make the range smaller and if the number in my head was bigger I should write "b" to make the range smaller and easier for the computer to guess the number. this is the code I came up with but there's something wrong with it that I can't find out.

    import random
    first=1
    second=99
    guess=random.randint(first,second)
    print(guess)
    answer=input("what is the number in your head(don't enter it, just compare it with the number on the screen)? print c for correct, b for bigger and s for smaller! \n")
    while answer!="c":
        if answer=="b":
            first==guess 1
            guess=random.randint(first,second)
            print(guess)
        elif answer=="s":
            second==guess-1
            guess=random.randint(first,second)
            print(guess)
    answer=input("what do you think about the new number? ")
    print("you did it!")

CodePudding user response:

You have two mistakes: using == (testing for equality) where you should have used = (assignment), and wrong indentation:

import random
first = 1
second = 99
guess = random.randint(first, second)
print(guess)
answer = input("what is the number in your head(don't enter it, just compare it with the number on the screen)? print c for correct, b for bigger and s for smaller! \n")
while answer != "c":
    if answer == "b":
        first = guess   1 # <-- this line
        guess = random.randint(first, second)
        print(guess)
    elif answer == "s":
        second = guess - 1 # <-- this line
        guess = random.randint(first, second)
        print(guess)
    answer = input("what do you think about the new number? ")  # <-- and this line
print("you did it!")

The final line would only run after the loop ended instead of once every loop the way you wrote it.

See how the spaces I added make it clearer what's going on on each line

CodePudding user response:

You should indent the second input line so that it belongs to the while loop. This way new input is requested after every guess.

CodePudding user response:

Your program is correct, it just needs a few modifications in the while loop. It should look like this:

while answer != "c":
    if answer == "b":
       first = guess 1
       guess = random.randint(first, second)
       print(guess)
    elif answer == "s":
       second = guess-1
       guess = random.randint(first, second)
       print(guess)
    answer = input("what do you think about the new number? ")
  • Related