[英]Is this a right code to print x for n times?
Is this a right way to write a function that prints x for n times?这是编写将 x 打印 n 次的函数的正确方法吗? My code:我的代码:
def funz(x,n):
f = (x+"\n")*(n-1) + x
print(f)
You can use sep
argument of print
:您可以使用print
sep
参数:
def funz(x, n):
print(*[x]*n, sep='\n')
funz('a', 3)
# Output:
a
a
a
Step by step:一步步:
>>> print([x])
['a']
>>> print([x]*n)
['a', 'a', 'a']
>>> print(*[x]*n)
a a a
>>> print(*[x]*n, sep='\n')
a
a
a
for
loops are useful for tasks like this. for
循环对于这样的任务很有用。 In this case you can do this:在这种情况下,您可以这样做:
n = int(input())
def funz(x, n):
for _ in range(n):
print(x)
funz('x',n)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.