【问题标题】:basic strings and variables python基本字符串和变量python
【发布时间】:2013-09-03 20:55:01
【问题描述】:

编写一个名为 Introduction(name, school) 的函数,该函数将名称(作为字符串)和学校作为输入,并返回以下文本:“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

【问题讨论】:

    标签: python string variables


    【解决方案1】:
    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")
    

    【讨论】:

    • 我还没关注你。如您所知,我是编程初学者。比什么代码更有效?它仍然出现括号错误。
    • 我的答案现在包括整个代码(更新)作为最后一部分。复制粘贴它,它应该运行。您可以将“Brian”更改为“ryan”,将“MIT”更改为“iowa”。
    • def introduction(name,school): 部分创建了一个函数,但实际上并不执行它。 print introduction("Brian","MIT") 部分实际上执行具有值“Brian”和“MIT”的函数。
    • @user2744489 太棒了!很高兴我能帮上忙。如果有人为您工作,请随时 accept an answer
    【解决方案2】:

    函数的定义应该使用变量而不是字符串。当您声明“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("Sulley", "MU")
    Hello.  My name is Sulley.  I have always wanted to go to TheMU.
    >>>
    

    【讨论】:

    • 我确实这样做了,但出现了错误:introduction(ryan, iowa) Traceback (most recent call last): File "", line 1, in NameError: name ' ryan' 没有定义
    【解决方案3】:

    函数的参数是变量名,而不是字符串常量,因此不应该用引号引起来。此外,字符串常量周围的括号和 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 提供给函数。

    【讨论】:

    • 它仍然出现错误,提示名称未定义
    猜你喜欢
    • 1970-01-01
    • 2019-01-08
    • 2017-02-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-12-12
    相关资源
    最近更新 更多