Python running in IDLE but not terminal? [duplicate] - python

This question already has answers here:
input() error - NameError: name '...' is not defined
(15 answers)
Closed 6 years ago.
upon looking around a bit I have still not come to the conclusion as to why the following piece of python works in IDLE but not terminal. Any help would be appreciated.
print("Hello User!")
request_list = ['']
while True:
greeting = input('')
if greeting.lower() == "hello":
print("Who is this?")
print("Welcome back " + input() +", what can I do for you?")
break
elif greeting.lower() != "hello":
print("Show some manners!")
The error
Traceback (most recent call last):
File "courtney.py", line 23, in <module>
greeting = input('')
File "<string>", line 1, in <module>
NameError: name 'hello' is not defined

you are running python3 IDLE and the terminal is set to python2.
In your computer's environmental variables, you want to change the path to the location of your Python3 installation instead of the python 2.
Take a look at the picture, the one you want to change is PATH
If you dont want to change your environmental variables so that your terminal stays using python2, then you have to change your input and print statements.
the code below is the implementation of your code in python 2.7:
print "Hello User!"
request_list = ['']
while True:
greeting = raw_input("What is your name? ")
if greeting.lower() == "hello":
print "Who is this?"
print "Welcome back " + greeting +", what can I do for you?"
break
elif greeting.lower() != "hello":
print "Show some manners!"

The problem is that you use python 2.x in your terminal. If you have installed both you should be able to use the command 'python3' to run your code instead of the command 'python'.
In python 3 'input' can take an integer or a string. In python2 'input' cannot take a string. Only other stuff. In python 2.x you should use 'raw_input' take a string.

Related

What could be my invalid syntax error in my code?

I am having problems with a simple program I wrote but do not know where the problem is, and it is giving me a Syntax error.
This is my code:
username = {}
temp = True
while temp:
name = input("Please input your username: ")
response = input("What is the place you want to visit? ")
username[name] = response
end = input("Do you want to end the program? Yes/No ")
if end == 'Yes':
temp = False
print("These are the results of the poll: ")
for names, responses in username.items():
print(names + " wants to go to " + responses)
This is my error:
File "<stdin>", line 1
/usr/local/bin/python3 "/Users/eric/Python Notes/Notes.py"
^
SyntaxError: invalid syntax
Check out the accepted answer here:
syntax error when using command line in python
Looks like your problem is that you are trying to run python test.py from within the Python interpreter, which is why you're seeing that traceback.
Make sure you're out of the interpreter, then run the python test.py command from bash or command prompt or whatever.
There are also some VSCode-specific tips here:
Invalid Syntax error when running python from inside Visual Studio Code

How to handle no input using input() function in Python?

I tried to write a program which requests user to choose an option, however, Python always show an error message if user choose nothing and only input ENTER. Here is an example
tmp=input("Choose program type:1.C++;2.Python;3.PERL (ENTER for default 2.Python)")
print tmp, type(tmp) #test input
if len(str(tmp)) == 0:
tmp=0
if tmp == 1:
print "User choose to create a C++ program.\n"
DFT_TYPE=".cpp"
elif tmp ==2:
print "User choose to create a Python program.\n"
DFT_TYPE=".py"
elif tmp ==3:
print "User choose to create a PERL scripts.\n"
DFT_TYPE=".pl"
else:
print "User choose incorrectly. Default Python program would be created.\n"
DFT_TYPE=".py"
if I input ENTER only, I got error message like below
Traceback (most recent call last): File "./wcpp.py", line 17, in <module>
tmp=input() File "<string>", line 0
^ SyntaxError: unexpected EOF while parsing
How to handle such case if user input nothing? Any further suggestion would be appreciated.
Since you are using python 2, use raw_input() instead of input().
tmp=raw_input("Choose program type:1.C++;2.Python;3.PERL (ENTER for default 2.Python)")
...
...
if tmp!='':
tmp = int(tmp)
pass #do your stuff here
else:
pass #no user input, user pressed enter without any input.
The reason you are getting error is because in python2 input() tries to run the input statement as a Python expression.
So, when user gives no input, it fails.
you can use raw_input with a default value
x = raw_input() or 'default_value'

Python 2.7 having multiple say commands on mac

