Skip to main content
 首页 » 编程设计

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

2025年05月04日16mayingbao

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

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

请您参考如下方法:

您的脚本返回一个语法错误,因为您不能通过str(name). 向字符串添加句号,但它也必须作为字符串添加str(名称) + "."

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 " 以便输出更多可读):

Hello. My name is kevin. I goto university of wisconsin.

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

def intro(name,school): 
    return "Hello. My name is {0}. I goto {1}.".format(name,school) 
 
print intro('kevin','university of wisconsin') 

输出:

Hello. My name is kevin. I goto university of wisconsin.

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

print intro(kevin,university of wisconsin) 因为它会带来语法错误,为什么?,因为变量不能有空格,字符串必须有引号或者 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)