Python throwing out a random invalid syntax error - python

Version: Python 3.3.2 (default, Sep 11 2013, 20:16:42)
Hey,
I'm doing some tests with python, fiddling a bit with the shell, but I get a strange error.
>>> a = 5
>>> if a > 0:
... print("a is a positive number.")
... if a < 0:
File "<stdin>", line 3
if a < 0:
^
SyntaxError: invalid syntax
I don't know why this error appears. I know I can use elif or else, but I just want to test.
Help?

This is valid Python syntax when it is located in a module, but in the interactive interpreter you need to separate blocks of code with a blank line.
The handy rule of thumb here is that you can't start a new block with if, def, class, for, while, with, or try unless you have the >>> prompt.

Are you pressing backspace to enter the second if? The shell doesn't like that. It's expecting another line in the logic block, or to be able to execute the block (by pressing enter one more time). The shell can only execute one block at a time, i.e. finish the first if first, then you can enter the second if. You can use elif because it's still considered part of the same logic block.

The REPL is still working on the previous code block. Enter an empty line on its own to terminate it first.

You need a blank line after your print statement, the Python interpreter thinks you're continuing a block until you do that, so you get an indentation error on your second if statement. This is not "invalid", the interactive interpreter is designed to work that way.

Related

"undo" goes to int() what shouldn't have happened

