如何在Python中打印多个参数?
参数是函数时在函数内传递的值。它们是包含数据或代码的独立项或变量。在调用期间,每个参数始终分配给函数定义中的参数。
示例:简单参数
Python3
def GFG(name, num):
print("Hello from ", name + ', ' + num)
GFG("geeks for geeks", "25")
Python3
def GFG(name, num="25"):
print("Hello from", name + ', ' + num)
GFG("gfg")
GFG("gfg", "26")
Python3
def GFG(name, num):
print("hello from %s , %s" % (name, num))
GFG("gfg", "25")
Python3
def GFG(name, num):
print("hello from %(n)s , %(s)s" % {'n': name, 's': num})
GFG("gfg", "25")
Python3
def GFG(name, num):
print("hello from {0} , {1}".format(name, num))
GFG("gfg", "25")
Python3
def GFG(name, num):
print("hello from {n} , {r}".format(n=name, r=num))
GFG("gfg", "25")
Python3
def GFG(name, num):
print("hello from " + str(name) + " , " + str(num))
GFG("gfg", "25")
Python3
def GFG(name, num):
print(f'hello from {name} , {num}')
GFG("gfg", "25")
Python3
def GFG(*args):
for info in args:
print(info)
GFG(["Hello from", "geeks", 25], ["Hello", "gfg", 26])
Python3
def GFG(**kwargs):
for key, value in kwargs.items():
print(key, value)
GFG(name="geeks", n="- 25")
GFG(name="best", n="- 26")
输出:
Hello from geeks for geeks, 25
不带参数或只有一个参数调用上述代码会产生错误。
变量函数参数
如上所示,函数有固定数量的参数。在Python中,还有其他方法可以定义可以采用可变数量参数的函数。
下面讨论不同的形式:
- Python默认参数:函数参数在Python中可以有默认值。我们使用赋值运算符(=) 为参数提供默认值。
例子:
蟒蛇3
def GFG(name, num="25"):
print("Hello from", name + ', ' + num)
GFG("gfg")
GFG("gfg", "26")
输出:
Hello from gfg, 25
Hello from gfg, 26
- 将其作为元组传递
蟒蛇3
def GFG(name, num):
print("hello from %s , %s" % (name, num))
GFG("gfg", "25")
输出:
hello from gfg , 25
- 将其作为字典传递
蟒蛇3
def GFG(name, num):
print("hello from %(n)s , %(s)s" % {'n': name, 's': num})
GFG("gfg", "25")
输出:
hello from gfg , 25
- 使用带有数字的新型字符串格式
蟒蛇3
def GFG(name, num):
print("hello from {0} , {1}".format(name, num))
GFG("gfg", "25")
输出:
hello from gfg , 25
- 使用带有显式名称的新型字符串格式
蟒蛇3
def GFG(name, num):
print("hello from {n} , {r}".format(n=name, r=num))
GFG("gfg", "25")
输出:
hello from gfg , 25
- 连接字符串
蟒蛇3
def GFG(name, num):
print("hello from " + str(name) + " , " + str(num))
GFG("gfg", "25")
输出:
hello from gfg , 25
- 在Python 3.6 中使用新的 f 字符串格式
蟒蛇3
def GFG(name, num):
print(f'hello from {name} , {num}')
GFG("gfg", "25")
输出:
hello from gfg , 25
- 使用 *args
蟒蛇3
def GFG(*args):
for info in args:
print(info)
GFG(["Hello from", "geeks", 25], ["Hello", "gfg", 26])
输出:
[‘Hello from’, ‘geeks’, 25]
[‘Hello’, ‘gfg’, 26]
- 使用 **kwargs
蟒蛇3
def GFG(**kwargs):
for key, value in kwargs.items():
print(key, value)
GFG(name="geeks", n="- 25")
GFG(name="best", n="- 26")
输出:
name geeks
n – 25
name best
n – 26