在python中的Python中制作函数时出错 [英] Error when making functions in my Python in python

查看:107
本文介绍了在python中的Python中制作函数时出错的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经编写了代码。就像我们运行原始的python一样。它使用 eval exec 。当我尝试制作函数或其中的任何 if 语句时,它不起作用。下面是代码:

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

运行:

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


推荐答案

由于您一次只处理一行如果只写如果为True:,则python解释器将引发错误。在普通的解释器中,这将触发多行编辑,并且仅在您创建空行时才开始执行。

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-之后语句将起作用(例如, if True:print( true)),但是您不能像您尝试的那样将if语句一个接一个地链接。但是,您可以链接普通语句,例如 if True:print(第一行); print(第二行)

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.

这篇关于在python中的Python中制作函数时出错的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