Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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
")
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)
>>> 
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
271 views
Welcome To Ask or Share your Answers For Others

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...