Your Guess Is as Good as Mine
August 12, 2024 11:24 AM   Subscribe

In my latest attempt on coding in Python (using Python 3), I decided to write a guess the number game. Mostly because it let me get my feet wet using includes and loops. What am I missing?? It looks like it should work, but clearly doesn't.

I'm using VS 2022

I can't figure out why I'm getting the error in the VS error box "Expected Expression" for the 2 elif statements.

Here's the code:


# Guess the Number

# Kathryn Marks
# kathryn.pythonprograms@gmail.com
# Created April 26, 2024
# Last modified August 12, 2024



# This is a game to guess a random number from 1 - 10
# Using a RNG pick a number
# Using a loop to decide if the number is too big, too small or the correct one.
# Print a message to the player with the feedback
# Continue until the player guess the correct number

# The random module allows us to generate the mystery number

from math import random

# Assign a random number to mystery_number

mystery_number = random.randint(0,10)

print ("This is a game to guess a random number between 0 and 10" )
print (mystery_number) # This is for debugging

guess = int(input("What is your first guess? "))
print ("You guessed ",guess)

# Logic to determine if guess is greater than, less than or equal to mystery_number
# Need to rewrite this into a while look
# Pseudocode something like
# While guess != mystery_number
# Test the guess using if elif else
# break


while guess != mystery_number:
if guess < mystery_number:
print ("That's too small, try again")
next_guess = int(input("What is your next guess? "))
print ("You guessed ",next_guess)

elif guess > mystery_number:
print ("That's too big, try again")
next_guess = int(input("What is your next guess? "))
print ("You guessed ",next_guess)

else break
print ("Congratulations, you guessed it!")


# EOF


Here's the traceback


