簡體   English   中英

在 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 循環來實現相同的結果?

謝謝

編輯:我打算發布迄今為止我試圖自己解決的問題,但現在沒有用了! 感謝大家高效的不同答案! 非常感激!

只是為了好玩,這里有一個不使用索引循環的版本。

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)

輸出

*    
 *   
  *  
   * 
  * 
 *  
*   

這應該這樣做:

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返回該character連接number ,則更容易。

例子:

'*'*10

返回

'**********'

因此,您使用 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)

返回

*
 *
  *
 *
*
n = int(input( ))
n1 = n//2 + 1
i = 1
while i <= n1:
    space = 1
    while space <= i - 1:
        print(" ",end="")
        space += 1
    j = 1
    p = "*"
    while j <= i:
        if j == i:
            print(p,end="")
        else:
            print("* ",end="")
        j += 1
    print()
    i += 1
i = n - n1
while i >= 1:
    space = 1
    while space <= i - 1:
        print(" ",end="")
        space += 1
    j = 1
    p = "*"
    while j <= i:
        if j == i:
            print(p,end="")
        else:
            print("* ",end="")
        j += 1
    print()
    i -= 1

星號的箭頭模式 -記住這里的 n 值總是奇數

對於 n = 5 輸出將是

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM