Skip to content

Commit d8a74a3

Browse files
committedApr 29, 2017
returning None for EOF, updated comments
1 parent 78ad44b commit d8a74a3

File tree

1 file changed

+28
-5
lines changed

1 file changed

+28
-5
lines changed
 

‎cs50/cs50.py

+28-5
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,11 @@ def write(self, x):
2121
sys.stdout = flushfile(sys.stdout)
2222

2323
def get_char(prompt=None):
24-
"""Read a line of text from standard input and return the equivalent char."""
24+
"""
25+
Read a line of text from standard input and return the equivalent char;
26+
if text is not a single char, user is prompted to retry. If line can't
27+
be read, return None.
28+
"""
2529
while True:
2630
s = get_string(prompt)
2731
if s is None:
@@ -34,7 +38,11 @@ def get_char(prompt=None):
3438
print("Retry: ", end="")
3539

3640
def get_float(prompt=None):
37-
"""Read a line of text from standard input and return the equivalent float."""
41+
"""
42+
Read a line of text from standard input and return the equivalent float
43+
as precisely as possible; if text does not represent a double, user is
44+
prompted to retry. If line can't be read, return None.
45+
"""
3846
while True:
3947
s = get_string(prompt)
4048
if s is None:
@@ -50,7 +58,11 @@ def get_float(prompt=None):
5058
print("Retry: ", end="")
5159

5260
def get_int(prompt=None):
53-
"""Read a line of text from standard input and return the equivalent int."""
61+
"""
62+
Read a line of text from standard input and return the equivalent int;
63+
if text does not represent an int, user is prompted to retry. If line
64+
can't be read, return None.
65+
"""
5466
while True:
5567
s = get_string(prompt);
5668
if s is None:
@@ -69,7 +81,11 @@ def get_int(prompt=None):
6981

7082
if sys.version_info.major != 3:
7183
def get_long(prompt=None):
72-
"""Read a line of text from standard input and return the equivalent long."""
84+
"""
85+
Read a line of text from standard input and return the equivalent long;
86+
if text does not represent a long, user is prompted to retry. If line
87+
can't be read, return None.
88+
"""
7389
while True:
7490
s = get_string(prompt)
7591
if s is None:
@@ -85,11 +101,18 @@ def get_long(prompt=None):
85101
print("Retry: ", end="")
86102

87103
def get_string(prompt=None):
88-
"""Read a line of text from standard input and return it as a string."""
104+
"""
105+
Read a line of text from standard input and return it as a string,
106+
sans trailing line ending. Supports CR (\r), LF (\n), and CRLF (\r\n)
107+
as line endings. If user inputs only a line ending, returns "", not None.
108+
Returns None upon error or no input whatsoever (i.e., just EOF).
109+
"""
89110
try:
90111
if prompt is not None:
91112
print(prompt, end="")
92113
s = sys.stdin.readline()
114+
if not s:
115+
return None
93116
return re.sub(r"(?:\r|\r\n|\n)$", "", s)
94117
except ValueError:
95118
return None

0 commit comments

Comments
 (0)
Please sign in to comment.