Hello, OnlineGDB Q&A section lets you put your programming query to fellow community users. Asking a solution for whole assignment is strictly not allowed. You may ask for help where you are stuck. Try to add as much information as possible so that fellow users can know about your problem statement easily.

Exercise for beginners.

+3 votes
asked Oct 6, 2022 by codenxn (1,350 points)

Hi, I was bored, so I wondered, why not create an exercise for beginners. What you'll need to know is: User Input, Else if statements, While loops, Random Number Generator.

Also, try to make it shorter. Good luck!


1 Answer

+2 votes
answered Oct 7, 2022 by Peter Minarik (88,520 points)
edited Oct 7, 2022 by Peter Minarik

Nice one!

Let me fix up the code for you as it does not compile. I've also fixed some logic error and reduced the number or lines required:

import random

number = random.randint(1, 10)
guess = 0
numberguess = 0
while guess != number:
    guess = int(input("enter here a numbers between 1-10\n"))
    numberguess = numberguess + 1
    if number > guess:
    elif number < guess:
    elif number == guess:
        print("Bingo! It took you exactly " + str(numberguess) + " guesses!")

Now make it so that the player needs to guess the number in ceil(log2(range)) + 1 steps, where range is the max - min + 1 (both the upper and lower limit being inclusive) of the numbers randomly generated.

For instance, if the range is 10 (1..10), then the user must guess the right number in ceil(log2(10)) + 1 guesses, which is 4.

There is a guaranteed strategy to win, let's see if players can figure it out. :)

You can also try to make a High Scores feature. You can just store the high scores in memory, or... save it in a file so you can compare your scores later as well!

I'd recommend scoring information holding the range and how many steps it took. This is because a narrower range is easier to guess so it wouldn't be fair to compare just the steps without knowing if they were measured on the same or different ranges.

Welcome to OnlineGDB Q&A, where you can ask questions related to programming and OnlineGDB IDE and and receive answers from other members of the community.