Echo's blog
Echo's blog
· 1 min read · Python学习

正方形列表

# 正方形#

1949 年 5 月 6 日, EDSAC早期的电子存储程序计算机在剑桥大学运行了其第一个程序。

它计算并打印出正方形列表:

PRTCL // SH
Terminal window
0 0
1 1
2 4
3 9
4 16
5 25
6 36
7 49
8 64
9 81

在左边,你得到了从 0 到 9 的所有个位数。右边是他们的正方形。例如,在最后一行,9 × 9 = 81。

这可以在 Python 中使用字符串连接来完成:

PRTCL // PY
# String concatenation
for i in range(5):
print('The square of ' + str(i) + ' is ' + str(i*i))

输出如下:

PRTCL // SH
Terminal window
The square of 0 is 0
The square of 1 is 1
The square of 2 is 4
The square of 3 is 9
The square of 4 is 16

# 字符串插值#

在继续执行说明之前,让我们学习一个与字符串连接非常相似的新工具。

字符串插值 是将变量值代入字符串中占位符的过程。

例如,如果您有一个模板可以在电子邮件中向某人打招呼,例如 'Hi {name}, nice to meet you!', 您想替换占位符 {name} 有实际名称。这是字符串插值。

上述程序可以使用字符串插值重新创建 {} 符号:

PRTCL // PY
# String interpolation
for i in range(5):
print(f'The square of {i} is {i*i}')

注意 f 引号前的前缀。

Related Posts

Comments

Copied
Copied to clipboard