NameError when using input() with Python 3.4 - python

I am a new Python user and I have been working through a number of tutorials. This has included running some of the code from the Command Prompt. This worked fine when I first tested the code but for some reason it seems to have stopped working and I am now getting errors when using Input(). I have included the code below and the error message I am receiving.
Code:
import sys
print (sys.version)
print("hello world")
myName = input("What is your name?")
print(myName)
if (myName == "Matt"):
print("Matt is great!")
elif (myName == "Bob"):
print("Bob is ok")
else:
print("Hello world")
input("Press enter to continue")
Error Message:
C:\Users\matt.xxxx>cd C:\Python34\Scripts\Projects
C:\Python34\Scripts\Projects>helloworld.py
2.7.7 (default, Jun 1 2014, 14:21:57) [MSC v.1500 64 bit (AMD64)]
hello world
What is your name?Matt
Traceback (most recent call last):
File "C:\Python34\Scripts\Projects\helloworld.py", line 6, in <module>
myName = input("What is your name?")
File "<string>", line 1, in <module>
NameError: name 'Matt' is not defined
C:\Python34\Scripts\Projects>
I know this can occur when using older versions of python, however I have checked and I am fairly sure I am using version 3.4 (checked using import sys etc.). I have recently installed PyCharm which is the only thing I can think of that has changed. The code works in PyCharm and from IDLE but not from the Command Prompt. Any help would be much appreciated.

From your example , I believe you are running the script using - helloworld.py - this would cause Windows to lookup the default application associated with the extension .py and run it.
I am guessing in your case when you installed PyCharm, it somehow made Python 2.7.7 the default application for .py files (Or it was like that from the start) so when you directly run .py files (even from command prompt) they run using Python 2.7.7 .
You said in your comment that when running python directly from command prompt, you are getting python 3.4 , so the easiest way to fix your issue would be to use that to run your script.
Run it using the command -
python helloworld.py
As a long term solution, you may want to consider changing the default application associated with .py files. You can checkout this link for guide on how to do that

Related

Impossible to run jupyter-book command after installing it

I'm trying to use Jupyter-book to create automatical PDF from my output, but after installing it using the 'pip install -U jupyter-book' command (which runs successfully), it doesn't recognize jupyter-book when I try to run a command:
Input:
jupyter_book create Jupyter_Book_Name
Output:
SyntaxError: invalid syntax (Temp/ipykernel_16888/3781613275.py, line 1)
File "C:\Users\MAXIME~1.DUS\AppData\Local\Temp/ipykernel_16888/3781613275.py", line 1
jupyter_book create Jupyter_Book_Name
^
SyntaxError: invalid syntax
I already try to add the init jupyter_book function in the sys.path but I get the same error, and the error arises for any command. I am working in Python 3.9.7 with Jupyter Notebook in Visual Studio Code on Windows 10.
Thank you in advance, any help would really help me.
Looks like you're confusing a shell (bash / ...) with a Python REPL.
You're running a shell command in a Python interpreter, a bit like if you try to start Python by typing python inside a Python interpreter:
$ python # Here I'm in bash, I run Python
Python 3.9.7 (default, Sep 3 2021, 06:18:44)
>>> python # Here I'm in the Python interpreter
# typing python again...
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'python' is not defined
# Yup, calling `python` here make no sense, Python looks for a variable
# named `python` not a program named `python`, and won't find it.
So get out of a Python interpreter, find a shell (depending on your OS), and run the command again.
Oh while I'm here, it's probably not:
jupyter_book create Jupyter_Book_Name
but:
jupyter-book create Jupyter_Book_Name

Python doesn't run properly on Visual Studio Code

I downloaded Visual Studio Code and installed Python following the instructions at https://code.visualstudio.com/docs/python/python-tutorial.
As I chose the Python extension in Visual Studio Code, an installation started, but it told me afterwards that the system install is not supported. Therefore I installed it with Homebrew.
First of all, I seem do not have the green 'run'-button displayed in the installation tutorial above. There I only can run code with right click and 'Run Selection/Line in Python Terminal'.
A simple print('Hello, World!') seems to run properly, but when I try to run a program with more than one line (i.e., more than one instruction) I get multiple error messages that I did not get while using Anaconda before.
For context: I am currently learning to program using Python and follow the book 'Automate the boring stuff with Python'.
The code I try to run is:
#! python3
# mclip.py - A multi-clipboard program.
TEXT = {'agree': """Yes, I agree. That sounds fine to me.""",
'busy': """Sorry, can we do this later this week or next week?""", 'upsell': """Would you consider making this a monthly donation?"""}
import sys, pyperclip
if len(sys.argv) < 2:
print('Usage: py mclip.py [keyphrase] - copy phrase text')
sys.exit()
keyphrase = sys.argv[1] # first command line arg is the keyphrase
if keyphrase in TEXT:
pyperclip.copy(TEXT[keyphrase])
print('Text for ' + keyphrase + ' copied to clipboard.')
else:
print('There is no text for ' + keyphrase)
For clarification:
Traceback (most recent call last): File "/Users/XXX/Desktop/Python Projects/Ex.py", line 7, in <module> import sys, pyperclip ModuleNotFoundError: No module named 'pyperclip'
is the error I get.
I just want to use Visual Studio Code properly and I am really not sure why it isn't working or what I did wrong while installing it. (For example, why am I missing the green 'run'-button?!)
There is one syntax error in your code on line 10. sys.exit() should be on the next line. Once that was fixed, it ran fine for me in my Visual Studio Code.
It's the indentation error:
if len(sys.argv) < 2:
print('Usage: py mclip.py [keyphrase] - copy phrase text')
sys.exit()
sys.exit() should be on the next line.
For displaying a green play button, you have to install the Python extension in Visual Studio Code.
You have made an error. When I ran it I got it. You have to place sys.exit() after enter or on the next line:
sys.exit()

