如何用 Python 打印圖案

在 Python 中,for循環用於打印各種模式。打印各種圖案是面試中最常見的編程問題。多重循環用於打印圖案,其中第一個外部循環用於打印行數,內部循環用於打印列數。大多數模式使用以下概念。

  • 打印行數的外部循環。
  • 內部循環打印列數。
  • 根據 Python 中所需位置打印空白的變量。

在本教程中,我們將討論一些常見的模式。

在本節中,我們將學習常見的金字塔模式。

示例-


# This is the example of print simple pyramid pattern
n = int(input("Enter the number of rows"))
# outer loop to handle number of rows
for i in range(0, n):
    # inner loop to handle number of columns
    # values is changing according to outer loop
        for j in range(0, i + 1):
            # printing stars
            print("* ", end="")     

        # ending line after each row
        print()

輸出:

* 
* * 
* * * 
* * * * 
* * * * *

說明:

在上面的代碼中,我們已經初始化了n個變量來輸入模式的行數。我們輸入 n = 5,循環的外部範圍將是 0 到 4。

  • 內部 for循環的迭代取決於外部循環。內部循環負責打印列數。
  • 第一次迭代,I 的值是 0,增加了 1,所以變成了 0+1,現在第一次內循環迭代,打印一顆星(*)。
  • 在第二次迭代中,I 的值是 1,它增加了 1,所以它變成了 1+1,現在內部循環迭代了兩次並打印了兩個星號(*)。
  • end 參數防止跳轉到另一行。它將打印星形,直到循環有效。
  • 最後一個打印語句負責結束每行後的行。

示例-


# This is the example of print simple reversed right angle pyramid pattern
rows = int(input("Enter the number of rows:"))
k = 2 * rows - 2  # It is used for number of spaces
for i in range(0, rows):
    for j in range(0, k):
        print(end=" ")
    k = k - 2   # decrement k value after each iteration
    for j in range(0, i + 1):
        print("* ", end="")  # printing star
    print("")

輸出:

      * 
     * * 
    * * * 
   * * * * 
  * * * * *

代碼-


rows = int(input("Enter the number of rows: "))

# the outer loop is executing in reversed order
for i in range(rows + 1, 0, -1):  
    for j in range(0, i - 1):
        print("*", end=' ')
    print(" ")

輸出:

Enter the number of rows: 5
* * * * *  
* * * *  
* * *  
* *  
*  

代碼-


n = int(input("Enter the number of rows: "))
m = (2 * n) - 2
for i in range(0, n):
    for j in range(0, m):
        print(end=" ")
    m = m - 1  # decrementing m after each loop
    for j in range(0, i + 1):
        # printing full Triangle pyramid using stars
        print("* ", end=' ')
    print(" ")

輸出:

Enter the number of rows: 10
                  *   
                 *  *   
                *  *  *   
               *  *  *  *   
              *  *  *  *  *   
             *  *  *  *  *  *   
            *  *  *  *  *  *  *   
           *  *  *  *  *  *  *  *   
          *  *  *  *  *  *  *  *  *   
         *  *  *  *  *  *  *  *  *  *   

代碼-


rows = int(input("Enter the number of rows: "))

# It is used to print space
k = 2 * rows - 2
# Outer loop in reverse order
for i in range(rows, -1, -1):
    # Inner loop will print the number of space.
    for j in range(k, 0, -1):
        print(end=" ")
    k = k + 1
    # This inner loop will print the number o stars
    for j in range(0, i + 1):
        print("*", end=" ")
    print("")

輸出:

                  * * * * * * * * * * * 
                   * * * * * * * * * * 
                    * * * * * * * * * 
                     * * * * * * * * 
                      * * * * * * * 
                       * * * * * * 
                        * * * * * 
                         * * * * 
                          * * * 
                           * * 
                            *

代碼-


rows = int(input("Enter the number of rows: "))

# It is used to print the space
k = 2 * rows - 2
# Outer loop to print number of rows
for i in range(0, rows):
    # Inner loop is used to print number of space
    for j in range(0, k):
        print(end=" ")
    # Decrement in k after each iteration
    k = k - 1
    # This inner loop is used to print stars
    for j in range(0, i + 1):
        print("* ", end="")
    print("")

