this post was submitted on 01 May 2025
24 points (100.0% liked)

Python

7069 readers
17 users here now

Welcome to the Python community on the programming.dev Lemmy instance!

πŸ“… Events

PastNovember 2023

October 2023

July 2023

August 2023

September 2023

🐍 Python project:
πŸ’“ Python Community:
✨ Python Ecosystem:
🌌 Fediverse
Communities
Projects
Feeds

founded 2 years ago
MODERATORS
 

There is an issue with the program when the user correctly guesses the number. The program should end when the break statement executes in the while loop found in main(), but instead it times out.

import random


def main():
    level = get_level()
    number = generate_random_number(level)

    while True:
        guess = get_guess()

        if check_guess(number, guess) == False:
            continue
        else:
            break


def get_level():
    while True:
        level = input("Level: ")

        try:
            int(level)
        except ValueError:
            continue
        if int(level) <= 0:
            continue
        else:
            return int(level)

def generate_random_number(level):
    number = random.randint(1, level)

    return number

def get_guess():
    while True:
        guess = input("Guess: ")

        try:
            int(guess)
        except ValueError:
            continue
        if int(guess) <= 0:
            continue
        else:
            return int(guess)

def check_guess(number, guess):
    if guess > number:
        print("Too large!")

        return False
    if guess < number:
        print("Too small!")

        return False
    if guess == number:
        print("Just right!")

        return True


main()
top 33 comments
sorted by: hot top controversial new old
[–] [email protected] 10 points 3 days ago* (last edited 3 days ago) (2 children)

Maybe try using the idiom:

if __name__=="__main__":
    main()

Instead of calling main since the way it's written now it will always run your code as soon as your module is imported. If the system expects a function named main and calls it, remove your call to main at the end.

[–] [email protected] 2 points 2 days ago

My name's not Shirley nor May. Meaning, the process guard has a name and it's not idiom.

[–] [email protected] 2 points 2 days ago

That passed the test! Thank you!

[–] [email protected] 4 points 4 days ago

What happens if you replace the last break in main() with exit()?

[–] [email protected] 4 points 4 days ago (1 children)

The code looks like it should run fine. How are you executing it and what makes you think it "times out"?

[–] [email protected] 1 points 4 days ago* (last edited 4 days ago) (4 children)

It's for CS50P which uses a customized VS Code. It has an automated code checker which I ran when I was done.

outputs "Just right!" when guess is correct

timed out while waiting for program to exit

[–] [email protected] 7 points 3 days ago (2 children)

How is that checker configured?

It might be doing something like this:

import student_module
student_module.main()

and because you're already invoking main as the module is imported, it's getting stuck the second time around. Maybe add some indicative print at the entrypoint to your main function.

Another reply in here has supplied the standard idiom for making a module executable:

if __name__ == "__main__":
  main()
[–] [email protected] 1 points 2 days ago* (last edited 2 days ago) (1 children)

What duh eh does standard idiom mean?

In computer programming, a programming idiom, code idiom or simply idiom is a code fragment having a semantic role[1] which recurs frequently across software projects. It often expresses a special feature of a recurring construct in one or more programming languages, frameworks or libraries. This definition is rooted in the linguistic definition of "idiom".

https://en.wikipedia.org/wiki/Programming_idiom

So this term is vague and abstract. Really not a specific term or grouping of related things.

The actual terminology

That standard idiom is called, process guard or simply guard. Learn about this term when doing anything involving multiprocessing.

The if __name__ == "__main__": guard is important when working with multiprocessing in Python. This prevents the creation of duplicate processes when the module is imported.

https://labex.io/tutorials/python-how-to-pass-arguments-in-python-multiprocessing-430780

So it's totally not for what its being described as. Or that's an oversimplification with a loss of vital details of it's actual purpose.

It could be worse

When don't know the name for something, Call it stuff!. Ya know, when really suack at naming things, be unrepentant! Stuff is as bad of a term i could come up with. Means didn't know how to describe it to accurately relate what it is or does, without being vulgar; out of fear the typos author left an Easter egg which is best left lie.

Used this term once, for a SQLAlchemy non-request based router implementation, the Session (term already taken) i call SessionStuff. Doesn't that just scream competence and authoritative implementation?

What do you do for a job? Urrrh ... stuff?

Regretted immediately and still do. Cuz session seems to have three different contexts / meanings.

Oh shit! Used the term, stuff. That's code prefer to not even read. That's a thing of nightmares that haunts our collective waking moments.

[–] [email protected] 2 points 2 days ago (1 children)

You sound angry. Take a breath and grow up.

[–] [email protected] 1 points 1 day ago* (last edited 1 day ago)

That's what code reviews feel like. Don't take it personally. Sugar coating advice is a skill when working in groups.

Evidently i'm not, so got that code review advice the less than tender way.

Everyone one else was not critical and let these avoidable coding mistakes slide. That doesn't fill me with confidence. Should strive to spend more time testing code bases to eventually be able to see and avoid these kinda coding mistakes.

If anyone feels the need to set me on the road to becoming a lovable teddy bear full of positivity and group comradery, jawboning alone is too kind, feel free to put me in the hot chair by reviewing packages have written and published.

Have ordered the packages according to the value you'd gain by learning them.

logging-strict

wreck

pytest-logging-strict

sphinx-external-toc-strict

drain-swamp and drain-swamp-action

[–] [email protected] 1 points 2 days ago (1 children)

The idiom allowed it to pass the checker's tests! Thanks for your help!

[–] [email protected] 1 points 2 days ago

