基本字符串和变量python

时间:2013-09-03 20:55:01

标签: python string variables

编写一个名为简介(名称,学校)的函数,该函数将名称(作为字符串)和学校作为输入,并返回以下文本:“Hello。我的名字是名字。我一直想上学。“

这是我的代码

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

3 个答案:

答案 0 :(得分: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")

答案 1 :(得分:2)

函数的定义应该采用变量而不是字符串。当你宣布“引言(”名称“,”学校“):”,这就是你在做什么。试试这个:

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

答案 2 :(得分: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