这个语法错误的原因是什么

时间:2013-09-21 03:57:43

标签: python

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

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

2 个答案:

答案 0 :(得分:5)

您的脚本会返回语法错误,因为您无法通过str(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')

输出:

  

您好。我的名字叫凯文。我转到威斯康星大学。

请注意:,如评论here中所述,您无法使用:

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)

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