Python 2.xx to 3.xx input workarounds

26 views
Skip to first unread message

CM

unread,
Sep 11, 2017, 12:28:50 AM9/11/17
to com...@googlegroups.com
There are some differences between Python 2 and Python 3 that might be unexpected for new Python users.  Since the book is written with Python 2.7 in mind, some of the example-code may require tweaking to work with Python 3.  I figure we can post the tweaks here as we find them.

In Program listing 1.1 (motion.py), input is entered via the line:

a, v0 = input('enter a, v0 (e.g. 1.0, 0.0): ')

This will create some errors when entering a and v0 in Python 3.6To work around this, I did:

a, v0 = input('enter a, v0 (e.g. 1.0, 0.0): ').split(',')  #read input, using a comma as a delimiter.
a = float(a)  #a appears to be read as a string; change it to a float.
v0 = float(v0)  #same for v0.

This tweak gets the program to run as expected.

Jay Wang

unread,
Sep 11, 2017, 8:24:17 AM9/11/17
to comphys
Another workaround for it to work in Python 3.xx is to add eval before input as
a, b = eval(input('enter a, b:'))

This is because Python 3.xx changed the behavior of input to act like raw_input of 2.xx.

Reply all
Reply to author
Forward
0 new messages