-2

I have made a code. It works like we are running the original python. It uses eval and exec. When I try to make a function or any if statement in it ,it don't works. Here is the code:

print("Python\n")
while True:
    command =input(">>> ")
    if command == "quit()":break
    try:
        try:
            eval(command)
        except:
            exec(command)
    except Exception as err:
        print("Exception: "+str(err))

Running:

Python

>>> a = input("Enter your name: ")
Enter your name: abc
>>> print(a)
abc
>>> if True:
Exception: unexpected EOF while parsing (<string>, line 1)
>>> if True:print(a);if a == "abc":print("Great Abc")
Exception: invalid syntax (<string>, line 1)
>>> 
7
  • 1
    Your question is not clear and more over please mention the relation between the two code snapshots you have posted Commented Sep 1, 2018 at 17:43
  • if True: fails because something needs to come after the :. You can put pass there. Commented Sep 1, 2018 at 17:44
  • 1
    Why are you trying to mimic the REPL behavior? Commented Sep 1, 2018 at 17:46
  • @Carcigenicate I tried to press enter to type my code within it. Commented Sep 1, 2018 at 17:46
  • @mmmmmmmm eval can't know that. You can try (if True and then press enter, but I doubt it will work. Again, why are you trying to reinvent REPL? Commented Sep 1, 2018 at 17:48

2 Answers 2

1

Since you are only processing one line at a time the python interpreter throws an error if you only write if True:. In the normal interpreter this would trigger a multi-line edit and only start executing when you make an empty line.

If you on the other hand put something after the if-statement it would work (e.g.if True: print("true")) But you cannot chain if-statements after one another like you try to do. You can however chain normal statements like if True:print("first line");print("second line").

The same problem goes for functions. They need to have a statement following the definition before the can be interpreted and normally you would be allowed to type that definition before the function gets read.

You could change your code to allow for this behaviour so that if a line ends with : you should continue to read the input and only execute it after an empty line has been given as input.

Sign up to request clarification or add additional context in comments.

1 Comment

@mmmmmmmm which example do you mean?
0

Eval fuction evalutes one line code, if statement demands minimal 2 lines(with indentation). Try lambda expression

lambda x: True if a == True else False

1 Comment

Not completely true. A if statement can have a statement follow on the same line. See my answer for more detail or try it out for yourself.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.