简体   繁体   English

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

[英]write a function that takes 2 string arguments

I'm a total beginner so please skip this one if you are offended by how simple it is.我是一个初学者,所以如果你被它的简单冒犯了,请跳过这个。

I can't figure out how to write a function which takes two arguments (name and course) and prints: Welcome "name" to the "course" bootcamp.我不知道如何编写一个 function ,它需要两个 arguments (名称和课程)并打印:欢迎“名称”到“课程”训练营。

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

I want to be able to print Welcome Stacie to the python bootcamp!我希望能够打印欢迎 Stacie 参加 python 训练营!

Pls try something like below.请尝试以下类似的方法。

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

greeting('Stacie', 'python')

if you still getting any error pls share screenshot of error.如果您仍然收到任何错误,请分享错误截图。

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

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

The function takes two variables, the variables are not strings, so they won't have quote marks. function 有两个变量,变量不是字符串,所以不会有引号。 In the print statement, f"<text>" is used in this case to print variables in the string with the help of {} .在 print 语句中, f"<text>"在这种情况下用于在{}的帮助下打印字符串中的变量。 So when you type in the string {name} it will take the name from the variable itself.因此,当您输入字符串{name}时,它将从变量本身中获取名称。

The function arguments you declare need to be variables , not actual values .您声明的 function arguments 需要是变量,而不是实际

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

Notice how you had the quoting diametrically wrong.注意你的引用是如何完全错误的。 The single quotes go around pieces of human-readable text and the stuff without quotes around it needs to be a valid Python symbol or expression.人类可读文本周围的单引号 go 和周围没有引号的内容必须是有效的 Python 符号或表达式。

If you want to supply a default value, you can do that.如果你想提供一个默认值,你可以这样做。

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

Calling greeting() will produce调用greeting()将产生

welcome John to the Python 101 course

and of course calling it with arguments like当然也可以用 arguments 来调用它

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

will fill the variables with the values you passed as arguments:将使用您作为 arguments 传递的值填充变量:

welcome Slartibartfast to the Pan Galactic Gargle Blaster course

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

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