i am following along with the online book "data science from the command line" by ___. i have no experience with python, so am unfamiliar with it’s syntax and interpretation intricacies.
while running this code, copied verbatim from the book:
import sys CYCLE_OF_15 = ["fizzbuzz", None, None, "fizz", None, "buzz", "fizz", None, None, "fizz", "buzz", None, "fizz", None, None] def fizz_buzz(n: int) -> str: return CYCLE_OF_15[n % 15] or str(n) if __name__ == "__main__": try: while (n: sys.stdin.readline()): print(fizz_buzz(int(n))) except: pass ´
i encounter this error in python 2
File "fizzbuzz.py", line 8 def fizz_buzz(n: int) -> str: ^ SyntaxError: invalid syntax´
and this error in python 3
´ File "/home/wan/saved-websites/datascience/ch04/fizzbuzz.py", line 13 while (n: sys.stdin.readline()): ^ SyntaxError: invalid syntax´
why am i getting different error references for different versions of python? i assume that it’s because of the order the interpreter reads the file, but a definitive answer would be better.
Bonus points: explain why the code itself doesn’t run. using these two error messages i’ve managed to triangulate that the error has to do with how n is assigned or referenced with the colon : operator. is my hypothesis correct?
def fizz_buzz(n: int) -> str:
This syntax is not supported in Python 2. Python added the type hint syntax in version 3.0
while (n: sys.stdin.readline()):
This is nonsense in any Python version. My guess is that the author intended to use the assignment expression operator introduced in Python 3.8 (affectionately called the walrus operator). That would look like
while (n := sys.stdin.readline()):