r/learnpython • • 2d ago

CS50 problom 4 Gussing game

this is what im trying to do https://cs50.harvard.edu/python/psets/4/game/

this my code

import random


while True:
    try:
        level = int(input("Level:"))
        if level >= 0:
            False
        number = random.randint(1, level)
        output = number
        if output < number:
            print("Too small!")
        elif output > number:
            print("Too large!")
        elif output == number:
            print("Just right!")
        
        print("Guess:", number)
    except ValueError:
        pass

when I start and give a number it give ether it stopes it "Just right!" or print both "Just right!" and Guess: so how do I make it don't do that and do what it suppose to do in the problem

0 Upvotes

12 comments sorted by

1

u/lfdfq 2d ago

First, these lines:

if l >= 0:
    False

What is it trying to do? It looks like it should error if you run it, because of those lines.

There are a few problems I see, but the biggest one is that you never ask the user their guess. You roll a random number AND use that number as the guess. Can you see why that does not work?

2

u/anas_mv 2d ago

Level was actually just L but i forget to change it As for the other Can you explain it .-.

2

u/lfdfq 2d ago

The question says to randomly generate a number, and then prompt the user for their guess.

Look at your code, it randomly generates the number, but just does not ask the user for their guess like you did for the level.

0

u/anas_mv 2d ago

So what im supposed to do to fix it

1

u/lfdfq 2d ago

You already do it for the level.

You want something like:

number = random.randint(1, level)
guess = int(input("Guess:"))

do you see how then number is randomly picked but guess comes from the user?

1

u/anas_mv 2d ago

Ohhhhh you are right thank you

1

u/AlexMTBDude 2d ago

First this:
output = number

Then this:
elif output == number:

What do YOU think will happen?

1

u/anas_mv 2d ago

If the two numbers are equal it will print "just right"

2

u/CIS_Professor 2d ago

In your code, the two number will be equal, you set them as such:

output = number

A single equal sign (=) assigns the value in the variable (or a constant, result of an expression, return from a function, ...) on the right side to the variable on the left.

Two equal signs (==) compares the values in the two variables.

For example:

x = 10        # assign 10 to x
y = x         # assign the value in x (10) to y; now y also has 10
if x == y:    # will always be True as x and y are equal to 10

1

u/AlexMTBDude 2d ago

The numbers will always be equal because of the first line

1

u/atarivcs 2d ago

This line:

output = number

Assigns output to be equal to number.

So of course you will never see the "too small" or "too large" messages...

1

u/Naive_Programmer_232 2d ago edited 2d ago

A couple of things. The assignment says the game should prompt the user for a level and if it is not a 'positive integer' to prompt them again. Your first conditional is wrong.

Part 1: verify level is a positive integer

    while True:
          try:
               level=int(input("Level: "))
               if level<=0:
                  # not a positive integer
                  continue

               # level is positive integer
               ...

          # int() fails to convert input str to int
          except ValueError:
               # loop implicitly continues
               pass

In addition, the assignment says, if level is a positive integer, get a random number from [1, level] (inclusive), and then ask the user for a guess between 1 and level. Your code does get the random number, however, it doesn't ask the user for the guess.

Part 2: gather guess from user

  while True:
        try:
            level=int(input("Level: "))
            if level<=0:
               # level is not a positive integer
               continue

            # level is positive integer

            # ask for random number [1,level]
            rand_num=random.randint(1,level)

            # ask for guess from user
            guess=int(input(f"Enter guess between 1 and {level}: "))

            ...
        
        # int() failed to convert input str to int
        except ValueError:
            # loop implictly continues
            pass

Then the assignment says when the guess is gathered from the user, you need to validate if the guess itself is also a positive integer.

Part 3: verify guess is a positive integer - structural issue hint

  while True:
        try:
            level=int(input("Level: "))
            if level<=0:
               # level is not a positive integer
               continue

            # level is positive integer

            # ask for random number [1,level]
            rand_num=random.randint(1,level)

            # ask for guess from user
            guess=int(input(f"Enter guess between 1 and {level}: "))

            if guess<=0:
               # guess is not a positive integer
               # ????
        
        # int() failed to convert input str to int
        except ValueError:
            # loop implictly continues
            pass

