I'm new to working in terminal (Mac, bash) and starting a tutorial, but I don't get the results that are expected.
Here's my code in atom.
print('Hello, python')
name = input('What is your name? ')
print name
And here's what I get after entering Tim (or after entering anything other than and integer)
Hello, python
What is your name? Tim
Traceback (most recent call last):
File "max2.py", line 2, in <module>
name = input('What is your name? ')
File "<string>", line 1, in <module>
NameError: name 'Tim' is not defined
If I enter an integer it works fine.
Hello, python
What is your name? 4
4
My understanding is that input takes the user input and puts it in a string. Any help would be appreciated.
Your code is correct, but you are running it through the wrong version of Python. The input() function is different between Python 2 and Python 3.
Function
Python 2
Python 3
input()
Reads and evaluates a Python expression
Reads a string
raw_input()
Reads a string
Doesn't exist, use input()
Since Python 2 is practically obsolete, you should make sure that your script is being invoked through python3 and not through just "python" (which is different from OS to OS but usually means Python 2).
For example, if your script has a #! line (and you're running it via ./myscript.py) then change that line to specify "python3".
(However, I'm actually not sure whether macOS even comes with Python 3. You may need to install it through Homebrew or whatever else they use on macOS.)
Also note that the print syntax is also very different between the two. You're using the correct syntax for Python 3, but it is only by coincidence that print(x) with one parameter works the same way in both versions.
Related
while True:
string = input('Enter some text to print. \nType "done" to quit>')
if string == 'done':
break
print(string)
print('Done!')
SyntaxError: invalid syntax
image of issue
Image after idz's suggestion
I think your problem is that you wrote:
while true:
instead of
while True:
However, if you are using Python 2 you should be aware that input will attempt to evaluate what you type in as Python. Depending on what your aim is, you may want to use raw_input instead. This is not an issue if your are using Python 3.
I run a loop in my jupyter notebook that references another python file using the execfile command.
I want to be able to see all the various prints and outputs from the file I call from execfile. However, I don't see any of the pandas dataframe printouts. E.g. if I just say 'df' I don't see the output of the table of the dataframe. However, I will see 'print 5'.
Can someone help me what options I need to set to enable this to be viewed?
import pandas as pd
list2loop =['a','b','c','d']
for each_item in list2loop:
execfile("test_file.py")
where 'test_file.py' is:
df=pd.DataFrame([each_item])
df
print 3
The solution is simply using the %run magic instead of execfile (whatever execfile is).
Say you have a file test.py:
#test.py
print(test_input)
Then you can simply do
for test_input in (1, 2, 3):
%run -i test.py
The -i tells Python to run the file in IPython's name space, thus the script knows about all your variables, and variables defined in your script are in your name space afterwards. If you explicitly call sys.exit in your script, you have to additionally use -e.
I'm having this error in a python script:
TypeError: 'str' does not support the buffer interface
The line that is generating the error is
username = cred_file.readlines()[0].split(';')[0]
I'm a python beginner, any help is appreciated.
You're running a python 2 script with python 3. Python 3 now returns bytes no longer str when reading from a binary stream.
3 choices:
run it with python 2. That if you don't have the rights/time to adapt the script, not recommended as python 3 is becoming more and more the norm.
change your code to insert a decode function (it will continue to work in python 2):
username = cred_file.readlines()[0].decode().split(';')[0]
If file is opened in read/binary mode, readlines returns a list of bytes not str. You have do decode the bytes into a str to apply str methods.
open the file in "r" instead of "rb". readlines then returns a list of str and your code will work. Sometimes it can be problematic on windows because of need to preserve the carriage return (\r) chars, so look out for side effects in your code.
Note: cred_file.readlines()[0] is a questionable construction: you're reading the whole file lines, and drop all the lines but the first. Not very efficient I/O and CPU wise.
Prefer that: cred_file.readline() which is equivalent to read the first line.
If you need to read all the lines for further processing, then store the result of readlines in a list.
I am working on a Windows 7 os in a Python (3.2.2) shell. Trying to learn the language I entered and had returned the following:
>>> cast = {
'cleese',
'Palin',
'Jones',
'Idle'
}
>>> print (cast[1])
Traceback (most recent call last):
File "<pyshell#12>", line 1, in <module>
print (cast[1])
TypeError: 'set' object does not support indexing
>>> cast.append('Gilliam')
Traceback (most recent call last):
File "<pyshell#13>", line 1, in <module>
cast.append('Gilliam')
AttributeError: 'set' object has no attribute 'append'
==========================
It seems as if the problem is not in the coding, but with how the program was installed.
I have installed, un-installed and installed again, but the resutl is the same. I there something I need to do before Python's shell is ready to be used?
hans
Python seems to work fine. The point is that set doesn't support indexing or appending. Try using a list instead ([] instead of {}). In place of appending, set has add, but indexing is out.
And Python has useful help,
>>> help(set)
prints a lot of info about sets.
It seems that you were trying to define a list. However, you used braces {} instead of brackets []. The interpreter treated it as a dictionary rather than a list, so indexing and append() didn't work here.
Just to mention in here, set's' do not support indexing, as they are hash based, it is very similar to dictionaries which don't support indexing as well. You can only access a dict by it's key.
If you need indexing, you can convert your set as follows:
convertedToList = list(set(1,2,3))
In python you can compile() string to be executed faster with exec(). But as soon as i use it, we lost information when an exception happen in the exec.
For example, here is a code snippet that calling a unknown method (for demo purposes):
code = 'my_unknown_method()'
bytecode = compile(code, '<string>', 'exec')
And later, i'm calling exec on that bytecode:
exec bytecode
The traceback showed is:
Traceback (most recent call last):
File "test.py", line 3, in <module>
exec bytecode
File "<string>", line 1, in <module>
NameError: name 'my_unknown_method' is not defined
The "exec()" frame is now obscure. I would like to have a better exception like:
Traceback (most recent call last):
File "test.py", line 3, in <module>
exec "my_unknown_method()"
File "<string>", line 1, in <module>
NameError: name 'my_unknown_method' is not defined
Any thoughts ?
Notes:
I don't want to use the second argument of compile (the filename)
I have tested to play with inspect and modify f_code on the frame, but it's readonly attribute.
EDIT: after looking more to sys.excepthook, i've seen that in python source code/traceback.c, when python want to show the line content, they are fopen() directly the file if found. No hook available at all to display our own content. The only way would be to create in real fake filename on disk ? Anyone ?
EDIT2: i checked some jinja2 debug code, and they are rewriting traceback too, but not for content. Would i need a custom except hook ? My concerns with it is since it's not in the traceback itself, if an user/module/whatever take the exception, the traceback will not contain valuable information.
You should have a look at this talk by Armin Ronacher. He's the author of Jinja2 and in this talk he explained, how he manipulates stack traces in Jinja2. If I remember correctly, he's using ctypes, to manipulate the data structures on the C level of Python. The talk was in my opinion the best talk of the whole Europython 2011 by the way.
After a deep search, it's not possible, CPython is using its own API to determine where the file is etc, and it cannot be patched in pure Python.
How about something like this:
import sys
def mkexec(code_str):
bc = compile(code, '<string>', 'exec')
def run():
try:
exec bc
except: # Yes I know a bare except
t, v, tb = sys.exc_info()
raise MyUsefullException("%s raised %s" % (code_str, v))
return run
exe = mkexec("some_unknown_something()")
exe()