# Downward triangle Pyramid
# It is used to print the space
k = rows - 2
# Output for downward triangle pyramid
for i in range(rows, -1, -1):
    # inner loop will print the spaces
    for j in range(k, 0, -1):
        print(end=" ")
    # Increment in k after each iteration
    k = k + 1
    # This inner loop will print number of stars
    for j in range(0, i + 1):
        print("* ", end="")
    print("")

輸出:

Enter the number of rows: 8
              * 
             * * 
            * * * 
           * * * * 
          * * * * * 
         * * * * * * 
        * * * * * * * 
       * * * * * * * * 
      * * * * * * * * * 
       * * * * * * * * 
        * * * * * * * 
         * * * * * * 
          * * * * * 
           * * * * 
            * * * 
             * * 
              *

代碼-


rows = input("Enter the number of rows: ")

# Outer loop will print the number of rows
for i in range(0, rows):
    # This inner loop will print the stars
    for j in range(0, i + 1):
        print("*", end=' ')
    # Change line after each iteration
    print(" ")
# For second pattern
for i in range(rows + 1, 0, -1):
    for j in range(0, i - 1):
        print("*", end=' ')
    print(" ")

輸出:

Enter the number of rows: 7
*  
* *  
* * *  
* * * *  
* * * * *  
* * * * * *  
* * * * * * *  
* * * * * * *  
* * * * * *  
* * * * *  
* * * *  
* * *  
* *  
*

代碼-


rows = int(input("Enter the number of rows: "))
k = rows - 2
# This is used to print the downward pyramid
for i in range(rows, -1 , -1):
    for j in range(k , 0 , -1):
        print(end=" ")
    k = k + 1
    for j in range(0, i+1):
        print("* " , end="")
    print()

# This is used to print the upward pyramid
k = 2 * rows  - 2
for i in range(0 , rows+1):
    for j in range(0 , k):
        print(end="")
    k = k - 1
    for j in range(0, i + 1):
        print("* ", end="")
    print()

輸出:

Enter the number of rows: 5
   * * * * * * 
    * * * * * 
     * * * * 
      * * * 
       * * 
        * 
        * 
       * * 
      * * * 
     * * * * 
   * * * * * 
  * * * * * *

我們已經討論了用於循環的基本金字塔模式。模式的概念取決於 for循環的邏輯和正確使用。

在這一節中,我們描述了幾種不同類型的數字模式的程序。讓我們逐一了解以下模式。

代碼-


rows = int(input("Enter the number of rows: "))
# Outer loop will print number of rows
for i in range(rows+1):
    # Inner loop will print the value of i after each iteration
    for j in range(i):
        print(i, end=" ")  # print number
    # line after each row to display pattern correctly
    print(" ")

輸出:

Enter the number of rows: 5
1  
2 2  
3 3 3  
4 4 4 4  
5 5 5 5 5  

解釋-

在上面的代碼中,我們已經根據行值打印了數字。第一行打印一個數字。接下來,兩個數字打印在第二行,接下來的三個數字打印在第三行,以此類推。在……里

代碼-


rows = int(input("Enter the number of rows: "))

# This will print the rows
for i in range(1, rows+1):
    # This will print number of column
    for j in range(1, i + 1):
        print(j, end=' ')
    print("")

輸出:

Enter the number of rows: 5
1 
1 2 
1 2 3 
1 2 3 4 
1 2 3 4 5

在上面的代碼中,我們在內部 for循環中打印了列值 j。

代碼-


rows = int(input("Enter the number of rows: 5"))
k = 0
# Reversed loop for downward inverted pattern
for i in range(rows, 0, -1):
    # Increment in k after each iteration
    k += 1
    for j in range(1, i + 1):
        print(k, end=' ')
    print()

輸出:

Enter the number of rows: 5
1 1 1 1 1 
2 2 2 2 
3 3 3 
4 4 
5

說明:

在上面的代碼中,我們使用了反向循環來打印向下的倒金字塔,其中數字在每次迭代後都會減少。

代碼-


rows = int(input("Enter the number of rows: "))
# rows value assign to n variable
n = rows
# Download reversed loop
for i in range(rows, 0, -1):
    for j in range(0, i):
        # this will print the same number
        print(n, end=' ')
    print()

輸出:

