使用基本程式設計概念在 Python 中列印乘法表

Jesse John 2023年1月30日

1. 使用變數
2. 獲取使用者輸入
3. 使用內建函式
4. 型別轉換變數
5. 迭代（迴圈）
6. 字串格式化
7. 使用 Unicode 符號

基本程式設計概念

``````table_of = 5
``````

``````table_of = input("Print times table of: ")
``````

``````table_of = int(input("Print times table of: "))
``````

`print("Times")` 在顯示屏上列印單詞 `Times`。一個空的 `print()` 函式列印一個空行。

`range()` 函式建立從 `start_int` 到但不包括 `end_int` 的序列。預設情況下，它增加 1。

``````range(start_int, end_int, step_int)
``````

``````for variable in range(start, end):
code to repeat
``````

Python 的 `f` 字串格式化功能允許我們使用佔位符 `{}` 在字串中包含變數。要使用變數 `table_of` 的值，我們將使用：

``````print(f"Times table of {table_of}")
``````

``````\N{MULTIPLICATION SIGN}
``````

在 Python 中列印給定數字的時間表

``````# The following code prints the times table
# of the given number till 'number x 9'.

# It prints the times table in two different ways.

table_of = int(input("Print times table of: "))

# Get the length of the result
l_res = len(str(table_of * 9))

print(f"Times Table of {table_of}:")
print()

for multiple in range(1, 10):
print(
f"{multiple} \N{MULTIPLICATION SIGN} {table_of} = {table_of*multiple:{l_res}}"
)
print()

print("-------------")
print()

for multiple in range(1, 10):
print(
f"{table_of} \N{MULTIPLICATION SIGN} {multiple} = {table_of*multiple:{l_res}}"
)
print()
``````

``````Print times table of: 1717
Times Table of 1717:

1 × 1717 =  1717

2 × 1717 =  3434

3 × 1717 =  5151

4 × 1717 =  6868

5 × 1717 =  8585

6 × 1717 = 10302

7 × 1717 = 12019

8 × 1717 = 13736

9 × 1717 = 15453

-------------

1717 × 1 =  1717

1717 × 2 =  3434

1717 × 3 =  5151

1717 × 4 =  6868

1717 × 5 =  8585

1717 × 6 = 10302

1717 × 7 = 12019

1717 × 8 = 13736

1717 × 9 = 15453
``````

``````# The following code prints the times table
# of the given number from a multiple till a multiple.

table_of = int(input("Print times table of: "))

# We will assume that the user correctly gives a smaller number
# at which to start and a larger number at which to end.

from_multiple = int(input("Enter the multiple at which to start: "))
to_multiple = int(input("Enter the multiple at which to end: "))

# Get the length of the result
l_res = len(str(table_of * to_multiple))

# Get the length of the larger multiple.
l_multiple = len(str(to_multiple))

print(f"Times Table of {table_of}:")
print()

for multiple in range(from_multiple, to_multiple + 1):
print(
f"{multiple:{l_multiple}} \N{MULTIPLICATION SIGN} {table_of} = {multiple*table_of:{l_res}}"
)
print()
``````

``````Print times table of: 16

Enter the multiple at which to start: 5

Enter the multiple at which to end: 15
Times Table of 16:

5 × 16 =  80

6 × 16 =  96

7 × 16 = 112

8 × 16 = 128

9 × 16 = 144

10 × 16 = 160

11 × 16 = 176

12 × 16 = 192

13 × 16 = 208

14 × 16 = 224

15 × 16 = 240
``````

Jesse is passionate about data analysis and visualization. He uses the R statistical programming language for all aspects of his work.