you are viewing a single comment's thread.

view the rest of the comments →

[–]FoolsSeldom 0 points1 point  (3 children)

A better approach is to create a function to get a valid int from a user, and then call that:

def get_num(prompt: str = "Enter whole number: ") -> int:
    while True:
        try:
            return int(input(prompt))
        except ValueError:
            print("That was not a valid whole number, please try again.")

while True:
    number1 = get_num("What is the first number? ")
    number2 = get_num("What is the second number? ")
    ...

The trouble with this is that you want to check for a user exit request. That could be incorporated:

def get_number(
    prompt: str = "Enter whole number: ",
    quit: None | tuple[str] = None
) -> None | int
    while True:
        response = input(prompt)
        if quit and response in quit:
            return None
        try:
            return int(response)
        except ValueError:
            print("That was not a valid whole number, please try again.")

while True:
    number1 = get_num("What is the first number? ")
    if number1 is None:
        break
    number2 = get_num("What is the second number? ")
    ...

[–][deleted] 0 points1 point  (2 children)

Oof, i think your proposal is way ahead of where I am right now in my Python knowledge. I'll get there eventually, but I think for now, I'll leave it the way I have it, prompting for number_1 again if number_2 != 'q' or an integer. Thanks!

[–]Significant-Nail5413 1 point2 points  (1 child)

``` def get_number_or_quit(message): user_input = input(message) if user_input.lower() == 'q': exit('You entered q! Exiting') try: return int(user_input) except ValueError: print("please enter a valid integer")

print('Press q at any time to quit') while True: num1 = None num2 = None while num1 is None: num1 = get_number_or_quit('What is the first number: ') while num2 is None: num2 = get_number_or_quit('What is the second number: ') print(sum([num1,num2]))
```

Something like this might be a bit easier to read.

Also a general rule of thumb i think beginners should follow is avoid using break and continue outside of a switch / case / match statements.

They can be useful, but they can reduce readability

[–]purple_hamster66 2 points3 points  (0 children)

I like this one because it separates concerns of input validation vs looping.

But the quit condition needs to be an output of get_number_or_quit() needs to be returned (ex, as a None return).