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

Categories

0 votes
267 views
in Technique[技术] by (71.8m points)

Error when making functions in my Python in python

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

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

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...