Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/322.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 使用exec函数的语法无效_Python - Fatal编程技术网

Python 使用exec函数的语法无效

Python 使用exec函数的语法无效,python,Python,我的主管不在工作 这是我的密码: b = ('''def peter: if nname == "peter": return "you are a cool boy" else: return "you are a not cool boy" def weight: if weight > 100: return "you weight too much" else: retu

我的主管不在工作

这是我的密码:

b = ('''def peter:
if nname == "peter":
    return "you are a cool boy"
else:
    return "you are a not cool boy"
def weight:
if weight > 100:
    return "you weight too much"
else:
    return
     "you weight good"
'''
exec(b)

当我运行它时,它会突出显示exec中的e并显示“无效语法”

您在开始处有一个未关闭的括号

此外,您的def语法不正确,您必须非常仔细地准备它

试试这个:

b ='''
def peter():
    if nname == "peter":
        return "you are a cool boy"
    else:
        return "you are a not cool boy"
def weight():
    if weight > 100:
        return "you weight too much"
    else:
        return "you weight good"
'''
exec(b)
你的语法错了

b ='''
def peter():
    if nname == "peter":
        return "you are a cool boy"
    else:
        return "you are a not cool boy"
def weight():
    if weight > 100:
        return "you weight too much"
    else:
        return "you weight good"
'''
exec(b)

我希望在创建这两个函数之前,您已经创建了一个名为nname和weight的变量。如果没有,那么首先创建它们

def peter(nname):# You also need to pass the variable nname in function Peter
    if nname == "peter":
        return "you are a cool boy"
    else:
        return "you are a not cool boy"
def weight(weight):# You also need to pass the variable weight in function weight.
   if weight > 100:
       return "you weight too much"
   else:
       return "you weight good"
weight(weight)
peter(nname)# Calling functions
代码应该是这样的。要在Python中定义函数,使用以下语法

def func_name(variable1, variable2):#Creating function
     #Your code
func_name(variable1, variable2)#Calling functions
您可以了解有关Python函数的更多信息:

它可以工作,但当我运行它时,它不会打印anything@Goose您所做的只是定义两个函数,从不调用它们,因此exec不会打印任何内容call@GooseHjonk您必须调用函数,然后它才会运行。我建议您首先学习python的基础知识及其工作原理。