2

编写一个名为 Introduction(name, school) 的函数,它接受一个名称(作为一个字符串)和一个学校作为输入,并返回以下文本:“你好。我的名字是名字。我一直想去上学。”</p>

这是我的代码

def introduction("name","school"):
    return ("Hello.  My name is ") + str(name) + (".  I have always wanted to go to The") + str(school) + (".")

我收到此错误:

Traceback (most recent call last):
  File "None", line 5, in <module>
invalid syntax: None, line 5, pos 23
4

3 回答 3

7
def introduction("name","school"):

应该

def introduction(name,school):

您作为函数的形式参数提供的名称本质上是实际参数的值被分配给的变量。包含文字值(如字符串)没有多大意义。

当您调用或调用该函数时,您可以在其中提供一个真实值(如文字字符串)

def introduction(name,school):
    return ("Hello.  My name is ") + str(name) + (".  I have always wanted to go to The") + str(school) + (".")

print introduction("Brian","MIT")
于 2013-09-03T20:56:16.507 回答
2

函数的定义应该采用变量而不是字符串。当您声明“introduction("name","school"):"时,这就是您正在做的事情。尝试这个:

def introduction(name, school):

这里:

>>> def introduction(name, school):
...     return ("Hello.  My name is ") + str(name) + (".  I have always wanted to go to The") + str(school) + (".")
...
>>> print introduction("Sulley", "MU")
Hello.  My name is Sulley.  I have always wanted to go to TheMU.
>>>
于 2013-09-03T20:57:17.930 回答
0

函数的参数是变量名,而不是字符串常量,因此不应该用引号引起来。此外,字符串常量周围的括号和 return 语句中参数到字符串的转换不是必需的。

def introduction (name,school):
    return "Hello. My name is " + name + ". I have always wanted to go to " + school + "."

现在,如果你调用函数,那么你调用函数print(introduction("Seth","a really good steak place")) # Strange name for a school...的参数字符串常量,所以你应该把它们放在引号中。

当然,如果参数不是常量,则不适用...

myname = "Seth"
myschool = "a really good steak place" # Strange name for a school...
print(introduction(myname,myschool))

...因此,您改为提供变量mynamemyschool函数。

于 2013-09-03T21:05:11.003 回答