Enter the number of rows: 6
6 6 6 6 6 6 
6 6 6 6 6 
6 6 6 6 
6 6 6 
6 6 
6

代碼-


rows = int(input("Enter the number of rows: "))
# Downward loop for inverse loop
for i in range(rows, 0, -1):
    n = i   # assign value to n of i after each iteration
    for j in range(0, i):
        # print reduced value in each new line
        print(n, end=' ')
    print("\r")

輸出:

Enter the number of rows: 6
6 6 6 6 6 6 
5 5 5 5 5 
4 4 4 4 
3 3 3 
2 2 
1

代碼-


current_Number = 1
stop = 2
rows = 3  # Number of rows to print numbers

for i in range(rows):
    for j in range(1, stop):
        print(current_Number, end=' ')
        current_Number += 1
    print("")
    stop += 2

輸出:

1 
2 3 4 
5 6 7 8 9

代碼-


rows = int(input("Enter the number of rows: "))
for i in range(0, rows + 1):
    # inner loop for decrement in i values
    for j in range(rows - i, 0, -1):
        print(j, end=' ')
    print()

輸出:

Enter the number of rows: 6
6 5 4 3 2 1 
5 4 3 2 1 
4 3 2 1 
3 2 1 
2 1 
1

代碼-


rows = int(input("Enter the number of rows: "))
i = 1
# outer file loop to print number of rows
while i <= rows:
    j = 1
    # Check the column after each iteration
    while j <= i:
        # print odd values
        print((i * 2 - 1), end=" ")
        j = j + 1
    i = i + 1
    print()

輸出:

Enter the number of rows: 5
1 
3 3 
5 5 5 
7 7 7 7 
9 9 9 9 9

代碼-


rows = int(input("Enter the number of rows: "))
for i in range(1, rows + 1):
    for j in range(1, rows + 1):
        # Check condition if value of j is smaller or equal than
        # the j then print i otherwise print j
        if j <= i:
            print(i, end=' ')
        else:
            print(j, end=' ')
    print()

輸出:

Enter the number of rows: 5
1 2 3 4 5 
2 2 3 4 5 
3 3 3 4 5 
4 4 4 4 5 
5 5 5 5 5

rows = int(input("Enter the number of rows: "))
for i in range(1, rows):
    for j in range(1, i + 1):
        # It prints multiplication or row and column
        print(i * j, end='  ')
    print()

輸出:

Enter the number of rows: 8
1  
2  4  
3  6  9  
4  8  12  16  
5  10  15  20  25  
6  12  18  24  30  36  
7  14  21  28  35  42  49  

在上面的部分,我們已經討論了所有基本的數字模式。它將在 Python 上為循環生成一個強命令。我們可以使用任何類型的循環模式。

我們知道,每個字母表都有自己的 ASCII 值,所以定義一個字符並將其打印到屏幕上。讓我們通過下面的例子來理解這些模式

代碼-


print("The character pattern ")
asciiValue = 65     #ASCII value of A
for i in range(0, 5):
    for j in range(0, i + 1):
        # It will convert the ASCII value to the character
        alphabate = chr(asciiValue)
        print(alphabate, end=' ')
        asciiValue += 1
    print()

輸出:

The character pattern 
A 
B C 
D E F 
G H I J 
K L M N O

解釋-

在上面的代碼中,我們將整數值 65 賦給了ASCII 值變量,它是一個 ASCII 值 a。我們為循環定義了打印五行。在內部循環體中,我們使用 char()函數將 ASCII 值轉換為字符。它將打印字母,在每次迭代後增加 asciiValue。

代碼-


print("The character pattern ")
asciiValue = int(input("Enter the ASCII value to print pattern: "))
# User - define value
if (asciiValue >= 65 or asciiValue <=122):
    for i in range(0, 5):
        for j in range(0, i + 1):
            # It will convert the ASCII value to the character
            alphabate = chr(asciiValue)
            print(alphabate, end=' ')
        print()
else:
    print("Enter the valid character value")

輸出:

The character pattern 
Enter the ASCII value to print pattern: 75
K 
K K 
K K K 
K K K K 
K K K K K

代碼-


str1 = "JavaTpoint"
x = ""
for i in str1:
    x += i
    print(x)

輸出:

