Ask your own question, for FREE!
MIT 6.00 Intro Computer Science (OCW) 10 Online
OpenStudy (anonymous):

Why am I getting a syntax error in this problem? >>> x = 15 ## Define x >>> if (x/2) * 2 == x: print 'even' ## define even value SyntaxError: invalid syntax

OpenStudy (anonymous):

x=15 ##define if (x/2)*2==x: print 'even' ##the left of 'print' shoud be space

OpenStudy (anonymous):

I am still getting a syntax error at 'even'

OpenStudy (anonymous):

try if ((x/2)*2 ==x): print "even"

OpenStudy (anonymous):

This code works correctly. http://dpaste.com/518071/ If you're getting a syntax error, either you're using python 3 or you have some funky issues with spacing or non-printing characters. My guess is you're using python 3. If that's the case you can try using print('even') and see if that works better. If you're not using python 3. Try retyping your code, but be sure that you indent (with a tab or 3-4 spaces) the line after the if (x/2)*2 == x: line.

OpenStudy (anonymous):

By the way - this logic will call any number even. You need something like if x/2 == int(x/2): print('even')

OpenStudy (anonymous):

or if float(x/2) == int(x/2): print('even')

OpenStudy (anonymous):

@JeffA (15/2) == 7 so (15/2) * 2 == 14 != 15 So the math is fine and the problem is probably indentation or python 3. But it's not terribly versatile since it will call all numbers even if x is a float.

OpenStudy (anonymous):

Indeed. Probably best to use modulo, but the instructor hasn't really covered it in the first lecture or two, so that's why most people use the (x/2) * 2 method.

OpenStudy (anonymous):

(x/2) * 2 is an example in the lecture to illustrate how integer division works.

Can't find your answer? Make a FREE account and ask your own questions, OR help others and earn volunteer hours!

Join our real-time social learning platform and learn together with your friends!
Can't find your answer? Make a FREE account and ask your own questions, OR help others and earn volunteer hours!

Join our real-time social learning platform and learn together with your friends!