Learn Python the Hard Way -- ex17.py under python-3 environment - python-3.x

I try to learn this book under python-3 environment but it pops out an error when I try to run it. Is there anywhere to fix this?
Once I deleted
print("Ready, hit RETURN to continue, CTRL-C to abort.")
input()
The code ran perfectly. So I think it should be the syntax problem between python 2 and python 3
from sys import argv
from os.path import exists
script, from_file, to_file = argv
print("Copying from %s to %s" % (from_file,to_file))
# we could do these two on one line too, how?
in_file = open(from_file)
indata = in_file.read()
print("The input file is %d bytes long" % len(indata))
print("Does the output file exist? %r" % exists(to_file))
print("Ready, hit RETURN to continue, CTRL-C to abort.")
input()
out_file = open(to_file, 'w')
out_file.write(indata)
print("Alright, all done")
out_file.close()
in_file.close()
When I try to run it, it should stops at input() and wait me hit the return key to continue. But in reality, the code stopped and an error called
"Traceback (most recent call last):
File "ex17.2.py", line 18, in <module> g
input("")
File "<string>", line 0
^
SyntaxError: unexpected EOF while parsing
popped out.

Yes you are correct!! The error you are getting is due to python version change. This code works perfectly fine in python 3.x but fails in python version under 3.x.
Hope this helps.

Related

PYTHON - TRY: ARGV STILL ERRORS OUT

Just trying to handle some IndexError while using sys. Searched a lot on how to do it, and I've come to a final "solution", but I don't know why it's not working.
Actual code
#!/usr/bin/python3
import sys
t = sys.argv[1]
u = sys.argv[2]
try:
t = sys.argv[1]
except IndexError:
print("no arg 1")
try:
u = sys.argv[2]
except IndexError:
print("no arg 2")
Output
Traceback (most recent call last):
File "/home/try.py", line 9, in <module>
t = sys.argv[1]
IndexError: list index out of range
I don't know why it errors out, since I have set previously the sys.argv[1] inside the try block
Could anyone help me out on this?
EDIT:
I was able to find a way around for this, which is, a separate script for different stuff.
The issue comes from the t and u definitions above the two try blocks. Get rid of those and keep your try blocks and you should be good.
In addition to the spurious statements at the start (i.e. outside of the try statement), I think you are misunderstanding how array subscripting works in Python.
Python arrays start from subscript 0 (not 1). For an array with 2 elements, their subscripts are 0 and 1. So your code should be:
import sys
try:
t = sys.argv[0] # <<<
except IndexError:
print("no arg 1")
try:
u = sys.argv[1] # <<<
except IndexError:
print("no arg 2")
Searched a lot on how to do it ...
Can I point out that this is NOT a good way to learn to program ... or to find the bugs in your code. You should not be searching for "solutions". You should be reading your code, and looking at the evidence and trying to figure out what you have done wrong.
For example, the version of the code in your question actually produces this output:
$ ./test.py
Traceback (most recent call last):
File "./test.py", line 5, in <module>
t = sys.argv[1]
IndexError: list index out of range
It says that the error is on line 5. Then you look at the code and see that line 5 is NOT in the try: statement.
Secondly, you should be consulting reliable resources on Python; e.g. the official documentation, a textbook, or a decent tutorial. They will explain clearly how array subscripting works, for example.

How do I fix this EOF error on python 3 version

I am working on a very basic problem on Hackerrank.
Input format:
First line contains integer N.
Second line contains string S.
Output format:
First line should contain N x 2.
Second line should contain the same string S.
sample test case
5
helloworld
my code is as: (on PYTHON 3)
n=int(input())
s=input()
print(2*n)
print(s)
I am getting error:
Execution failed.
EOFError : EOF when reading a line
Stack Trace:
Traceback (most recent call last):
File "/tmp/143981299/user_code.py", line 1, in <module>
N = int(input())
EOFError: EOF when reading a line
I tried this method to take input many times and this is the first time I am having this error. Can anyone please explain why?
use a try/except block to handle the error
while True:
try:
n=int(input())
s=input()
print(2*n)
print(s)
except:
break

Taking input while accounting for both Python 2.x and 3.x