Traceback (most recent call last):
File "C:\Python311\Lib\runpy.py", line 198, in _run_module_as_main
return _run_code(code, main_globals, None,
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Python311\Lib\runpy.py", line 88, in _run_code
exec(code, run_globals)
File "c:\program files\microsoft visual studio\2022\community\common7\ide\extensions\microsoft\python\core\debugpy\adapter/../..\debugpy\launcher/../..\debugpy\__main__.py", line 39, in
cli.main()
File "c:\program files\microsoft visual studio\2022\community\common7\ide\extensions\microsoft\python\core\debugpy\adapter/../..\debugpy\launcher/../..\debugpy/..\debugpy\server\cli.py", line 430, in main
run()
File "c:\program files\microsoft visual studio\2022\community\common7\ide\extensions\microsoft\python\core\debugpy\adapter/../..\debugpy\launcher/../..\debugpy/..\debugpy\server\cli.py", line 284, in run_file
runpy.run_path(target, run_name="__main__")
File "c:\program files\microsoft visual studio\2022\community\common7\ide\extensions\microsoft\python\core\debugpy\_vendored\pydevd\_pydevd_bundle\pydevd_runpy.py", line 320, in run_path
code, fname = _get_code_from_file(run_name, path_name)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "c:\program files\microsoft visual studio\2022\community\common7\ide\extensions\microsoft\python\core\debugpy\_vendored\pydevd\_pydevd_bundle\pydevd_runpy.py", line 294, in _get_code_from_file
code = compile(f.read(), fname, 'exec')
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\ksmar\source\repos\Guess the Number\Guess_the_Number.py", line 45
elif guess > mystery_number:
^^^^
SyntaxError: invalid syntax
The thread 1 has exited with code 0 (0x0).
The program 'python.exe' has exited with code 1 (0x1).
posted by kathrynm to Computers & Internet (12 answers total) 2 users marked this as a favorite
 
Best answer: The Mefi editor's <code> tags don't preserve leading whitespace, which is meaningful to Python. I'm guessing that there's something above your elif that's indented to the same extent as the elif itself, meaning that Python is interpreting the original if and whatever's indented underneath it as complete, and is therefore not expecting the elif and possibly also the else that goes with it. Whitespace-sensitive languages are a bit of a pain in the arse that way.

If you re-paste the code using <pre> instead of <code> we'd be able to see whether that's actually what's going on.
posted by flabdablet at 11:37 AM on August 12, 2024 [3 favorites]


Im on my phone so i cant look at this, but this is something ive found ChatGPT to be pretty good at, if youre willing to lean on AI to help learn this stuff. Newer versions can explain things quite well Ive found.

Apologies for the non-answer, and I know askme generally frowns on “ask chatgpt” answers but in this specific case (debugging single file python scripts) ive found it to be quite helpful!
posted by cgg at 11:40 AM on August 12, 2024 [4 favorites]


as flabdablet noted, the missing indents are probably the key. I took a pass at indenting it as I think it should be, and changed the from math import random to import random because on my platform (MacOS, Python3) that's what it wanted, changed the "else" block to a multi-line, and added a guess = next_guess at the end of the loop, and ended up with rand.py, which runs.

Hopefully you can use the difference between what you have and that to help you figure it out?
posted by straw at 11:46 AM on August 12, 2024 [1 favorite]


I think it's the "else break" line, assuming that's how it looked in the original file - you just want "else:" (with a colon). You could say "break" after printing the success message to stop the while loop, but it should stop anyway because the loop condition tests whether the guess is correct.
posted by offog at 11:46 AM on August 12, 2024


Using the code presented as-is but reindented because formatting got lost, using Python 3.12.5 (latest) and on 3.11.9 (latest 3.11), I get an error on line 1 because your import is wrong. random isn't in math, you just need to import random. Additionally, I got an error because you're mixing a block if/elif with a non-block else. Make your else into a block like the if/elifs are. Works OK after that, but there are other issues with your algorithm that I am not addressing.
posted by mrg at 11:48 AM on August 12, 2024


Best answer: Once you've got the elif syntax sorted out, you'll need to pay attention to next_guess - I'm thinking you probably want that to be just guess so that the while loop condition works properly.

Also, at present you've got two copies of the code that prompts for and collects a guess, one in each branch of the if inside the while. You could combine those and put them between the end of the if and the end of the while. That way, the if becomes responsible only for telling you what was wrong with your guess, or for breaking out of the while if there was nothing wrong with it, and collecting a new guess each time around becomes the while loop's sole concern.
posted by flabdablet at 11:50 AM on August 12, 2024 [3 favorites]


+1 ChatGPT

Prompt: “the following code gives me XYZ error, do you know why” and then paste the code.
posted by St. Peepsburg at 12:24 PM on August 12, 2024 [3 favorites]


Best answer: This is what the code would look like, incorporating the previous comments.
Note you don't need a separate break statement since you'll break out of the while loop if the while condition is not satisfied.
import random

# Assign a random number to mystery_number

mystery_number = random.randint(0,10)

print ("This is a game to guess a random number between 0 and 10" )
print (mystery_number) # This is for debugging

guess = int(input("What is your first guess? "))

while guess != mystery_number:
    print ("You guessed ",guess)
    if guess < mystery_number:
        print ("That's too small, try again")
    elif guess > mystery_number:
       print ("That's too big, try again") 
    guess = int(input("What is your next guess? "))

print ("Congratulations, you guessed it!")


posted by needled at 12:26 PM on August 12, 2024 [2 favorites]


Best answer: you don't need a separate break statement since you'll break out of the while loop if the while condition is not satisfied

In fact you don't even need the elif, just else will do. The while condition guarantees that at any point inside the loop body before guess gets changed (which happens only at the very end), guess and mystery_number will not be equal. So once the test for guess being less than mystery_number has failed, it can't have done so due to guess being equal to mystery_number. The only remaining possibility is that guess is strictly greater, so there's no need to test explicitly for that.
import random

mystery_number = random.randint(0, 10)

print ("This is a game to guess a random number between 0 and 10" )
print (mystery_number) # This is for debugging

guess = int(input("What is your first guess? "))

while guess != mystery_number:
    print ("You guessed",guess)
    if guess < mystery_number:
        print ("That's too small, try again")
    else:
        print ("That's too big, try again")
 
    guess = int(input("What is your next guess? "))

print ("Congratulations, you guessed it!")

posted by flabdablet at 4:57 AM on August 13, 2024 [1 favorite]


Best answer: flabdablet, you're absolutely right, and so a conditional expression could be used instead of if .. else statements.
But I think at this point it might be overthinking and your code above might be considered more readable. I just wanted to see how much this could be shortened, heh.
import random

mystery_number = random.randint(0,10)

print ("This is a game to guess a random number between 0 and 10" )
print (mystery_number) # This is for debugging

guess = int(input("What is your first guess? "))

while guess != mystery_number:
    print ("You guessed ", guess)
    print ("That's too", "small," if guess < mystery_number else "big,", "try again")
    guess = int(input("What is your next guess? "))

print ("Congratulations, you guessed it!")

posted by needled at 5:45 AM on August 13, 2024


Response by poster: Thank you all.

I thought it was an indentation issue, but I was all mixed up.

I think I got the import statement from a web resource. Thanks for the correction.

flabdablet, your answer about next_guess clears up why I was getting an infinite loop before I mucked up the indenting.

Needled, also thanks for the other approach. I mostly understand it. I'm going to sit down now and look at it more closely.

Thanks everyone for your patience.
posted by kathrynm at 12:48 PM on August 13, 2024


I mostly understand it.

Python conditional operator

posted by flabdablet at 7:04 AM on August 14, 2024


« Older In search of novels where some clarity and...   |   Lynden Washington hotel recommendations Newer »

You are not logged in, either login or create an account to post comments