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.