Now this is an interesting piece to the puzzle. Consider where ???? is, what happens if you put continue there?

Answer: control will go back to the top of the loop, just like it would with the level verification part. However, in the guess case, this is an issue. If control goes back to the top of the loop, then the user will be asked for the level again!

So, this is starting to point at a structural issue. Maybe the level verification part should be in its own loop, while the guess verification part should be in a separate loop. Maybe the two loops could be on the same level or could be nested within each other?

Let's consider two separate loops on the same level. One loop for level validation and the other loop for guess validation. In addition let's separate the int() failure ValueError from the level error when it's not a positive integer; and also from the guess error when it's not a positive integer or it's greater than level.

To do this, we'll create two custom exception classes, InvalidLevelError and InvalidGuessError, and use two except statements in each loop's try/except/else chain to distinguish between the ValueError caused by int() breaking and the appropriate custom exception ('exceptions' are python's term for errors).

Part 4: new structure to verify level and guess with custom error classes + try/except/else

 # custom level exception
 class InvalidLevelError(Exception):
       pass 

 # custom guess exception
 class InvalidGuessError(Exception):
       pass    


 # Note: in python, variables inside loops remain accessible 
 # in the enclosing scope. This program's enclosing scope is global.
 # Thus variables defined inside the loops are accessible outside of them.
 # (For more learning: research global vs local scope in python)


 # level verification loop
 while True:

        # verifying level
        try:

            level=int(input("Level: "))

            if level<=0:
               raise InvalidLevelError("Level must be positive integer")

        # int() fails to convert str to int
        except ValueError:
            print("Level must be int type")
      
        # level is not positive integer
        except InvalidLevelError as err_msg:
            print(err_msg)

        # only executes if no excepts did - level was reassigned and is valid
        else:
       
             # get out of loop
             break

     # if an except did execute, it comes out here (skipping over else)
     # but since there is no code -> the loop continues


 # level is positive-int now

 # we need random number between [1,level]
 rand_num=random.randint(1,level)

 # time to validate guess

 # guess validation loop
 while True:

       try:

            guess=int(input(f"Enter guess between 1 and {level}: "))
            if guess<=0 or guess>level:
               raise InvalidGuessError(f"Guess must be between [1,{level}]")

       # int() fails to convert str to int
       except ValueError:
            print("Guess must be int type")

       # guess is invalid (not positive int or above level)
       except InvalidGuessError as e:
            print(e)

       # no excepts executed - guess is valid
       else:

            # TO-DO: 
            # - Guess checks (high,low,same) against rand_num
            # - when to continue to top of this loop? 
            # - when to break out of this loop?

The above is for sake of example. By no means is this the only way to go about this nor is the best way of doing it. I'm going to leave Part 4 the way it is so you can figure out the rest.

Ideally, what should happen is the TO-DO comment portion should be edited and guess should be compared with rand_num.

If guess!=rand_num, then the loop should do what? And what should happen first per the case (larger / smaller)? When should the break apply?? I'll leave it for you to decide.


Once you get your program working. Here's some extra challenges to consider implementing:

  1. Add a play again feature at the end of the program to restart from the beginning automatically so that they don't have to re-run it manually to continue the game. (hint: consider putting your program into a function).
  2. Add a counter variable to keep track of how many guesses the user makes per game round. This could even be two variables, how many too large and how many too small, since it only takes 1 correct answer to end the round.
  3. Add a track record data structure that associates each round with the number of guesses total, or divided by type, made in order to win the game. Display this if the user does not want to play again and/or quits at the end.
  4. Add more game-logic. For example, maybe define a deterministic algorithm to pre-calculate how many guesses can be made in a game round per the level, in order to 'win' or 'lose' that round (e.g. suppose the user enters level 10, then behind the scenes the max amount of allowable guesses is 15; if the user guesses the random number within 15 tries, they win; otherwise they lose). You can then possibly add these outcomes into the track record if you'd like to.

There's a lot you can do with a project like this. This is a great starting point.

Anyway, hopefully this clarifies things a bit more. Best of luck with everything!