【问题标题】:write a function that takes 2 string arguments编写一个接受 2 个字符串参数的函数
【发布时间】:2019-10-01 04:54:48
【问题描述】:

我是一个初学者,所以如果你对它的简单性感到不快,请跳过这个。

我不知道如何编写一个接受两个参数(名称和课程)并打印的函数: Welcome "name" to the "course" bootcamp。

def greeting('name', 'course'):
    print (welcome,'name', to, the, 'course')

我希望能够打印 Welcome Stacie to the python bootcamp!

【问题讨论】:

  • 欢迎来到 SO!变量包含字符串,而不是字符串:删除变量周围的所有引号并将它们放在字符串文字周围,如"welcome""to""the"

标签: python string function arguments


【解决方案1】:

请尝试以下方法。

def greeting(name, course):
    print ('welcome' + name + 'to' + 'the' + course)

greeting('Stacie', 'python')

如果您仍然收到任何错误,请分享错误截图。

【讨论】:

【解决方案2】:

您声明的函数参数需要是变量,而不是实际的

def greeting(name, course):
    print ('welcome', name, 'to the', course)

请注意您的引用是如何完全错误的。单引号围绕着人类可读的文本,而没有引号的东西必须是有效的 Python 符号或表达式。

如果你想提供一个默认值,你可以这样做。

def greeting(name='John', course='Python 101 course'):
    print ('welcome', name, 'to the', course)

调用greeting()会产生

welcome John to the Python 101 course

当然还有像

这样的参数调用它
greeting('Slartibartfast', 'Pan Galactic Gargle Blaster course')

将使用您作为参数传递的值填充变量:

welcome Slartibartfast to the Pan Galactic Gargle Blaster course

【讨论】:

    【解决方案3】:
    def greeting(name, course):
        print (f"Welcome {name} to the {course}")
    
    greeting("Jhon", "Python for Beginners")
    # > Welcome Jhon to the Python for Beginners
    

    该函数有两个变量,变量不是字符串,所以它们不会有引号。在 print 语句中,f"<text>" 在这种情况下用于在 {} 的帮助下打印字符串中的变量。因此,当您输入字符串 {name} 时,它将从变量本身获取名称。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-11-15
      • 2022-12-04
      • 1970-01-01
      • 2021-03-07
      • 2014-12-13
      • 1970-01-01
      • 1970-01-01
      • 2021-02-16
      相关资源
      最近更新 更多