I have one problem. While drawing some sprites, why do I have a string named "undo" that goes to int()? (base 10)
import win32gui as w
import os as r
import time as t
import keyboard as kb
import random as ra
fw = w.GetForegroundWindow()
con = w.GetDC(fw)
r.system(f'mode con:cols={64} lines={32}')
r.system('color 07')
def CreateImag(readedlines,x,y):
for u in readedlines:
gg=u.split()
w.BitBlt(con,int(gg[0])+x,int(gg[1])+y,int(gg[2]),int(gg[3]),con,0,0,-1)
print('sprite draw')
t.sleep(2)
rl = []
r.system('cls')
while True:
print("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n"+'='*64+"\n [from x from y f.x+x", end='')
print("f.y+y], for exit type \"exit\", for undo type \"undo\"")
if ag=='undo':
print(list.pop(-1))
break
ag = input('>>')
if ag=='exit':
file = open(f'image{ra.randint(0,100001)}.imag')
for aa in rl:
file.write(f'{aa}\n')
file.close()
rl.append(ag)
CreateImag(rl, 10, 10)
r.system('cls')
and then it gives this
Why is the string not appending?
I read the code and tried to understand the goal of the program, and here are the things I figured out that is done wrong. I stated them and provided solutions for them.
1
The reason why ag=input() is written after the if statement is because you cannot execute the undo command without doing anything. So, you need to do something first, and only then you can undo.
So, the error is caused, which is shown from the terminal pic is because, by you entering 'undo' as the first command, and since it didn't find any if statement, it appended the string 'undo' to rl (Which is not what we want).
Solution:
First, don't enter 'undo' as the first command in the program. (Although, it's the most easy fix but not recommended practice.)
Second, Shift the ag=input(">>") command directly under two print statements and change the code in the if statement as follows:
if ag=='undo':
if len(rl) > 0: # Condition to check if rl is not empty
print(rl.pop(-1))
break # Use continue instead?
I changed list.pop(-1 to rl.pop(-1) as recommended by #oluwafemi-sule
Advice/Recommendation: Usually, when we undo things we don't exit the program/loop. We generally don't break the loop. We skip the rest of the execution, so I fell you should use continue instead of break in the above code.
2
Suppose someone entered 'exit' instead of the required argument, hence the program performs the required steps before closing. Now, we want the program to terminate, and here in your code there is no termination statement.
If we don't terminate the program, 'exit' will be appended to the rl and again it'll cause an error. Hence, your other if statement should have a break statement. That would break the loop and hence complete the execution.
if ag=='exit':
file = open(f'image{ra.randint(0,100001)}.imag')
for aa in rl:
file.write(f'{aa}\n')
file.close()
break

What is the difference between running a code through the "console" and running it regularly?

I'm a beginner at Python and coding in general, and I've been primarily using the trinket interpreter to work out some of my scripts. I was just trying to get used to defining a function with if and elif lines alongside the return command.
The code I'm trying to run is a pretty simple one, but when I run it regularly nothing shows up. However, when I run it through the console it
comes out fine. What am I doing wrong?
def the_line(text):
if text == ("just a boy"):
phrase = ("I fly alone")
elif text == "syndrome":
phrase = ("darn you syndrome")
return phrase
the_line("just a boy")
The first picture is what happens when I run it regularly and the second is through the console.
In the console, when you run a statement but don't assign it to anything, the shell will print the resulting object. You call the function but don't save it in a variable, so it is displayed. The "console" in your IDE is also called a Read, Evaluate and Print Loop (REPL).
But your code really just discarded that return value. That's what you see in the first case, the returned object wasn't assigned to anything and the object was deleted. You could assign it to a variable and print, if you want to see it.
def the_line(text):
if text == ("just a boy"):
phrase = ("I fly alone")
elif text == "syndrome":
phrase = ("darn you syndrome")
return phrase
foo = the_line("just a boy")
print(foo)
(As a side note, 4 spaces for indents please. We are not running out of spaces).
This is very clearly explained in Think Python's section 2.4. It has everything to do with the Read-Eval-Print-Loop (REPL) concept.
Briefly, the console is a REPL, so you see the output because it Prints what it Evaluated after Reading something (and then it prompts again for you to input something, that's the loop part). When you run the way you call "regularly", you are in what is called "script mode" (as in Think Python). Script mode simply Reads and Evaluates, there is not the Print-Loop part. A REPL is also called "interactive mode".
One could say that a REPL is very useful for prototyping and testing things out, but script mode is more useful for automation.
What you need to see the output would be like
print(the_line("just a boy"))
for line number 9.

Is it possible to run indented blocks using exec()?

Using the exec() python command, is it possible to run indented blocks of code (Like if/else statements or try/except). For example:
name = input("Enter name: ")
if name == "Bob":
print("Hi bob")
else:
print("Hi user")
At the moment I am using this to run the code:
code_list = []
while True:
code = input("Enter code or type end: ")
if code == "end":
break
else:
code_list.append(code)
for code_piece in code_list:
exec(code_piece)
Also I know that this isn't very "Pythonic" or "Good practise" to let the user input their own code but it will be useful in other parts of my code.
The problem here isn't the indentation. The problem is that you're trying to exec the lines of a compound statement one by one. Python can't make sense of a compound statement without the whole thing.
exec the whole input as a single unit:
exec('\n'.join(code_list))
From exec() documentation:
This function supports dynamic execution of Python code. object must be either a string or a code object. If it is a string, the string is parsed as a suite of Python statements which is then executed ...
Thus, you can do things like
exec("a=2\nb=3")
exec("if a==2:\n\tprint(a)\nelse:\tprint(b)")
You just need to follow the right syntax and indentation.
Another way of formatting code within an exec() function is to use triple quotes, which makes it easy to see what the code looks like.
code = """ # Opening quotes
for i in range(0, 10): # Code line 1
print(i) # Code line 2
""" # Closing quotes
exec(code)
This would maybe not work if you're asking the user to input the code, but it's a trick that may come in handy.

Indention Errors on Python IDLE

I'm just following the basic's of python and have been using IDLE as I find it handy to experiment scripts in real-time.
While I can run this script with no issues as a file I just cannot include the last print statement in IDLE!. I have tried an indentation, 4 spaces, no indentation's. Please explain what I'm doing wrong.
while True:
print ('Who are you?')
name = input()
if name != 'Joe':
continue
print('Hello, Joe. What is the password? (It is a fish.)')
password = input()
if password == 'swordfish':
break
print('value')
SyntaxError: invalid syntax
You can type one statement at a time. The while loop considered one with the loop itself, and since the loop is a code block everything in it is okay.
The print at the end however is a new command. You have to run the while loop first and type the print after in the interpreter.
You can't paste more than one statement at a time into IDLE. The problem has nothing to do with indentation. The while loop constitutes one compound statement and the final print another.
The following also has issues when you try to paste at once into IDLE:
print('A')
print('B')
The fact that this has a problem shows even more clearly that the issue ins't one of indentation.
You have an undentation error in line 10, then you need just to add an espace
while True:
print ('Who are you?')
name = input()
if name != 'Joe':
continue
print('Hello, Joe. What is the password? (It is a fish.)')
password = input()
if password == 'swordfish':
break
print('value')
As others have kindly pointed out python IDLE only allows one block of code to be executed at a time. In this instance the while loop is a 'block'. The last print statement is outside this block thus it cannot be executed.

why isn't input() behaving right?

I've the following python 2.7.3 code which I am submitting to codechef online programming contest:
case = input()
for i in xrange(0, case):
try:
l = [elem for elem in raw_input().split()]
res = int(l[0][::-1]) + int(l[1][::-1])
print int(str(res)[::-1])
except:
break
This works on my computer, even when I use input redirection and use a in.txt file for input, still it works.
But the problem is when i submit it for evaluation, I get an exception and that exception gets removed when I use raw_input for getting the value of case
case = int(raw_input())
My in.txt file is as follows:
1
23 45
My problem is that its working on my computer perfectly, what is it that the online contest site feeding at the 1st line that an exception is being raised, and further it gets rectified when I use raw_input.
Shouldn't input() also work when my 1st line is always an integer?
Most likely, the site that you're submitting the code to disables the input command. This is sometimes done as part of "sandboxing", to prevent you from running arbitrary code on their machine. E.g., they wouldn't want to let you run a script that deletes all files on their disk.
The input command is more-or-less equivalent to running eval(raw_input()), and eval can be used to do just about anything.
You say you get an exception. Exactly what kind of exception, and what is the exception message?

Categories