[英]python nested loop output art and reverseal
I am trying to write a program that looks something like this if, say, the input number was 6, or something like that the output should look like this: 我正在尝试编写一个看起来像这样的程序,例如,输入数字为6,或者输出看起来像这样:
*
**
***
****
*****
******
*****
****
***
**
*
but when I do it like I was told, this way specifically because this is what a classmate told me to do. 但是当我像被告知时那样做时,这种方式特别是因为这是同学告诉我的。 :
:
n = int(input("Enter a value for n: "))
for i in range(1, n + 1):
for j in range(n):
if n - j > i:
print(" ", end = " ")
else:
print("*", end = " ")
print("")
for i in range(1, n):
for j in range(n):
if n - j < i:
print(" ", end = " ")
else:
print("*", end = " ")
print("")
I get: 我得到:
*
**
***
****
*****
******
*****
****
***
**
*
What am I doing wrong? 我究竟做错了什么? Please tell me how to get it to correctly line up, I'd really appreciate it if someone could help me with this so I can learn to do this on my own, please assist me...
请告诉我如何正确排列,如果有人可以帮助我,我将不胜感激,以便我可以独自学习,请帮助我...
Your loops are a bit overcomplicated, so I've simplified somewhat: 您的循环有点复杂,因此我做了一些简化:
n = int(input("Enter a value for n: "))
for x in range(n):
out = ''
for y in range(n-x):
out = out +' '
for y in range(x):
out = out +'*'
print(out)
for x in range(n):
out = ''
for y in range(x):
out = out +' '
for y in range(n-x):
out = out +'*'
print(out)
Enjoy! 请享用!
If your assignment requires you to write the code exactly as you posted, Austin Kootz answer is the way to go. 如果您的作业要求您完全按照发布的代码来编写代码,那么Austin Kootz的答案就是正确的选择。
However, a more simplifed way of doing this is using ljust
但是,更简单的方法是使用
ljust
n = 6
for x in range(n - 1, 0, -1):
print ''.ljust(x, ' ') + '*'.ljust(n - x, '*')
for x in range(n):
print ''.ljust(x, ' ') + '*'.ljust(n - x, '*')
What you want in the second set of loops is to take the row number (counting from 1) and print that many spaces (" "), and then print asterisks ("*") for the rest of the row. 在第二组循环中,您要获取行号(从1开始计数)并打印那么多的空格(“”),然后为该行的其余部分打印星号(“ *”)。 So if i is the row number and j the column number (and indexing starts from 0), you should print " " while j < i + 1 and "*" otherwise.
因此,如果i是行号,j是列号(并且索引从0开始),则应打印“”,而j <i + 1,否则打印“ *”。 This gives:
这给出:
# The top part of the pyramid
for i in range(1, n + 1):
for j in range(n):
if n - j > i:
print(" ", end = " ")
else:
print("*", end = " ")
print("")
# The bottom half of the pyramid
for i in range(n):
for j in range(n):
# Print spaces in the beginning of the row
# (while the column number is less than the row number)
if j < i + 1:
print(" ", end = " ")
# Print asterisks for the rest of the row
else:
print("*", end = " ")
print("")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.