I have tried many things to try to get text to speech to work in python 2.7 on a mac. I managed to write some simple codes using the system os such as:
from os import system
system('say Hello world')
This works alone:
from os import system
string2 = 'test'
string1 = 'hello world' + string2 + '.'
system("say %s" %(string1))
But if I do multiple say commands, like this:
system('say Please tell me your name.')
name = raw_input()
st = "Hello. Want pie" + name + "?"
system("say " + st)
I get this error after I enter my name:
sh: -c: line 0: unexpected EOF while looking for matching `''
sh: -c: line 1: syntax error: unexpected end of file
Am I currently making a mistake in concept, or does having two say commands not work? If having two say commands do not work this way, then how can I use text to speech multiple times in python 2.7 with macintosh?
Trying changing the format and see if you have any better luck.
system('say Please tell me your name.')
name = raw_input()
st = "Hello. Want pie" + name + "?"
system('say %s' %(st))

How does a user input a filename?

I've written code for an assembler, but I am still new to python.
In my code I have the user input a file that will be converted into an assembly language. I think I've almost got it working, but I can't figure out where the user enters the file name.
I'm in (what I think is) IDLE, and then when I hit F5 it runs in the shell. I'm getting an error, but I'm pretty sure it's because no file name has been entered.
Where is the user supposed to input these kinds of things? Is this done from the python shell, or from the command line, do I need to turn it into an executable?
Can someone help clarify where the user is inputting all this information?
I'll put in a segment of code, although I don't think it's necessary to answer my questions, but maybe it'll give you a better idea of my issue.
if __name__ == '__main__':
import sys
if len(sys.argv) == 1:
print 'need filename'
sys.exit(-1)
table = SymbolTable()
parser = Parser(sys.argv[1])
parser.advance()
line = 0
while parser.hasMoreCommands():
if parser.commandType() == 'L_COMMAND':
table.addEntry(parser.symbol(), line)
else:
line += 1
parser.advance()
code = Code()
parser = Parser(sys.argv[1])
parser.advance()
var_stack = 16
while parser.hasMoreCommands():
cmd_type = parser.commandType()
if cmd_type == 'A_COMMAND':
number = 32768
try:
addr = int(parser.symbol())
except:
if table.contains(parser.symbol()):
addr = table.getAddress(parser.symbol())
else:
table.addEntry(parser.symbol(), var_stack)
addr = var_stack
var_stack += 1
bin_number = bin(number | addr)[3:]
assembly = '0' + bin_number
print assembly
elif cmd_type == 'C_COMMAND':
assembly = '111'
assembly += code.comp(parser.comp())
assembly += code.dest(parser.dest())
assembly += code.jump(parser.jump())
print assembly
parser.advance()
The part to note is at the beginning lines 4-6 where it's checking the file name. So once I run my program I get 'need filename' printed to the screen and an error message that looks like this:
Traceback (most recent call last):
File "C:\Python27\Assembler.py", line 98, in <module>
sys.exit(-1)
SystemExit: -1
So where can I input the filename to avoid this error?
The way you have it, Python expects the filename as an argument:
python file.py your_file.asm
If you want to prompt for a filename, use raw_input() (or input() for Python 3):
filename = raw_input('Enter a filename: ') or 'default_file.asm'
sys.argv contains command line arguments.
So, this script has to be run through command-line, for getting input, as said by blender, use raw_input (or input) for getting input from the user, if there are not enough command-line arguments.
Something like this:
if len(sys.argv) == 1:
print "You can also give filename as a command line argument"
filename = raw_input("Enter Filename: ")
else:
filename = sys.argv[1]
And change the line
parser = Parser(sys.argv[1])
To
parser = Parser(filename)

getting error with learn python the hard way exercise 14

I am following zed shaw's learn python the hard way and am following exercise 14. Here's the program I am talking about:
from sys import argv
script, user_name = argv
prompt = '> '
print "Hi %s, I'm the %s script." % (user_name, script)
print "I'd like to ask you a few questions."
print "Do you like me %s?" % user_name
likes = raw_input(prompt)
print "Where do you live %s?" % user_name
lives = raw_input(prompt)
print "What kind of computer do you have?"
computer = raw_input(prompt)
print """
Alright, so you said %r about liking me.
You live in %r. Not sure where that is.
And you have a %r computer. Nice.
""" % (likes, lives, computer)
Now, I run this program in powershell terminal using the command
python e:\python\ex14.py
and I get the following error message:
Traceback (most recent call last):
File "e:\python\ex14.py", line 3, in (module)
script, user_name=argv
ValueError: need more than 1 value to unpack.
Now, I am not sure what the problem is. The only reason could be that I am typing the file path instead of typing the filename only.
This script expects to take an argument at the command line. You're not providing one.
At the terminal, type python e:\python\ex14.py YourNameHere.

Categories

Resources