Neovim throws an error running input(), runs ok in Vim

Noob question here, Neovim throws an error when running a script using input() in the command-line window, while the same script runs in vim 8.0. eg
print('Enter your name:')
myName = input()
:! python % <- ex command used
Nvim output:
myName: Traceback (most recent call last):
File "x.py", line 2, in <module>
myName = input()
EOFError: EOF when reading a line
shell returned 1
I prefer the way neovim runs it's scripts in it's own bottom window as opposed to vim outputting to the command line, but I have to switch to vim for any scripts using input().
Is there a nvim.init setting or a different command I can use to succeed here, or is this a known flaw in neovim? I'm on wsl using the latest vim and nvim.
I am not sure why you're getting this error. But, since you are using neovim, have you tried using the built-in terminal emulator? The below command can be used to run the program within newovim in a new split window:
:vsplit term://python3 %
python3 is the name of program, which can be substituted with any other program. Where % is the current file's path. See :h terminal-start for more information.
The same can be done using Vim (8.0 or above) by using the command:
:term python3 %
this will again open a new split for the program running. See :h terminal for more information.
A further optimization to the workflow would be to add a filetype specific mapping. In our case that would be(unix like systems) in ~/.vim/after/ftplugin/python.vim
nnoremap <leader>r :vsplit term://python3 %<cr>

Can't run Python code in Command Prompt

I'm new to Python and I created my first piece of code which is simply
print('Hello World!')
and it works fine and I named it hello.py. When I try to open the file it says with "python hello.py"
I get an error message that says
File "hello.py", line 1
PYthon 3.4.4 (v3.3.3:737efcadf5a6, Dec 20 2015, 20:20:57) [MSC v.1.600 64 bit (AMD65)] on win32
SyntaxError: invalid syntax
I added Python to the PATH so I don't know what's the issue
You're not supposed to put those lines into your script. They come from the interpreter, giving information to you. You're only supposed to include in your script the commands that you want to give to the interpreter. In your case, your hello.py file should consist entirely of this:
print('Hello World!')
and nothing else.

Why can't Python find and run my scripts when calling Python from Python command line?

I am in the python command line (using python 2.7), and trying to run a Python script. My operating system is Windows 7. I have set my directory to the folder containing all of my scripts, using:
os.chdir("location").
os.getcwd() returns this location.
When I type:
python myscript.py
I get this error:
File "<stdin>", line 1
python myscript.py
^
SyntaxError: invalid syntax.
What have I done wrong?
The first uncommented line of the script I'm trying to run:
from game import GameStateData
It sounds like you're trying to run your script from within Python. That's not how it works. If you want to run myscript.py, you need to do it from a system command prompt, not from inside the Python interpreter. (For instance, by choosing "Command Prompt" from your start menu. I think it's usually under "Accessories" or something like that.) From there you'll need to change to the directory where your scripts are by using the CD command.
Based on the additional information you have provided it does look like you are issuing the command inside of Python.
EDIT: Maybe part of the confusion comes from the term command line. You are at the command line in both the "Windows command" shell, and also when you are inside the "Python shell".
This is what I get in the command line when inside the Python shell:
D:\Users\blabla \Desktop>python
Python 2.7.2 (default, Jun 12 2011, 15:08:59) [MSC v.1500 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> python testit.py
File "<stdin>", line 1
python testit.py
^
SyntaxError: invalid syntax
>>>
Or this:
>>> os.chdir("..")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'os' is not defined
>>>
My suggestion would be to open a Windows command shell window with the cmd command and then issue your python myscript.py from there.
For more help it would be helpful to see your code, at least the first few lines where the error occurs and some certainty as to where the python command is being issued.
As the other answers indicate, you are probably in the Python shell unintentionally. But if you really do want to run your script from there, try execfile("myscript.py")
on windows shell run echo %PATH%, and check if your .py is under any of the paths.

Categories