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的基础知识及其工作原理。