繁体   English   中英

写一个 function 需要 2 个字符串 arguments

[英]write a function that takes 2 string arguments

我是一个初学者,所以如果你被它的简单冒犯了,请跳过这个。

我不知道如何编写一个 function ,它需要两个 arguments (名称和课程)并打印:欢迎“名称”到“课程”训练营。

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

我希望能够打印欢迎 Stacie 参加 python 训练营!

请尝试以下类似的方法。

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

greeting('Stacie', 'python')

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

def greeting(name, course):
    print (f"Welcome {name} to the {course}")

greeting("Jhon", "Python for Beginners")
# > Welcome Jhon to the Python for Beginners

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

您声明的 function arguments 需要是变量,而不是实际

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

注意你的引用是如何完全错误的。 人类可读文本周围的单引号 go 和周围没有引号的内容必须是有效的 Python 符号或表达式。

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

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

调用greeting()将产生

welcome John to the Python 101 course

当然也可以用 arguments 来调用它

greeting('Slartibartfast', 'Pan Galactic Gargle Blaster course')

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

welcome Slartibartfast to the Pan Galactic Gargle Blaster course

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM