[英]I need help to print this pattern in python, i have given my approach but couldnt figure out pls support
My Approach Code:我的方法代码:
n=int(input(":"))
for i in range(n+1):
for j in range(1,i+1):
print(","+str(j), end="")
print()
for i in range(n, 1, -1):
for j in range(1, i):
print(","+str(j), end="")
print()
But Couldnt get required pattern pls help但无法获得所需的模式请帮助
You can use "," as the print separator instead of concatenating the comma as long as you print all numbers in one call to print (which you can do with unpacking):您可以使用“,”作为打印分隔符,而不是连接逗号,只要您在一次打印调用中打印所有数字(您可以通过拆包来完成):
n = 5
for d in range(1-n,n):
print(*range(1,n-abs(d)+1),sep=",")
1
1,2
1,2,3
1,2,3,4
1,2,3,4,5
1,2,3,4
1,2,3
1,2
1
If you want to adjust your code, you could use a variable for the comma and only have it contain an actual comma from the second number onward:如果你想调整你的代码,你可以为逗号使用一个变量,并且只让它包含从第二个数字开始的实际逗号:
n=int(input(":"))
for i in range(n+1):
comma = ""
for j in range(1,i+1):
print(comma+str(j), end="")
comma = ","
print()
for i in range(n, 1, -1):
comma = ""
for j in range(1, i):
print(comma+str(j), end="")
comma = ","
print()
Note that you are printing an extra blank line at the beginning.请注意,您在开头打印了一个额外的空白行。 If that is not your intention, you should make the first loop use range(1,n+1)
如果这不是你的意图,你应该让第一个循环使用range(1,n+1)
Another way to fix your code would be to systematically print a comma as the ending character and use the final print for the last number on each line:修复代码的另一种方法是系统地打印逗号作为结束字符,并将最终打印用于每行的最后一个数字:
n=int(input(":"))
for i in range(1,n+1):
for j in range(1,i):
print(j, end=",")
print(i)
for i in range(n-1, 0, -1):
for j in range(1, i):
print(j, end=",")
print(i)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.