-2

In my understanding while True: mean loop forever, like saying while True == True.
There is also mechanism to break out of the infinite loop using a break statement.
I came across a function, in the cs50 module, using a while loop (to keep prompting for an int), where there is no break.
I am trying to understand how, when we input an int the "True statement" change to False (that's how I understand it) in the loop and we stop prompting the user.

In other words what can change the while True to false in the code?

The function is as follow:

def get_long(prompt=None):
    """
    Read a line of text from standard input and return the equivalent long;
    if text does not represent a long, user is prompted to retry. If line
    can't be read, return None.
    """
    while True:
        s = get_string(prompt)
        if s is None:
            return None
        if re.search(r"^[+-]?\d+$", s):
            try:
                return long(s, 10)
            except ValueError:
                pass

        # temporarily here for backwards compatibility
        if prompt is None:
            print("Retry: ", end="")

The get_string() function used inside is as follow:

def get_string(prompt=None):
"""
Read a line of text from standard input and return it as a string,
sans trailing line ending. Supports CR (\r), LF (\n), and CRLF (\r\n)
as line endings. If user inputs only a line ending, returns "", not None.
Returns None upon error or no input whatsoever (i.e., just EOF). Exits
from Python altogether on SIGINT.
"""
try:
    if prompt is not None:
        print(prompt, end="")
    s = sys.stdin.readline()
    if not s:
        return None
    return re.sub(r"(?:\r|\r\n|\n)$", "", s)
except KeyboardInterrupt:
    sys.exit("")
except ValueError:
    return None

I am trying to figure how the while True statement is no more true when the s variable get a string and when the string is casted into an int ? Can someone please explain this to me, maybe I am missing something about the while True: statements.

  • Your try-catch statement redundant because you can find only integer number with this regular expression. Also `return None` means that function will return `None` if `get_string` would return `None`. Where do you want to break from your function? – Lev Zakharov Aug 04 '18 at 20:52
  • The command "break" will cause the loop to terminate. Simply place it under whatever conditional you want to cause the loop to end. Realize, any code after the while loop _will_ execute (there is no code after it in your example though). –  Aug 04 '18 at 21:04
  • @LevZakharov This isn't my function i found it in the https://github.com/cs50/python-cs50 . The function is working fine, I just don't understand how it breaks out of the while True statement, in other words, what in the following code make the True statement return to false and break out of the loop. – Future Gadget Aug 04 '18 at 22:35

2 Answers2

2

In this scenerio, the breakout is using a return. So when the condition is met, the enclosing function returns. It returns a None, if the user response can't be read. The pass is just a way to ignore the error and continue prompting the user for input.

osbon123
  • 499
  • 3
  • 11
1

If s is None, that just means nothing was returned from the get_string() function

"pass" will just go to the next line of code. It does nothing and is comparable to a "placeholder" so that your code will run without error. In this case, the pass statement means that if a ValueError is encountered while doing the return long(s, 10), the function will continue with if prompt is None.

Once either of the return statements are executed, the loop will break. Not only that but the whole function get_long() stops executing once either of the return statements are executed.

Also it's more pythonic and pep8 compliant to say:

if not s:
    return None
  • Everything is working as it is in this function, I want to understand how, this is working though – Future Gadget Aug 04 '18 at 20:50
  • A pass will still be required if you do a broad try-except with no action upon except... –  Aug 04 '18 at 21:02
  • fair enough,... I have done that too... but technically any try/except "should" have an associated exception raised. In this example, it could be easily recoded without a try/except –  Aug 04 '18 at 21:05
  • _Should_, but the broad statement "typically wont leave pass..." is not correct. –  Aug 04 '18 at 21:06
  • There are limited situations where a try/except with a pass are used.. not ideal, I agree. –  Aug 04 '18 at 21:07
  • @eDen "How it is working" is that your `return` statement is ending the entire function. –  Aug 04 '18 at 21:10