PFK and iPython

27 Jan, 2019

Jobakhan writes (edited):

Using this code
import sys
def moon_weight():
    print('Please enter your current Earth weight')
    weight = float(sys.stdin.readline())
    print('Please enter the amount your weight might increase each year')
    increase = float(sys.stdin.readline())
    print('Please enter the number of years')
    years = int(sys.stdin.readline())
    years = years + 1
    for year in range(1, years):
        weight = weight + increase
        moon_weight = weight * 0.165
        print('Year %s is %s' % (years , moon_weight))

then it gives me this:
error in ipython
Why is this happening?

It looks like you're using iPython/Jupyter Notebook to run the examples in the book. Python for Kids wasn't specifically written to work with iPython (nor was the code actually tested with that app), which is why you're having issues. Having said that, I think many of the examples will work, but some, like the code you sent, will need modification.

In the case of the moon_weight function, it's using sys.stdin.readline() (that's the sys module, "standard input" object, readline function) to read input from the user running the program. There are a couple of ways to read command line input in Python - and in the case of Jupyter it looks like stdin doesn't behave the same way as the Python shell. I found the following in the Jupyter client documentation:

This pattern of requesting user input is quite different from how stdin works at a lower level. The Jupyter protocol does not support everything code running in a terminal can do with stdin...

So what's actually happening when you run that code? The function sys.stdin.readline() returns straight away with an empty string (''), and Python then throws an error when trying to convert that empty string to a floating point number. If you replace sys.stdin.readline() in the above code with input(), the program should then work in jupyter:

weight = float(input())
...
increase = float(input())
...
years = int(input())