在 Python 中仅使用 While 循环打印星号箭头
Print asterisk arrow using only While loops in Python
我正在尝试用星号创建一个箭头,其中列数由用户输入。是的,我确实知道如何使用 for 循环来完成此操作:
columns = int(input("How many columns? "))
while columns <= 0:
print ("Invalid entry, try again!")
columns = int(input("How many columns? "))
x = 1
for x in range(1, columns):
for x in range(x):
print(" ", end="")
print("*")
for x in range(columns,0,-1):
for x in range(x):
print(" ", end="")
print("*")
#output looks like
"""
How many columns? 3
*
*
*
*
*
"""
但是我的问题是,如何仅使用 while 循环实现相同的结果?
谢谢
编辑:我打算 post 到目前为止我试图自己解决这个问题,但现在没有用了!
谢谢大家有效的不同答案!非常感激!
应该这样做:
columns = int(input("How many columns? "))
while columns <= 0:
print ("Invalid entry, try again!")
columns = int(input("How many columns? "))
x = 1
while x < columns:
y = 0
while y < x:
print(" ", end="")
y += 1
print("*")
x += 1
x = columns
while x > 0:
y = 0
while y < x:
print(" ", end="")
y += 1
print("*")
x -= 1
首先,还是用函数好。如果您知道 character*number
returns character
连接了 number
次,就更容易了。
示例:
'*'*10
returns
'**********'
因此您使用 while 的程序将遵循相同的逻辑。
def print_arrow(k):
i = 0
while(i < k-1):
print(i*' ' + '*')
i +=1
while(i >= 0):
print(i*' ' + '*')
i -= 1
第一个 while 打印上半部分,最后一个使用 i = k-1
的事实,所以只需按相反的顺序执行即可。
示例:
print_arrow(3)
returns
*
*
*
*
*
只是为了好玩,这里有一个不使用索引循环的版本。
def print_arrow(n):
a = '*'.ljust(n + 1)
while a[-1] != '*':
print(a)
a = a[-1] + a[:-1]
a = a[1:]
while a[0] != '*':
a = a[1:] + a[0]
print(a)
# Test
print_arrow(4)
输出
*
*
*
*
*
*
*
我正在尝试用星号创建一个箭头,其中列数由用户输入。是的,我确实知道如何使用 for 循环来完成此操作:
columns = int(input("How many columns? "))
while columns <= 0:
print ("Invalid entry, try again!")
columns = int(input("How many columns? "))
x = 1
for x in range(1, columns):
for x in range(x):
print(" ", end="")
print("*")
for x in range(columns,0,-1):
for x in range(x):
print(" ", end="")
print("*")
#output looks like
"""
How many columns? 3
*
*
*
*
*
"""
但是我的问题是,如何仅使用 while 循环实现相同的结果?
谢谢
编辑:我打算 post 到目前为止我试图自己解决这个问题,但现在没有用了! 谢谢大家有效的不同答案!非常感激!
应该这样做:
columns = int(input("How many columns? "))
while columns <= 0:
print ("Invalid entry, try again!")
columns = int(input("How many columns? "))
x = 1
while x < columns:
y = 0
while y < x:
print(" ", end="")
y += 1
print("*")
x += 1
x = columns
while x > 0:
y = 0
while y < x:
print(" ", end="")
y += 1
print("*")
x -= 1
首先,还是用函数好。如果您知道 character*number
returns character
连接了 number
次,就更容易了。
示例:
'*'*10
returns
'**********'
因此您使用 while 的程序将遵循相同的逻辑。
def print_arrow(k):
i = 0
while(i < k-1):
print(i*' ' + '*')
i +=1
while(i >= 0):
print(i*' ' + '*')
i -= 1
第一个 while 打印上半部分,最后一个使用 i = k-1
的事实,所以只需按相反的顺序执行即可。
示例:
print_arrow(3)
returns
*
*
*
*
*
只是为了好玩,这里有一个不使用索引循环的版本。
def print_arrow(n):
a = '*'.ljust(n + 1)
while a[-1] != '*':
print(a)
a = a[-1] + a[:-1]
a = a[1:]
while a[0] != '*':
a = a[1:] + a[0]
print(a)
# Test
print_arrow(4)
输出
*
*
*
*
*
*
*