gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 08:13:04 25 4
gpt4 key购买 nike

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

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)

关于python - 这个语法错误的原因是什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18928724/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com