You picked up an STD from mvirts. That dodgy terminology has been passed on and added to your lexicon.

South Park suggested the cure for this, eat a banana. Life doesn't have to make sense, roll with it.

Quickly taking a shower was oddly never suggested.

[–] [email protected] 4 points 4 days ago* (last edited 3 days ago)

Do you know how to use breakpoints? Put one on "Just right!" and then step through it.

Edit: I just ran the code and it exits properly. It's probably your customized VS Code . Which command is it using to run your code?

Anti Commercial-AI license

[–] [email protected] 2 points 3 days ago

try running the code outside the special editor, just python3 whatever_file_the_code_is_in.py. if it works as it should, then something is wrong with the environment you have been provided.

[–] [email protected] 2 points 3 days ago

It seems to run fine. You should likely as a TA or something as this appears to be something specific to your environment.

[–] [email protected] 3 points 3 days ago* (last edited 3 days ago) (1 children)

Nothing really sticks out. It could also be something about how the automated checker provides input (maybe it expects to not press enter or something and it's stuck at input()... hard to say)

I personally would install ruff and run "ruff check yourfile.py" and then later "ruff check --select=ALL yourfile.py" and read about everything it complains about.

Google the error codes and find the description and discussion of each and why it is complaining, sometimes they're not a big deal, sometimes they are aha moments. Ruff has a page discussing each warning and error

https://docs.astral.sh/ruff/rules/

[–] [email protected] 2 points 3 days ago* (last edited 3 days ago) (1 children)

Actually I think it may be your get_entry() code. The try traps all non-numbers and restarts the loop for new entry. So like typing "exit" or an empty string or anything that's not convertible to a number is being trapped by the raise and sent back for reentry. And anything that is a number can't hit the break. Just my guess.

[–] [email protected] 1 points 3 days ago

I second this! Add a print("invalid number, try again") or something to verify and avoid silent failures.

[–] [email protected] 2 points 4 days ago (2 children)

probably indentation issue, make sure to have 4 spaces on each indent level

[–] [email protected] 1 points 2 days ago* (last edited 2 days ago)

1 2 3 4

1 2 3 4

1 2 3 4 5

1 2 3 4 1 2 3 4 1 2 3

Opps!

[–] [email protected] 1 points 4 days ago (2 children)

Was using tabs but I went through it to make sure and seemed to be ok.

[–] [email protected] 1 points 2 days ago

Don't think that's a literal suggestion.

More like a subtle way to portray his frustrations having to look through code example with three while(True) loops?

[–] [email protected] 1 points 3 days ago (1 children)

If you set up ruff you should get autoformatting (and you can enable various lints).

[–] [email protected] 1 points 2 days ago (1 children)

or not introducing another programming language into your toolchain by sticking with black, flake8, isort, and pre-commit

[–] [email protected] 1 points 2 days ago (1 children)

At the user level they're just tools, not programming languages. Python users are generally moving to ruff (and uv) because of ergonomics: It works well and really fast which makes for a smooth experience in-editor. Plus using fewer tools to achieve a similar result is generally desirable.

And for a complete newbie like someone taking a course, I think there's no "sticking with" to speak of. Might as well just skip over the tools people are migrating away from and start with the tool people are migrating to.

[–] [email protected] 1 points 1 day ago

Can see both the pros and cons.

Looking at existing packages we actually use, it's a mixed bag. When helping other projects, have not run into the situation where had to use ruff. Do see some uptake. It's not like a light switch there will be multiple commits before the ruff configuration is right. But i'm sure the configuration is simplier than the rocket science that is: black, flake8, isort, pre-compile, tox configurations.

Overtime expect Rust to bleed into the Python toolchain. The excuse to resist this is there is not enough time in the day for Python let alone other coding languages especially low level languages like Rust and integration of those low level languages and Python. Sounds like a ton of work unless intending to write Rust modules to optimize speed of complex Python apps.

[–] [email protected] 0 points 4 days ago (4 children)

Cannot see the issue at first glance, but you can try to write "return null" instead of break. That should always exit the function.

[–] [email protected] 1 points 2 days ago* (last edited 2 days ago)

Having multiple return statements in one function is a mistake. There shall ever be only one, unless that's unworkable due to tons of checks.

Cringe! That's like watching bad movies for the joy of really really bad movie moments. Watch Dead Snow II THEN Dead Snow I. Both are cringe. Former good cringe later really really bad cringe. Do not watch in chronological order.

A return statement within a while loop. Is that good or bad cringe?

Code with multiple return in one function/method screams noob. Especially when its completely unnecessary and avoidable. The return statement in random locations is a close 2nd.

The return statement in a while loop is just eyebrow raising. Like trying to write cringe, but forgot the threadpool, with GIL enabled, within the while on crack cocaine loop.

[–] [email protected] 1 points 2 days ago

or avoid the break all together; coverage hates break and continue.

is_found = False
while(on crack cocaine):
    if not is_found:
        do something
        is_found = True
    else:  # pragma: no cover
        pass
[–] [email protected] 3 points 3 days ago (1 children)

There's no null in Python. There's None, but like the other comment points out, just using return is fine.

[–] [email protected] 3 points 3 days ago (1 children)

Oh yea sorry, mixed up my programming languages for a second there :)

[–] [email protected] 1 points 2 days ago

... or just trying to identify who will out themselves as Captain Obvious.

went off without a hitch

That was a, sorry not sorry

[–] [email protected] 3 points 4 days ago

Just "return" should work too. Does returning null has a perk?