Please ignore the example, it is just in a book I am currently learning from.
I am running this in Netbeans 6.9.1 as 7 doesn't support Python :( and I am getting a error when trying to run it in the output console. The code is exact as to what is written in the text book. The only thing I can think of is that net beans only supports 2.7.1 yet the book I am learning from is Python 3.1. Could this be the issue? Please let me know if I have overlooked something.
Here is the basic script;
# Word Problems
# Demonstrates numbers and math
print("If a 2000 pound pregnant hippo gives birth to a 100 pound calf,");
print("but then eats 50 pounds of food, how much does she weigh?");
input("Press the enter key to find out.");
print("2000 - 100 + 50 =", 2000 - 100 + 50);
input("\n\nPress the enter key to exit");
Traceback (most recent call last):
File "/Users/Steve/Desktop/NewPythonProject/src/newpythonproject.py", line 6, in <module>
input("Press the enter key to find out.");
File "<string>", line 0
^
SyntaxError: unexpected EOF while parsing
-Thanks guys.
The issue is that input() means something different in Python 3.x. In Python 2.x, the equivalent function is raw_input().
Simply replace your calls to input() with ones to raw_input() and it will work as expected:
# Word Problems
# Demonstrates numbers and math
print("If a 2000 pound pregnant hippo gives birth to a 100 pound calf,")
print("but then eats 50 pounds of food, how much does she weigh?")
raw_input("Press the enter key to find out.")
print("2000 - 100 + 50 =", 2000 - 100 + 50)
raw_input("\n\nPress the enter key to exit")
The reason this caused a problem is that in Python 2.x, input() takes user text, then interprets it as a Python expression. As you were giving it a blank line, which is an invalid expression, it throws an exception.
I would highly suggest using a different editor if you are learning Python 3.x. PyCharm is great (albeit not free), and Eclipse+Pydev is out there. To be honest, you don't really need an IDE for Python - a good text editor like Gedit that supports code highlighting is all you really need.
Also note I removed the semicolons, which are entirely redundant in Python.
Related
This question already has answers here:
How can I limit the user input to only integers in Python
(7 answers)
Closed 9 months ago.
I'm trying to teach myself how to code in Python and this is my first time posting to Stack Overflow, so please excuse any improprieties in this post. But let's get right to it.
I'm trying to use the input command to return an integer. I've done my research, too, so below are my multiple attempts in Python 3.4 and the results that follow:
Attempt #1
guess_row = int(input("Guess Row: "))
I get back the following:
Traceback (most recent call last):
File "<input>", line 1, in <module>
ValueError: invalid literal for int() with base 10: 'Guess Row: 2`
Attempt #2
guess_row = float(input("Guess Row: "))
I get back the following:
Traceback (most recent call last):
File "<input>", line 1, in <module>
ValueError: could not convert string to float: "Guess Row: 2""
Attempt #3
try:
guess_row=int(input("Guess Row: "))
except ValueError:
print("Not an integer")
Here, I get back the following:
Guess Row: 2
Not an integer
Although it returns something, I know this is wrong because, for one, the input returns as a string and it also returns the print command.
Point being, I've tried int, float, and try, and so far nothing has worked. Any suggestions? I just want to be able to input an integer and have it returned as one.
Your third attempt is correct - but what is happening to guess_row before/after this code? For example, consider the following:
a = "Hello"
try:
a = int(input("Enter a number: "))
except ValueError:
print("Not an integer value...")
print(str(a))
If you enter a valid number, the final line will print out the value you entered. If not, an exception will be raised (showing the error message in the except block) and a will remain unchanged, so the final line will print "Hello" instead.
You can refine this so that an invalid number will prompt the user to re-enter the value:
a = None
while a is None:
try:
a = int(input("Enter a number: "))
except ValueError:
print("Not an integer value...")
print(str(a))
To illustrate the comments, from 3.4.2 Idle Shell on Windows, python.org (PSF) installer
>>> n = int(input('Guess1: '))
Guess1: 2
>>> n2 = float(input('Guess2: '))
Guess2: 3.1
>>> n, n2
(2, 3.1)
What system are you using and how did you install Python?
However, I noticed something odd. The code works if I run it just by using the traditional run (i.e., the green button) that runs the entire code, rather than trying to execute individuals lines of code by pressing F2. Does anyone know why this may be the case?
This seems to be a problem in Eclipse, from the PyDev FAQ:
Why raw_input() / input() does not work correctly in PyDev?
The eclipse console is not an exact copy of a shell... one of the changes is that when you press in a shell, it may give you a \r, \n or \r\n as an end-line char, depending on your platform. Python does not expect this -- from the docs it says that it will remove the last \n (checked in version 2.4), but, in some platforms that will leave a \r there. This means that the raw_input() should usually be used as raw_input().replace('\r', ''), and input() should be changed for: eval(raw_input().replace('\r', '')).
Also see:
PyDev 3.7.1 in Eclipse 4 — input() prepends prompt string to input variable?,
Unable to provide user input in PyDev console on Eclipse with Jython.
I am brand new to python. I have been working on the courses on Codecademy. I am also currently using Pydev / LiClipse.
In one of the first lessons on Codecademy it wants you to set the variable parrot to "Norwegian Blue". Then it wants you to print the length of parrot using the len string method. It is very simple, and I got the answer right away with:
parrot = "Norwegian Blue"
print len(parrot)
When I put the exact same code into LiClipse it returned:
SyntaxError: invalid syntax
It work in LiClipse when I changed it to:
print (len(parrot))
Can someone let me know why that worked in codecademy, but not in LiClipse, and why adding the parenthesis fixed it?
It sounds like Pydev/LiClipse is using Python 3 while Codeacademy is using python 2.x or some other older version. One of the changes made when python updated from 2.x to 3 was print is now a function.
Python 2:
print "stuff to be printed"
Python 3:
print("stuff to be printed")
You must take into account the version in which you are working.
In Python 2 your code would look like this:
parrot = "Norwegian Blue"
print len(parrot)
In Python 3 your code would look like this:
parrot = "Norwegian Blue"
print ( len(parrot) )
It worked in CodeAcademy because their interpreter is a Python 2.7, where you didn't need the parenthesis because print was a statement. In Python 3.0+, print requires the parentheses because it's a function.
More information on what's different between Python 2.7 and 3.0+ can be found here:
What's New In Python 3.0
Some of the sample differences with print on the above page:
Old: print "The answer is", 2*2
New: print("The answer is", 2*2)
Old: print x, # Trailing comma suppresses newline
New: print(x, end=" ") # Appends a space instead of a newline
Old: print # Prints a newline
New: print() # You must call the function!
It's good to know the differences between both, in case you're working with legacy systems and the lot vs. in your private environment. In Python 2.7 and below, print() works; however, omitting the ()s does not work in Python 3.0+, so it's better to get into the habit of using them for print.
End of life for Python 2.7 is expected to be in 2020, so you have plenty of time anyway.
In Python 3 print was changed to require parenthesis. CodeAcademy is probably using Python 2 and it looks like you're using Python 3.
https://docs.python.org/3/whatsnew/3.0.html#print-is-a-function
From the docs
Print Is A Function
The print statement has been replaced with a
print() function, with keyword arguments to replace most of the
special syntax of the old print statement (PEP 3105). Examples:
So this line of code in my Python game is not working:
direction=raw_input("What would you like to do?\n")
It's supposed to get the player to type in a command either: North, South, East, West, Look, Search, Commands or Inventory. It's coming up with this:
Traceback (most recent call last):
File "/Users/khalilismail/Desktop/COMPUTING/Text-based Games/DragonQuest.py", line 173, in
direction=raw_input("What would you like to do?\n")
EOFError: EOF when reading a line
Please help
Here is the stack of code surrounding this:
while game==on:
while place==town:
direction=raw_input("What would you like to do?\n")
if direction=="west":
if "iron ore" and "wood" and "3 Gold Pieces" in items:
print "The blacksmith greets you, and you tell him that you have the items and money he requires, you also give him the saw to make up for some of the difference, he then forges you a battleaxe and wishes you luck on the rest of your quest"
items.remove ("saw")
items.remove ("3 Gold Pieces")
items.remove ("iron ore")
items.remove ("wood")
items.append ("battleaxe")
As suggested in the comments, some editors don't support input (including Atom). Here are some options you can overcome this:
Set the direction variable by hard-coding it while debugging (don't forget to remove it after debugging)
Change your editor (keep in mind that Sublime also has the same problem, but this has a workaround - Sublime Text 2 console input; Notepad++ however doesn't have this problem when running code through command line).
You could also try and remove the newline '\n' from the raw_input string to test if it works.
I currently teach first year university students python, and I was surprised to learn that the seemingly innocuous input function, that some of my students had decided to use (and were confused by the odd behaviour), was hiding a call to eval behind it.
So my question is, why does the input function call eval, and what would this ever be useful for that it wouldn't be safer to do with raw_input? I understand that this has been changed in Python 3, but it seems like an unusual design decision in the first place.
Python 2.x input function documentation
Is it ever useful to use Python 2's input over raw_input?
No.
input() evaluates the code the user gives it. It puts the full power of Python in the hands of the user. With generator expressions/list comprehensions, __import__, and the if/else operators, literally anything Python can do can be achieved with a single expression. Malicious users can use input() to remove files (__import__('os').remove('precious_file')), monkeypatch the rest of the program (setattr(__import__('__main__'), 'function', lambda:42)), ... anything.
A normal user won't need to use all the advanced functionality. If you don't need expressions, use ast.literal_eval(raw_input()) – the literal_eval function is safe.
If you're writing for advanced users, give them a better way to input code. Plugins, user modules, etc. – something with the full Python syntax, not just the functionality.
If you're absolutely sure you know what you're doing, say eval(raw_input()). The eval screams "I'm dangerous!" to the trained eye. But, odds are you won't ever need this.
input() was one of the old design mistakes that Python 3 is solving.
Python Input function returns an object that's the result
of evaluating the expression.
raw_input function returns a string
name = "Arthur"
age = 45
first = raw_input("Please enter your age ")
second = input("Please enter your age again ")
# first will always contain a string
# second could contain any object and you can even
# type in a calculation and use "name" and "age" as
# you enter it at run time ...
print "You said you are",first
print "Then you said you are",second
examples of that running:
Example: 1
Prompt$ python yraw
Please enter your age 45
Please enter your age again 45
You said you are 45 Then you said you are 45
Example: 2
Prompt$ python yraw
Please enter your age 45 + 7
Please enter your age again 45 + 7
You said you are 45 + 7 Then you said you are 52
Prompt$
Q. why does the input function call eval?
A. Consider the scenario where user inputs an expression '45 + 7' in input, input will give correct result as compared to raw_input in python 2.x
input is pretty much only useful as a building block for an interactive python shell. You're certainly right that it's surprising it works the way it does, and is rather too purpose-specific to be a builtin - which I presume is why it got removed from Python 3.
raw_input is better, It always returns the input of the user without changes.
Conversely The input() function will try to convert things you enter as if they were Python code, and it has security problems so you should avoid it.
In real program don't use input(), Parse your input with something that handles the specific input format you're expecting, not by evaluating the input as Python code.
I'm liking this book so far, but I run into an issue with exercise 17. It won't run:
neil#neil-K52F:~/python$ python ex17.py ex17from.txt ex17to.txt
File "ex17.py", line 8
indata input.read()
^
SyntaxError: invalid syntax
The book makes me create a variable named input. Is this a legal variable name?
The code you posted simply puts one identifier next to another, without anything (but a space) in between. That's as meaningless and invalid in Python as it is in English. The code in the book has an assignment in there (i.e. indata = ...).
Normally you set a value for your input/raw_input(python 2.x)
x = input("Text Here")
You may also call a data type function on input method
x = float(input("Enter a Number")
x = int(input("Enter an Integer")
I use these all the time in Python 2.7 where raw_input() stores the value as a string.