Error when making functions in my Python in python

谁都会走 提交于 2019-12-26 16:02:36

问题


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)
>>> 

回答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.




回答2:


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


来源:https://stackoverflow.com/questions/52130639/error-when-making-functions-in-my-python-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!