1

我想知道为什么我的代码不起作用。不是字符串吗?我的经期会影响我的代码吗?引用某处?

def intro(name,school):
    return "Hello. My name is" + str(name). + "I go to" + str(school).
4

2 回答 2

5

您的脚本返回语法错误,因为您无法将句号添加到字符串 bystr(name).但它也必须作为字符串添加str(name) + "."

def intro(name,school):
    return "Hello. My name is " + str(name) + "." + " I go to " + str(school) + "."

print intro('kevin','university of wisconsin')

这将打印(注意我添加的额外空格,"I go to"替换为" I go to "以便输出更具可读性)

你好。我的名字叫凯文。我去了威斯康星大学。

但是您可以使用该format()方法来克服字符串添加的复杂性:

def intro(name,school):
    return "Hello. My name is {0}. I goto {1}.".format(name,school)

print intro('kevin','university of wisconsin')

输出:

你好。我的名字叫凯文。我去了威斯康星大学。

请注意:如评论中所述,不能使用:

print intro(kevin,university of wisconsin)因为它会带来一个Syntax Error为什么?,因为变量不能有空格,字符串必须有引号或者python认为kevin是一个变量,但你总是欢迎这样做:

name = 'kevin'
school = 'university of wisconsin'

def intro(name,school):
    return "Hello. My name is " + str(name) + "." + " I go to " + str(school) + "."
    #return "Hello. My name is {0}. I goto {1}.".format(name,school)

print intro(name,school)
于 2013-09-21T07:51:52.120 回答
1

试试翻译..

Python 2.7.2 (default, Oct 11 2012, 20:14:37)
[GCC 4.2.1 Compatible Apple Clang 4.0 (tags/Apple/clang-418.0.60)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> def intro(name,school): return "Hello. My name is" + str(name). + "I go to" + str(school).
  File "<stdin>", line 1
    def intro(name,school): return "Hello. My name is" + str(name). + "I go to" + str(school).
                                                                    ^
SyntaxError: invalid syntax
>>>

它为您提供了一个很好的线索,即语法是错误的str(name).。果然是。同样的问题@str(school).将其更改为:

def intro(name,school): 
    return "Hello. My name is" + str(name) + ". I go to" + str(school) + "."
于 2013-09-21T04:01:13.403 回答