Since Python 2's raw_input was changed to just input for Python 3, I was wondering if there was a way to take input while accounting for both Python 2 and 3. I'm trying to write a script for both versions, and this input part is the only thing that's not working well.
I tried running just input with Py2, and this happens:
>>> a = input('Input: ')
inp: test
Traceback (most recent call last):
File "<pyshell#0>", line 1, in <module>
a = input('Input: ')
File "<string>", line 1, in <module>
NameError: name 'test' is not defined
I saw a workaround to quote the input:
>>> a = input('Input: ')
inp: "testing test"
a
'testing test'
Is there a way to concatenate the quote to the beginning and end of the input? '"' + input('input: ') + '"' isn't working
Probably not a good practice, but you can use a try block to test whether the raw_input() is being recognized (thus telling you whether you're on Python 2.x or Python 3.x):
try:
a = raw_input('input: ')
except NameError:
a = input('input: ')
I would use raw_input() to test because it's not accepted by Python 3.x and is what you expect to use in Python 2.x, so the input() will not trigger in Python 2.x.
I'm not an expert so I'm sure there are better suggestions.
#Chris_Rands' suggested dupe thread has a more elegant solution by binding input = raw_input so if you have multiple input(), you only need to try once.
This works for both Python 2 and 3.
from builtins import input
input("Type something safe please: ")

Python Code Error With Input

I Am having a problem with an input code here is the out come of the code
Hello World The Game
Youtube: www.youtube.com/user/creepermoon2/
Current Game Version 0.1 Alpha
What Is your name?Josef
Traceback (most recent call last):
File "C:/Python27/Game.py", line 25, in <module>
Name = input ("What Is your name?")
File "<string>", line 1, in <module>
NameError: name 'Josef' is not defined
The code is
#This is a simple video game created by CreeperMoon2
#PROGRAMING NOTES
#to wait use time.sleep(SECONDS)
#
#
#
#
#VARIABLES
GameVrsn = 0.1
#VARIABLES
#IMPORTED CLASSES
import time
import os
#IMPORTED CLASSES
print "Hello World The Game"
time.sleep(5)
print "Youtube: www.youtube.com/user/creepermoon2/"
time.sleep(5)
print ("Current Game Version 0.1 Alpha")
time.sleep(5)
Name = input ("What Is your name?")
I really have no idea how to fix this i got this out of a tutorial for python 3 it may be incorrect but i don't know how to fix it please respond quickly
Although you think you are running the 3.x interpreter you are actually using the 2.x one, because
print "Hello World The Game"
would be an error with python 3. (print is a function there: print("Hello World The Game"))
In Python 2 you should use raw_input instead of input.
Your code is a mix of Python 2 and 3 syntax and would not work on either without error.

How to replace execfile() with exec() in Pydev on Ctrl+Alt+Enter key binding?

There's a problem in Pydev 2.5 and Python 3.2 with trying to load the module contents "into" the interactive console: when you hit Ctrl+Alt+Enter, Pydev fires execfile(filename) instead of exec(compile(open(filename).read(), filename, 'exec'), globals, locals) - the latter being execfile()'s replacement in Python 3+...
So, how to change this behaviour?
ETA: to be a bit more concrete, things go like this: I create a new PyDev Module, say 'test.py', write some simple function def f(n): print(n), hit Ctrl+Alt+Enter, then I select "Console for currently active editor" and Python 3.2 interpreter, interactive console wakes up, and then I get this:
>>> import sys; print('%s %s' % (sys.executable or sys.platform, sys.version))
PyDev console: using default backend (IPython not available).
C:\Program Files (x86)\Python\3.2\python.exe 3.2.3 (default, Apr 11 2012, 07:15:24) [MSC v.1500 32 bit (Intel)]
>>> execfile('C:\\testy.py')
>>> f(1)
Traceback (most recent call last):
File "<console>", line 1, in <module>
NameError: name 'f' is not defined
As you can see, it still uses execfile() instead of exec(), that replaced it in Python 3+...
EDIT:
The actual problem is that the execfile is not getting the proper globals in the PyDev redefinition. So, if the execfile did execfile('my_file', globals()), it would work... I'll change the implementation of PyDev so that if the globals is not passed, it'll do:
if glob is None:
import sys
glob = sys._getframe().f_back.f_globals
(you can fix that in your local install at plugins/org.python.pydev_XXX/PySrc/_pydev_execfile.py and it should work -- please let me know if it doesn't).
INITIAL ANSWER:
That's not possible, but PyDev does redefine execfile when you're in its console on Python 3, so, it should still work... is that not working for you for some reason?
Also, the replacement: exec(compile(open(filename).read(), filename, 'exec'), globals, locals) is broken for some situations in Python 3.
The actual redefinition (which should work in all situations and is available in PyDev) is:
#We must redefine it in Py3k if it's not already there
def execfile(file, glob=None, loc=None):
if glob is None:
glob = globals()
if loc is None:
loc = glob
stream = open(file, 'rb')
try:
encoding = None
#Get encoding!
for _i in range(2):
line = stream.readline() #Should not raise an exception even if there are no more contents
#Must be a comment line
if line.strip().startswith(b'#'):
#Don't import re if there's no chance that there's an encoding in the line
if b'coding' in line:
import re
p = re.search(br"coding[:=]\s*([-\w.]+)", line)
if p:
try:
encoding = p.group(1).decode('ascii')
break
except:
encoding = None
finally:
stream.close()
if encoding:
stream = open(file, encoding=encoding)
else:
stream = open(file)
try:
contents = stream.read()
finally:
stream.close()
exec(compile(contents+"\n", file, 'exec'), glob, loc) #execute the script

Resources