J
Ja
Jav
Java
JavaT
JavaTp
JavaTpo
JavaTpoi
JavaTpoin
JavaTpoint

我們可以用任何單詞來打印字符。

代碼-


print("Print equilateral triangle Pyramid with characters ")
s = 5
asciiValue = 65
m = (2 * s) - 2
for i in range(0, s):
    for j in range(0, m):
        print(end=" ")
    # Decreased the value of after each iteration
    m = m - 1
    for j in range(0, i + 1):
        alphabate = chr(asciiValue)
        print(alphabate, end=' ')
        # Increase the ASCII number after each iteration
        asciiValue += 1
    print()

輸出:

Print equilateral triangle Pyramid with characters 
        A 
       B C 
      D E F 
     G H I J 
    K L M N O

在本文中,我們已經討論了所有基本的模式程序。這些模式在面試中經常被問到,理解 Python for loop 的概念也很有幫助。一旦我們得到了程序的邏輯,我們就可以使用 Python 循環打印任何模式。


原創文章,作者:SY99E,如若轉載,請註明出處:https://www.506064.com/zh-hk/n/126203.html

(0)
打賞 微信掃一掃 微信掃一掃 支付寶掃一掃 支付寶掃一掃
SY99E的頭像SY99E
上一篇 2024-10-03 23:07
下一篇 2024-10-03 23:07

相關推薦

  • Python中引入上一級目錄中函數

    Python中經常需要調用其他文件夾中的模塊或函數,其中一個常見的操作是引入上一級目錄中的函數。在此,我們將從多個角度詳細解釋如何在Python中引入上一級目錄的函數。 一、加入環…

    編程 2025-04-29
  • 如何查看Anaconda中Python路徑

    對Anaconda中Python路徑即conda環境的查看進行詳細的闡述。 一、使用命令行查看 1、在Windows系統中,可以使用命令提示符(cmd)或者Anaconda Pro…

    編程 2025-04-29
  • Python計算陽曆日期對應周幾

    本文介紹如何通過Python計算任意陽曆日期對應周幾。 一、獲取日期 獲取日期可以通過Python內置的模塊datetime實現,示例代碼如下: from datetime imp…

    編程 2025-04-29
  • Python周杰倫代碼用法介紹

    本文將從多個方面對Python周杰倫代碼進行詳細的闡述。 一、代碼介紹 from urllib.request import urlopen from bs4 import Bea…

    編程 2025-04-29
  • Python列表中負數的個數

    Python列表是一個有序的集合,可以存儲多個不同類型的元素。而負數是指小於0的整數。在Python列表中,我們想要找到負數的個數,可以通過以下幾個方面進行實現。 一、使用循環遍歷…

    編程 2025-04-29
  • Python清華鏡像下載

    Python清華鏡像是一個高質量的Python開發資源鏡像站,提供了Python及其相關的開發工具、框架和文檔的下載服務。本文將從以下幾個方面對Python清華鏡像下載進行詳細的闡…

    編程 2025-04-29
  • Python程序需要編譯才能執行

    Python 被廣泛應用於數據分析、人工智能、科學計算等領域,它的靈活性和簡單易學的性質使得越來越多的人喜歡使用 Python 進行編程。然而,在 Python 中程序執行的方式不…

    編程 2025-04-29
  • 蝴蝶優化算法Python版

    蝴蝶優化算法是一種基於仿生學的優化算法,模仿自然界中的蝴蝶進行搜索。它可以應用於多個領域的優化問題,包括數學優化、工程問題、機器學習等。本文將從多個方面對蝴蝶優化算法Python版…

    編程 2025-04-29
  • python強行終止程序快捷鍵

    本文將從多個方面對python強行終止程序快捷鍵進行詳細闡述,並提供相應代碼示例。 一、Ctrl+C快捷鍵 Ctrl+C快捷鍵是在終端中經常用來強行終止運行的程序。當你在終端中運行…

    編程 2025-04-29
  • Python字典去重複工具

    使用Python語言編寫字典去重複工具,可幫助用戶快速去重複。 一、字典去重複工具的需求 在使用Python編寫程序時,我們經常需要處理數據文件,其中包含了大量的重複數據。為了方便…

    編程 2025-04-29

發表回復

登錄後才能評論