Here's my python code. Could someone show me what's wrong with it.
while 1:
date=input("Example: March 21 | What is the date? ")
if date=="June 21":
sd="23.5° North Latitude"
if date=="March 21" | date=="September 21":
sd="0° Latitude"
if date=="December 21":
sd="23.5° South Latitude"
if sd:
print sd
And Here's what happens:
>>>
Example: March 21 | What is the date?
Traceback (most recent call last):
File "C:\Users\Daniel\Desktop\Solar Declination Calculater.py", line 2, in <module>
date=input("Example: March 21 | What is the date? ")
File "<string>", line 0
^
SyntaxError: unexpected EOF while parsing
>>>
Use raw_input instead of input :)
If you use input, then the data you
type is is interpreted as a Python
Expression which means that you
end up with gawd knows what type of
object in your target variable, and a
heck of a wide range of exceptions
that can be generated. So you should
NOT use input unless you're putting
something in for temporary testing, to
be used only by someone who knows a
bit about Python expressions.
raw_input always returns a string
because, heck, that's what you always
type in ... but then you can easily
convert it to the specific type you
want, and catch the specific
exceptions that may occur. Hopefully
with that explanation, it's a
no-brainer to know which you should
use.
Reference
Note: this is only for Python 2. For Python 3, raw_input() has become plain input() and the Python 2 input() has been removed.
Indent it! first. That would take care of your SyntaxError.
Apart from that there are couple of other problems in your program.
Use raw_input when you want accept string as an input. input takes only Python expressions and it does an eval on them.
You are using certain 8bit characters in your script like 0°. You might need to define the encoding at the top of your script using # -*- coding:latin-1 -*- line commonly called as coding-cookie.
Also, while doing str comparison, normalize the strings and compare. (people using lower() it) This helps in giving little flexibility with user input.
I also think that reading Python tutorial might helpful to you. :)
Sample Code
#-*- coding: latin1 -*-
while 1:
date=raw_input("Example: March 21 | What is the date? ")
if date.lower() == "march 21":
....
I had this error, because of a missing closing parenthesis on a line.
I started off having an issue with a line saying:
invalid syntax (<string>, line ...)?
at the end of my script.
I deleted that line, then got the EOF message.
While #simon's answer is most helpful in Python 2, raw_input is not present in Python 3. I'd suggest doing the following to make sure your code works equally well in Python 2 and Python 3:
First, pip install future:
$ pip install future
Second: import input from future.builtins
# my_file.py
from future.builtins import input
str_value = input('Type something in: ')
And for the specific example listed above:
# example.py
from future.builtins import input
my_date = input("Example: March 21 | What is the date? ")
I'm using the follow code to get Python 2 and 3 compatibility
if sys.version_info < (3, 0):
input = raw_input
I'm trying to answer in general, not related to this question, this error generally occurs when you break a syntax in half and forget the other half. Like in my case it was:
try :
....
since python was searching for a
except Exception as e:
....
but it encountered an EOF (End Of File), hence the error. See if you can find any incomplete syntax in your code.
i came across the same thing and i figured out what is the issue. When we use the method input, the response we should type should be in double quotes. Like in your line
date=input("Example: March 21 | What is the date? ")
You should type when prompted on console "12/12/2015" - note the " thing before and after. This way it will take that as a string and process it as expected. I am not sure if this is limitation of this input method - but it works this way.
Hope it helps
After the first if statement instead of typing "if" type "elif" and then it should work.
Ex.
` while 1:
date=input("Example: March 21 | What is the date? ")
if date=="June 21":
sd="23.5° North Latitude
elif date=="March 21" | date=="September 21":
sd="0° Latitude"
elif date=="December 21":
sd="23.5° South Latitude"
elif sd:
print sd `
What you can try is writing your code as normal for python using the normal input command. However the trick is to add at the beginning of you program the command input=raw_input.
Now all you have to do is disable (or enable) depending on if you're running in Python/IDLE or Terminal. You do this by simply adding '#' when needed.
Switched off for use in Python/IDLE
#input=raw_input
And of course switched on for use in terminal.
input=raw_input
I'm not sure if it will always work, but its a possible solution for simple programs or scripts.
Check the version of your Compiler.
if you are dealing with Python2 then use -
n= raw_input("Enter your Input: ")
if you are dealing with python3 use -
n= input("Enter your Input: ")
Check if all the parameters of functions are defined before they are called.
I faced this problem while practicing Kaggle.
Related
I have a few python files that take input as two ints separated by spaces, and return an int. (My class requires this.) I'm having an issue where an extra "D" appears along with my output, after I hit Ctrl-D to end the input. It's running the programs correctly, though - the output is correct.
Here's what I'm seeing:
$ python gcd_euclid.py
144 100
4D
$ python pc_1_ucsd.py
3 4
7D
Oddly...this wasn't happening yesterday, and I'm not sure if I changed anything. Does anyone have any ideas why this is happening and how to fix it?
Edit: Here is the snippet that the course provided for reading the input. I hadn't used sys.stdin before this week.
import sys
input = sys.stdin.read()
tokens = input.split()
a = int(tokens[0])
b = int(tokens[1])
print(a + b)
(they chose to use the input keyword as a variable, not me!)
I suspect it is old keyboard echo (where did the line feed go?) Try feeding shell input using something like:
command-and-args <<!EOF
input lines
!EOF
When I run the following code :
import math
x=float(input('enter : '))
print(x)
and then I input : math.sin or cos or pi or log .... of a number like : sin(2) ,I get this error :
Traceback (most recent call last):
File "C:\Users\user\Desktop\hh.py", line 10, in <module>
x=float(input('enter : '))
ValueError: could not convert string to float: 'sin(x)'
You can get an answer by combining comments from #Walter Tross and #wwii. How to fix the problem if you want users to be able to enter code that will be evaluated with the result stored in x, you should use:
from ast import literal_eval
x = literal_eval(input('enter:'))
P.S. You will need to put quotation marks around the user input.
P.P.S. Your user can put in basically any code to be executed using this input.
To get to the why, you are giving python commands and expecting it to evaluate what you said and store it in x. You are giving words to python and not giving it a way to convert them to numbers. It'd be the same as typing into your terminal 2 plus 2. The words don't mean anything unless you have some kind of compiler.
It is difficult for you to write a program to understand and evaluate expressions, especially ones that include functions like sin or sqrt. However, if you are sure that the user of your program is safe (and that is usually a bad assumption), you can get Python to do the evaluation using the built-in eval function. You could try this:
import math
strexpr = input('enter: ')
print(eval(strexpr))
Then, if you run this program and the user types math.sin(2), the program prints
0.9092974268256817
which is the correct value of the sine of two radians.
NOTE: This little program will allow the user to type any valid Python expression then evaluate it. If the user knows how, he could use this to format the hard drive and wipe out all your data or do all kinds of mischief. Use this only if you are totally sure of the user. But how can you ever be sure about anyone else?
This may be repeated, but none of the existing answers solved my problem.
So, I'm using Python 2.7, and I get this error (title) whenever I try this:
number = int(raw_input('Number : '))
I tried this in Sublime Text 2, compileronline.com and in codecademy; it fails in the first 2 of this sites. It works on codecademy and in the terminal compiler, but I can't understand exactly why it is failing.
The issue here is that Sublime text 2's console doesn't support input.
To fix this issue, you can install a package called SublimeREPL. SublimeREPL provides a Python interpreter that takes in input.
And as for compileronline.com, you need to provide input in the "STDIN Input" field on the lower right of the website.
try:
value = raw_input()
do_stuff(value) # next line was found
except (EOFError):
break #end of file reached
This seems to be proper usage of raw_input when dealing with the end of the stream of input from piped input.
Refer this post
I am very new to programming and I'm starting out with Python. I tried to look up my question here but didn't really find anything.
I'm trying to work a very simple print command but I'm getting an error for some reason that I don't understand.
last = 'smith'
middle = 'paul'
first = 'john'
print(first.capitalize(), middle.capitalize(), last.capitalize(), sep='\t')
According to the answer in the book, this should be right, but every time I try to run it, I get an error with the 'sep':
print(first.capitalize(), middle.capitalize(), last.capitalize(), sep='\t')
^
SyntaxError: invalid syntax
Can someone tell me what I'm doing wrong. for what it's worth I'm using PyScripter.
[EDIT]
Thanks for that. I found out that I'm using Python 2.7.3 instead of 3.3. So I looked up the manual to see how the separator works. It seems to me that the only difference is with the square bracket. The manual describes the print function as :
print([object, ...][, sep=' '][, end='\n'][, file=sys.stdout])
So I changed my print command and added the square bracket:
print ([first.capitalize(),middle.capitalize(),last.capitalize()] [, sep='\t'])
but unfortunately this doesn't work either as I get an error that highlights the square brackets around sep='\t'. Even when I take the brackets out, the error doesn't go away.
I'm not sure what I'm doing wrong, it seems like it should be very simple.
You aren't actually using Python 3, you just think you are. Try:
import sys
print(sys.version)
and see what comes out. The Python 2 print ... statement (not print(...) function in Python 3) interprets this as
print (first.capitalize(), middle.capitalize(), last.capitalize(), sep='\t')
which is trying to print a tuple with a keyword argument, thus the syntax error on sep
So I'm writing a differential calculator program in python 2.4 (I know it's out of date, it's a school assignment and our sysadmin doesn't believe in updating anything) that accepts a user input in prefix notation (i.e. input = [+ - * x^2 2x 3x^2 x], equivalent to x^2 + 2x - 3x^2 * x) and calculates the differential.
I'm trying to find a way to read the command line user input and put the mathematical operators into a queue, but I can't figure it out! apparently, the X=input() and x=raw_input() commands aren't working, and I can find literally 0 documentation on how to read user input in python 2.4. My question is: How do I read in user input in python 2.4, and how do I put that input into a queue? Here is what I am trying:
1 formula = input("Enter Formula:")
2
3 operatorQueue=[]
4
5 int i = len(formula)
6
7 for x in formula:
8 if formula[x] == '*', '+', '-', '/':
9 operatorQueue.append(formula[x])
0
11 print "operator A:", operatorQueue.pop(0)
12
Which is not working (I keep getting errors like "print: command not found" and "formula:command not found")
Any help would be appreciated
#miku already answered with this being your initial problem, but I thought I would add some more.
The "sh-bang" line is required by command line scripts so that the proper process is used to interpret the language, whether it be bash, perl, python,etc. So in your case you would need: /usr/bin/env python
That being said, once you get it running you are going to hit a few other issues. raw_input should be used instead of input, because it will give you back a raw string. input is going to try and eval your string which will mostly likely give you problems.
You may need to review python syntax a bit more. Assignments in python don't require that you declare the variable type: int a = 1. It is dynamic and the compiler will handle it for you.
Also, you will need to review how to do your if elif else tests to properly handle the cases of your formula. That too wont work doing it all on one line with multiple params.
If you're on a unix-ish platform, put a
#!/usr/bin/env python
on top of your program. The shell does not seem to recognize that you are running a python script.