C-和-Python-应用教程-一-

77 阅读34分钟

C 和 Python 应用教程(一)

原文:C and Python Applications

协议:CC BY-NC-SA 4.0

一、Python 编程

这是两章中的第一章,在这两章中,您将回顾 Python 和 C 编程语言。尽管不需要事先了解 Python 或 C 语言,但我们假定您对计算和程序有基本的了解。

在本章中,我们将从 Python 的基础知识开始。这将包括程序中使用的项目如何存储在计算机中,基本的算术格式,处理字符串,读入用户可以在命令行输入的数据,等等。然后,我们将学习计算机上的文件访问,这将在本书结束时把我们引向工业/商业水平的计算。

如果您的计算机上还没有 Python 开发环境,您可以从 www.python.org/downloads/ 免费下载它和开发工具包。访问 Python 的另一种方式是使用 Visual Studio。同样,可以下载它的一个版本。

变量的定义

本节介绍 Python 中使用的不同类型的存储区域。我们将这些存储区域称为“变量”不同的类型可以是数字(整数或小数)、字符和不同类型的组(字符串、数组、字典、列表或元组)。

在这些示例中,您可以在命令行中输入“Python ”,这将启动 Python 环境并生成“> > >”作为提示,让您输入 Python 代码。

在 Python 中,不像 C,你不把变量定义为一个特定的类型。不同的类型有整数、浮点、字符、字符串等。当你给变量赋值时,类型被赋值。所以尝试下面的代码:

>>> a1 = 51
>>> print(type(a1))
We get the output
<class 'int'>
>>>

这里我们定义了一个名为“a1”的变量,并给它赋值整数值 51。

然后,我们用参数“type”和“a1”调用函数“print”,并得到回复“class 'int '”。“类型”是指我们要显示变量是整数、浮点、字符、字符串等。

我们现在可以通过键入“quit()”退出 Python 环境。

我们现在将从程序中执行相同的功能。

创建一个名为“typ1a.py”的文件。

然后输入下面两行 Python 代码:

a1=51
print(type(a1))

现在在命令行输入“python typ1a.py”。

你应该得到输出

<class 'int'>

这和我们的第一个例子一样。

这只是证明了两种方法的等价性。

显然,如果你想运行一个有很多行代码的程序,并且可能要运行很多次,那么把代码放在一个文件中会更有效率。

我们可以使用以下代码演示不同的数据类型存储在同一个变量中:

a1=51
print(type(a1))

a1=51.6
print(type(a1))

a1='51'
print(type(a1))

当我们运行这个时,我们得到

<class 'int'>
<class 'float'>
<class 'str'>

输入的 51 是一个整数。51.6 是浮点(十进制)类型,而“51”是字符串。

如果我们使用 print("a1 is ",type(a1)),我们可以使结果更清楚一些。

所以我们的程序现在是

a1=51
print("a1 is",type(a1))

a1=51.6
print("a1 is",type(a1))

a1='51'
print("a1 is",type(a1))

输出是

a1 is <class 'int'>
a1 is <class 'float'>
a1 is <class 'str'>

我们可以在我们的代码行前面加上“#”字符来添加注释。

a1='51' #assign string containing 51 to variable a1
print("a1 is",type(a1)) # print the type assigned to a1

下面显示了一些简单的算术运算。

以下代码保存在文件“arith1.py”中:

arith1a.py

用整数值初始化变量 v1、v2、v3 和 v4。

v1= 2
v2 = 4
v3 = 7
v4 = 8

将 v1 与 v2 相加,并将结果存储在 v5 中。

v5 = v1 + v2
print(v5)

结果是

6

您可以将添加与打印结合起来,如下所示:

print(v1+v2)

给出相同的答案:

6

现在做减法:

v6 = v4 - v3
print(v6)
giving
1

现在是乘法:

v7 = v4 * v3

print(v7)
giving
56

现在一个部门:

v8 = v4 / v1
print(v8)
giving
4.0

v10 = v3 % v2 # the % sign means show the remainder of the division
print(v10)
gives
3

用 2 的幂来提高。

v11 = v2 ** 2
print(v11)
gives
16

提高到变量 v1 中的幂。

这里 v2 包含 4,v1 包含 2。

v11 = v2 ** v1
print(v11)
gives
16

展示 Python 如何遵守 BODMAS (BIDMAS)的规则。

这里 v2 包含 4,v1 包含 2,v3 包含 7,v4 包含 8。

v11 = v1 + v2 * v4 - v3 # show BODMAS
print(v11)
gives
27

展示 Python 如何遵守普通代数规则。

v11 = (v1 + v2) * (v4 - v3)
print(v11)
gives
6

实数(浮点数)

这种类型的数字包含小数点。所以,对于下面的作业

V1 = 2
V2 = 3.5
V3 = 5.1
V4 = 6.75

我们得到

print(type(V1))
<class 'int'>
print(type(V2))
<class 'float'>
print(type(V3))
<class 'float'>
print(type(V4))
<class 'float'>

特性

在 Python 中,还可以将字符分配给位置,例如:

c1 = 'a'
print(type(c1))
produces
<class 'str'>

这意味着 c1 被归类为字符串。

现在我们知道了我们可以有哪些不同类型的变量,我们将看看如何使用它们。

读入数据

现在我们可以向运行我们程序的人显示一条消息,我们可以要求他们键入一个字符,然后阅读这个字符,并把它打印到屏幕上。本节着眼于用户如何输入程序要读取的数据。

如果我们输入命令

vara = input()

计算机等待用户输入数据。

所以如果你现在输入 r5,计算机将 r5 存储在变量 vara 中。

您可以通过键入以下命令打印 vara 的内容来检查这一点

print(vara)

哪张照片

r5

我们可以通过使用

print("data typed in is:-", vara)
giving
data typed in is:-r5

您还可以通过输入以下命令使输入命令对用户来说更加清晰

varb=input(“enter some data to be stored in varb”)

然后,我们可以再次明确地打印出内容

print("data typed in is:-", varb)
giving
data typed in is:-r5

你必须使用 int(input)来输入一个整数。

否则,它是一个字符串(一个或多个字符),例如:

n = int(input('Enter a number: '))
you enter 4
 >>> print(type(n))
<class 'int'>

# Program to check input
# type in Python

num = input ("Enter number :")
print(num)
#You could enter 5 here and it would store 5 as a string and not as a number
>>> print(num)
5
>>> print ("type of number", type(num))
type of number <class 'str'>
>>>

#entering a float number (type 'float' before the 'input' command)
n = float(input('Enter a number: '))
Enter a number: 3.8
>>> print(type(n))
<class 'float'>
>>> print(n )
3.8

既然我们可以手动将数据输入到程序中,我们将查看数据组。

数组

数组是包含许多项的存储区域。从我们上一节关于整数的内容来看,我们可以用同一个标签定义多个整数。Python 没有默认的数组类型,尽管我们有不同类型的数组。

因此,我们可以有一个名为“firstintarr”的整数数组,其中包含数字 2、3、5、7、11 和 13。每个条目称为一个“元素”,数组中的单个元素可以使用它在数组中的位置来引用。这个位置被称为“指数”数组中的元素必须是同一类型。类型显示在数组的开头。

数组机制必须导入到您的程序中,如下所示:

from array import *
firstintarr = array('i', [2,3,5,7,11])

firstintarr 定义中的“I”表示元素是整数。

我们可以使用索引引用数组的元素,例如:

v1 = firstintarr[3]
print(v1)

这输出

7

我们也可以通过在数组定义中用“f”代替“I”来定义数组中的浮点变量。

所以我们可以定义

firstfloatarr = array( 'f', [0.2,4.3,21.9,7.7])

我们现在可以写了

varfloat1 = firstfloatarr[1]
print(varfloat1)

这会将 4.3 存储到 varfloat1 中。

数组机制必须被导入到你的程序中。

所以在每个程序的开始,你需要包含代码

from array import *

一旦我们有了数组,我们就可以在数组中插入、删除、搜索或更新元素。

数组是一个容器,可以容纳固定数量的项目,这些项目应该是同一类型的。大多数数据结构利用数组来实现它们的算法。以下是理解阵列概念的重要术语:

  • 插入

  • 删除(移除)

  • 搜索

  • 更新

  • 附加

现在让我们来复习一下。

插入到数组中

以下代码位于 array3.py 文件中:

from array import *

myarr = array('i', [2,3,5,7,11])

myarr.insert(1,13) # this inserts 13 into position 1 of the array (counting from 0)

for x in myarr:
 print(x)

这输出

2
13
3
5
7
11

从数组中删除

以下代码位于源代码文件 array4.py 中:

array4.py

from array import *

myarr = array('i', [2,3,5,7,11])

myarr.remove(2) # this removes the element containing 2 from the array

for x in myarr:
 print(x)

这输出

3
5
7
11

搜索

以下代码位于 array5.py 文件中:

from array import *

myarr = array('i', [2,3,5,7,11])

print (myarr.index(3))#this finds the index of the array which contains 3

这输出

1

更新数组

以下代码位于 array6.py 文件中:

array6.py

from array import *

myarr = array('i', [2,3,5,7,11])

myarr[2] = 17) #this updates element 2 with 17

for x in myarr:
 print(x)

这输出

2
3
17
7
11

追加到数组

以下代码位于 array9a.py 文件中:

array9a.py

from array import *

myarr = array('i', [2,3,5,7,11])

for x in myarr:
 print(x)

new = int(input("Enter an integer: "))
myarr.append(new)
print(myarr)

这输出

2
3
5
7
11

输入一个整数:19

array('i', [2, 3, 5, 7, 11, 19])

本节展示了 Python 中“数组”的用法。

用线串

字符串类似于我们在上一节中讨论的字符数组。它们在引号中定义。这些可以是单引号或双引号。我们可以使用 slice 操作符([ ]和[:])来指定我们定义的字符串的一部分。与字符数组一样,我们可以使用它在字符串(索引)中的位置来指定字符串中的单个元素,其中索引从 0 开始。

我们可以使用“+”连接两个字符串,并使用“*”重复该字符串。

我们不能更新字符串的元素——它们是不可变的。这意味着一旦它们被创建,就不能被修改。

以下代码:

firststring = 'begin'
print(firststring)
gives
begin

以下代码:

one = 1
two = 2
three = one + two
print(three)
#gives
3

以下代码:

first = " first "
second= "second"
concat = first + " " + second
print(concat)
#gives
first  second
print("concat: %s" % concat)
gives
concat:  first  second
The following code is in the file tst13a.py
secondstring = "second string"
print(secondstring.index("o")) #gives
3
print(secondstring.count("s")) # count the number of s characters in string gives
2

print(secondstring[2:9]) # prints slice of string from 2 to 9 giving

cond st
print(secondstring[2:9:1]) #  The general form is [start:stop:step] giving

cond st
print(secondstring[::-1]) # Reverses the string giving

gnirts dnoces

splitup = secondstring.split(" ")
print(splitup) #gives
['second', 'string']

字符串是不可变的,所以如果我们尝试

second= "second"
second[0]="q"

我们得到

回溯(最近一次呼叫):

  File "<stdin>", line 1, in <module>

type error:“str”对象不支持项赋值

表明我们试图更新一些不可变的东西(在这个例子中是一个字符串)。

列表

列表类似于数组和字符串,因为您定义了许多元素,这些元素可以使用索引单独指定。然而,对于列表,元素可以是不同的类型,例如,字符、整数和浮点。

以下代码位于 alist7.py 文件中:

firstlist = ['k', 97 ,56.42, 64.08, 'bernard']

我们在方括号中指定元素。

然后,我们可以使用索引(从 0 开始)访问列表中的单个元素,例如:

print(firstlist[0])
gives
k
print(firstlist[1:3])
gives
[97, 56.42]

我们可以修改列表中的元素。

firstlist[3] = 'plj'
print(firstlist)
giving
['k', 97, 56.42, 'plj', 'bernard']

我们可以从列表中删除一个元素。

del firstlist[3]
print(firstlist)
giving
['k', 97, 56.42, 'bernard']

我们可以在列表中添加一个元素。

firstlist.append(453.769)
print(firstlist)
giving
['k', 97, 56.42, 'bernard', 453.769]

读取列表中的条目

以下代码保存在 alist1a.py 文件中:

alist1a.py

list1 = ['first', 'second', 'third']
list2 = [1, 2, 3, 4, 5 ]

print ("list1: ", list1)
print ("list1[0]: ", list1[0])
print ("list2: ", list2)
print ("list2[3]: ", list2[3])
print ("list2[:3]: ", list2[:3])
print ("list2[2:]: ", list2[2:])
print ("list2[1:3]: ", list2[1:3])

这输出

list1:  ['first', 'second', 'third']
list1[0]:  first
list2:  [1, 2, 3, 4, 5]
list2[3]:  4
list2[:3]:  [1, 2, 3]
list2[2:]:  [3, 4, 5]
list2[1:3]:  [2, 3]

更新列表

以下代码保存在文件 alist2a.py 中:

alist2a.py

list1 = [1, 2, 3, 4, 5 ]

print ("list1: ", list1)

list1[1] = 26 #update the second item (counting from zero)

print ("updated list1: ", list1)

这输出

list1:  [1, 2, 3, 4, 5]
updated list1:  [1, 26, 3, 4, 5]

从列表中删除元素

以下代码保存在 alist3a.py 文件中:

alist3a.py
list1 = [1,2,3,4,5,6]
print (list1)
del list1[4]
print ("Updated list1 : ", list1)

这输出

[1, 2, 3, 4, 5, 6]
Updated list1 :  [1, 2, 3, 4, 6]

追加到列表

以下代码保存在文件 alist4aa.py 中:

alist4aa.py
list2 = [10,11,12,13,14,15]
print (list2)
new = int(input("Enter an integer: "))
list2.append(new)
print(list2)

这会输出(如果您输入 489)

[10, 11, 12, 13, 14, 15]

输入一个整数:489

[10, 11, 12, 13, 14, 15, 489]

这显示了列表的用途。

字典

字典包含一个条目列表,其中一个条目充当下一个条目的键。列表是无序的,可以修改。键值关系是唯一的。字典是可变的。

创建字典

在第一个例子中,我们创建了一个空字典。第二,我们有条目。

firstdict = {}

或者

firstdict ={'1':'first','two':'second','my3':'3rd'}

添加到词典中

以下代码保存在文件 adict1a.py 中:

adict1a.py
#create the dictionary
adict1 = {'1':'first','two':'second','my3':'3rd'}

print (adict1)

print (adict1['two'])   # in the dictionary 'two' is the key to 'second'

adict1[4] = 'four' # we want to add another value called 'four' whose key is 4

print (adict1)

print (len(adict1)) #this will print the number of key-value pairs

这输出

{'1': 'first', 'two': 'second', 'my3': '3rd'}
second
{'1': 'first', 'two': 'second', 'my3': '3rd', 4: 'four'}
4

如果我们想要添加其键为 dinsdale 的值,那么我们将其指定为' dinsdale '。

因此

adict1['dinsdale'] = 'doug'
print (adict1)

输出

{'1': 'first', 'two': 'second', 'my3': '3rd', 4: 'four', 'dinsdale': 'doug'}

修订词典

以下代码保存在文件 adict2a.py 中。

这将键为“2”的值修改为“2nd”。

adict2a.py
adict1 = {'1':'first','two':'second','my3':'3rd'}

adict1['two'] = '2nd'

print(adict1)

这输出

{'1': 'first', 'two': '2nd', 'my3': '3rd'}

从字典中删除

以下代码保存在文件 adict3a.py 中:

adict3a.py
adict1 = {'1':'first','two':'second','my3':'3rd'}
print(adict1)
del adict1['two'] #this deletes the key-value pair whose key is 'two'
print(adict1)

这输出

{'1': 'first', 'two': 'second', 'my3': '3rd'}
{'1': 'first', 'my3': '3rd'}

在字典中搜索

我们想搜索字典,看看其中是否包含某个特定的关键字。在这种情况下,我们想看看' a '和' c '是否是字典中的键。

在 Python 中

>>> my_dict = {'a' : 'one', 'b' : 'two'}

>>> 'a' in my_dict
TRUE
>>> 'c' in my_dict
FALSE

以下代码保存在文件 adict5aa.py 中:

adict5aa.py
print("Enter key to be tested: ")
testkey = input()
my_dict = {'a' : 'one', 'b' : 'two'}
print (my_dict.get(testkey, "none"))

这将输出(如果在询问密钥时输入“a ”)

输入要测试的密钥:

a

一个

或输出(如果在询问密钥时输入“x”)

输入要测试的密钥:

x

没有人

我们已经看到字典能做什么。我们现在来看看元组。

元组

元组包含不可变的项目。元组中的元素可以用括号中的逗号分隔,或者用逗号分隔单个引用的元素。它们的访问方式类似于数组,元素从 0 开始编号。在这一节中,我们将研究元组的创建、连接、读取、删除和搜索。

例如,定义两个称为 firsttup 和 secondttup 的元组:

firsttup = ('a', 'b', 'c', 1, 2, 3)
secondtup = “a”, “b”, 10,  25

以下代码引用了 firsttup 的第三个元素:

firsttup[2]
gives
c

以下代码引用了 firsttup 的第三个元素:

firsttup[3]
gives
1
secondtup = "a", "b", 10,  25

以下代码引用 secondtup 的第二个元素:

secondtup[1]
gives
b

以下代码引用了 secondtup 的第三个元素:

secondtup[2]
gives
10

我们还可以使用负索引从末尾开始选择,并向后工作,例如,

secondtup[-1]

这给了

25
secondtup[-2]

这给了

10

无法修改元组。

所以如果我们有

firsttup = ('a', 'b' 'c', 1, 2, 3)
firsttup[3] = 9

我们会得到

  File "<stdin>", line 1, in <module>

TypeError: 'tuple' object does not support item assignment

创建元组

# An empty tuple

empty_tuple = ()
print (empty_tuple)
()

# Creating non-empty tuples

# One way of creation
tup = 'first', 'second'
print(tup)
('first', 'second')

# Another for doing the same
tup = ('first', 'second')
print(tup)
('first', 'second')

连接两个元组

# Code for concatenating 2 tuples

tuple1 = (0, 1, 2, 3)
tuple2 = ('first', 'second')

# Concatenating above two
print(tuple1 + tuple2)
(0, 1, 2, 3, 'first', 'second')

创建嵌套元组

# Code for creating nested tuples

tuple1 = (0, 1, 2, 3)
tuple2 = ('first', 'second')
tuple3 = (tuple1, tuple2)
print(tuple3)
gives
((0, 1, 2, 3), ('first', 'second'))

创建重复的元组

# Code to create a tuple with repetition

tuple3 = ('first',)*3
print(tuple3)
gives
('first', 'first', 'first')

将列表或字符串转换为元组

# Code for converting a list and a string into a tuple

list1 = [0, 1, 2]
print(tuple(list1))
(0, 1, 2)
print(tuple('first')) # string 'first'
('f', 'i', 'r', 's', 't')

创建单元素元组

# Creating tuple with

single element (note that we still require the comma)
t=(1,)
print(t)
gives
(1,)

读取元组

# Reading from start (index starts at zero)

tup1=(2,3,4,5,6,7)
tup[3]
gives
5

# Reading from  end (index starts at -1)
tup1[-1]
gives
7

在元组内搜索

# Search
tup1=(2,3,4,5,6,7)
print (6 in tup1) # this tests if 6 is contained in tup1
gives
True
print (9 in tup1)
gives
False

删除元组

# Deleting a complete Tuple

del tup1
print(tup1)
gives

NameError: name 'tup1' is not defined

使用元组创建变量

# define our tuple as

aTuple = (10, 20, 30, 40)
# Now we can assign each of its elements to separate variables
a, b, c, d = aTuple
print(a)
gives
10
print(b)
gives
20
print(c)
gives
30
print(d)
gives
40

我们已经在本节中介绍了不同类型变量的定义和用法。我们现在来看看“if”语句的用法。

如果是这样的话

当你的程序需要决定是执行一个操作还是另一个操作时,我们使用 if 语句。

这些相当简单。基本上,我们说

if (something is true)
        Perform a task

这是 if 的基本形式。

我们可以这样延伸

if (a condition  is true)
      Perform a task
else if it does not satisfy the above condition
      Perform a different task

下面是演示这一点的一些 Python 代码:

number = 5
if number > 3:
   print('greater than 3')

number = 5
if number > 3:
   print('greater than 3')
else:
   print('not greater than 3')

将这段代码输入程序并运行它。毫不奇怪,输出是

greater than 3

您可以修改程序,以便输入要测试的数字,但是不要忘记,对于这个代码,您需要 number = int(input ("Enter number:"))来输入一个数字。

本节已经展示了“if”语句在编程中的重要性。现在我们来看看循环。

循环(For 和 While)

当我们在一个程序中做许多计算时,用十个数字做类似的事情可能有点麻烦。我们可以通过重复类似的代码十次来完成。我们可以通过编写一段代码,然后在同一段代码中循环十次来使这变得简单一点。这被称为“for 循环”我们还将看看“while”循环。

对于循环

下面是一个 for 循环如何帮助我们的例子。

声明是

'for x in variable
     Carry out some code'

所以如果我们有一个如下的变量

forloopvar1 = [20,13,56,9]

我们可以说

for x in forloopvar1: # go through forloop1 and place each element  in x
    print(x)  #this is the only instruction within the loop

输出

20
13
56
9

Python 中的“范围”指令具有通用格式

范围(开始、停止、步进)

在哪里

“start”是索引的起始值。默认值为 0。

“停止”比要使用的最后一个索引小 1。

“步长”是指索引增加的幅度。默认值为 1。

下面是一个使用“range”指令的例子。

程序从变量 number 和 total 设置为 1 开始循环 for 循环。

在循环中,它将数字的当前值乘以累计值。然后它在数字上加 1。所以它算出 123456789*10 或“10 阶乘”(10!).

number = 1
total = 1
for x in range(10): ): #so here start is 0 (default), stop is 10-1, and step is 1
         total = total * number
        number = number + 1
print(total)

这输出

3628800

你可以用科学计算器来验证它是 10 的阶乘。

for x in range(3, 6): # starts with 3 and ends with 6-1
    print(x)

这输出

3
4
5

我们也可以有一个值的列表,而不是一个范围,如下一个程序所示。

它遍历这些值,找到值 46 的索引位置。我们可以看到 46 在位置 9(从 0 开始计数)。

forloopvar1 = [20, 13, 56, 9, 32, 19, 87, 51, 70, 46, 56]
count = 0
for x in forloopvar1:
     if x == 46:
           break
          count = count + 1
print(count)

这输出

9

While 循环

“while”循环的逻辑类似于我们的 for 循环。

在这里,我们说

'while x is true
      Carry out some code'

因此,我们可以有下面的代码,它不断地向 count 加 1,直到 count 不再小于 10。在循环中,要求用户输入整数。这些被加到一个总数中,在循环结束时打印出来。

total = 0;
number = 0
# while loop goes round 10 times
while number < 10 :

      # ask the user to enter the integer number
      n = int(input('Enter a number: '))

      total = total + n
      number = number + 1
print('Total Sum is = ', total)

因此,如果用户输入如下所示的数字,我们将得到总数:

Enter a number: 1
Enter a number: 2
Enter a number: 3
Enter a number: 4
Enter a number: 5
Enter a number: 6
Enter a number: 7
Enter a number: 8
Enter a number: 9
Enter a number: 10
Total Sum is =  55

我们在这一节已经看到了循环的重要性。我们的下一部分着眼于开关。

开关

在 C 编程中,有一个被广泛使用的指令叫做“switch”但是,因为 Python 中没有 switch 语句,所以本节将演示一些可以包含在您的程序中以执行相同功能的代码。

开关根据它接收到的变量值跳转到一段代码。例如,如果您必须为 30 多岁的人和 40 多岁的人执行不同的代码,并为 50 多岁的人执行不同的代码,我们可以有下面的代码。这里我们有“选项”中的值,它决定了我们跳转到哪个代码。

该函数的代码在文件 as switch 3 . py 中:

aswitch3.py
def switch(option):
     if option == 30:
                print("Code for people in their 30s")
     elif option == 40:
                print("Code for people in their 40s")

     elif option == 50:

               print("Code for people in their 50s")

    else:
        print("Incorrect option")
#main code in the program where you enter 30,40 or 50 and the function 'switch' is called which uses the appropriate number as shown.
 optionentered = int(input("enter your option (30, 40 or 50 : ) "))
switch(optionentered)
running this program and entering '50' gives
enter your option : 50
Code for people in their 50s

本节展示了如何在 Python 中执行切换。我们现在转到 Python 中一个重要的函数库。这叫做“numpy”

使用 Numpy 的算术运算

Numpy 是一个数学函数库,可以包含在 Python 程序中。它在操作数组、读取文本文件和处理数学公式时非常有用。Numpy 可以通过多种方式安装。一种方法是从命令行使用“pip ”,如下所示:

pip install numpy

它在操作矩阵(或具有额外维度的数组)时特别有用。到目前为止,我们看到的数组都是一维数组。在这一节中,我们将看看更多维度的数组。一维数组也可以称为“秩 1 数组”

onedarray = array('i', [10,20,30,40,50])

我们使用“import numpy”将 numpy 导入到我们的程序中,并为我们的程序分配一个链接。这里我们将链接定义为“np ”,因此整行代码是

import numpy as np

numpy 函数“shape”返回数组的维数。所以如果你的数组被定义为

b = np.array([[1,2,3],[4,5,6]])

则该数组将是一个 2×3 矩阵(两行三列),如下所示:

[[1 2 3]
 [4 5 6]]

所以如果你现在输入

print(b.shape)

你会得到

(2, 3)

作为形状。

这个函数的代码在文件 numpy1.py 中:

import numpy as np

a = np.array([1, 2, 3])   # Create a rank 1 array
print(type(a))            # Prints "<class 'numpy.ndarray'>"
print(a.shape)            # Prints "(3,)"
print(a[0], a[1], a[2])   # Prints "1 2 3"
a[0] = 5                  # Change an element of the array
print(a)                  # Prints "[5, 2, 3]"

b = np.array([[1,2,3],[4,5,6]])    # Create a rank 2 array

#1 2 3
#4 5 6
# reference elements counting from 0
# so b[1, 2] is row 1 (2nd row) column 2 (3rd column)
#so if you print b[1, 2] you get 6
print("b[1, 2] follows")
print(b[1, 2])

print(b.shape)                     # Prints "(2, 3)" 2 rows 3 columns
print(b[0, 0], b[0, 1], b[0, 2])   # Prints "1 2 3"
print(b[1, 0], b[1, 1], b[1, 2])   # Prints "4 5 6"
print(b[0, 0], b[0, 1], b[1, 0])   # Prints "1 2 4"

矩阵的正常数学表示如下所示:

img/515548_1_En_1_Figa_HTML.jpg

这就是我们在前面的代码中使用以下代码行定义的内容:

b = np.array([[1,2,3],[4,5,6]])    # Create a rank 2 array

矩阵运算可以通过看现实生活中的例子来理解。以下是为一家电脑公司工作的三个人的表格。第一张表显示了每个人一个月销售多少台笔记本电脑和多少台打印机。

店内销售

Person     Laptops     Printers
Joe         4              5
Mary        6              7
Jen         7              9

下表显示了每个人在网上销售了多少台笔记本电脑和打印机。

在线销售

Person     Laptops     Printers
Joe           6           22
Mary          21          24
Jen           41          17

这些表可以用如下所示的矩阵来表示。我们将第一个矩阵中的每一项与第二个矩阵中的相应项相加,得出第三个矩阵中显示的总数。

img/515548_1_En_1_Figb_HTML.jpg

下表显示了每人售出的笔记本电脑和打印机总数:

总销售额/总销售额

Person    Laptops     Printers
Joe         10            27
Mary        27            31
Jen         48            26

如果每个人的总销售额在下个月翻了一番,我们可以将他们当前的总销售额乘以 2,如下所示:

img/515548_1_En_1_Figc_HTML.jpg

我们现在查看他们第一个月的总额,并有另一个包含笔记本电脑和打印机成本的表。

销售总额

Person      Laptops     Printers           Cost/Item list with cost
Joe          10          27                    Laptop          200
Mary         27          31                    Printer          25
Jen          48          26

我们可以计算出每个人为公司赚了多少钱,方法是用笔记本电脑的总销量乘以成本。然后,我们将他们的打印机销售总数乘以其成本,然后将两者相加。该表及其相应的矩阵表示如下所示:

             Sales Cost
Joe         10x200 + 27x25 = 2975
Mary        27x200 + 31x25 = 3875
Jen         48x200 + 26x25 = 4775

矩阵相乘是有规律的。第一个矩阵的列数必须等于第二个矩阵的行数。

所以如果我们说一个矩阵是 2×3(两行三列),那么它可以乘以一个 3×2 或者一个 3×3 或者一个 3.4 等等。矩阵。它不能乘以 2×3 或 2×4 或 4×2 或 4×3 等。

img/515548_1_En_1_Figd_HTML.jpg

在上图的乘法中,我们看到它是(3x2) x (2x1)产生一个(3x1)矩阵。

数字计算

清单 1-1 到 1-5 是一些用矩阵展示基本 numpy 计算的程序。

添加两个 2x2 矩阵。

import numpy as np

a = np.array(([3,1],[6,4]))

b = np.array(([1,8],[4,2]))

c = a + b

print('matrix a is')
print(a)
print('matrix b is')
print(b)
print('matrix c is')
print(c)

Listing 1-1numpmat.py

这输出

matrix a is
[[3 1]
 [6 4]]
matrix b is
[[1 8]
 [4 2]]
matrix c is
[[ 4  9]
 [10  6]]

将一个 2x3 矩阵添加到另一个 2x3 矩阵中。

import numpy as np

a = np.array(([1,2,3],[4,5,6]))

b = np.array(([3,2,1],[6,5,4]))

d = a + b

c = 2*a

print('matrix a is')
print(a)
print('matrix b is')
print(b)
print('matrix d is')
print(d)
print('matrix c is')
print(c)

Listing 1-2numpmat2.py

这输出

matrix a is
[[1 2 3]
 [4 5 6]]
matrix b is
[[3 2 1]
 [6 5 4]]
matrix d is
[[ 4  4  4]
 [10 10 10]]
matrix c is
[[ 2  4  6]
 [ 8 10 12]]

将一个 2x2 矩阵添加到一个 2x2 矩阵,两个都是浮点型。

import numpy as np

a = np.array(([3.1,1.2],[6.3,4.5]))

b = np.array(([1.3,8.6],[4.9,2.8]))

c = a + b

print('matrix a is')
print(a)
print('matrix b is')
print(b)
print('matrix c is')
print(c)

Listing 1-3numpmat3.py

这输出

matrix a is
[[3.1 1.2]
 [6.3 4.5]]
matrix b is
[[1.3 8.6]
 [4.9 2.8]]
matrix c is
[[ 4.4  9.8]
 [11.2  7.3]]

将一个 3x2 矩阵乘以一个 2x1 矩阵。

import numpy as np

a = np.array(([1,2],[4,5],[6,8]))

b = np.array(([3],[6]))

c = np.matmul(a,b) #matmul is the numpy function for multiplying matrices

print('matrix a is')
print(a)
print('matrix b is')
print(b)
print('matrix c is')
print(c)

Listing 1-4numpmat4.py

这输出

matrix a is
[[1 2]
 [4 5]
 [6 8]]
matrix b is
[[3]
 [6]]
matrix c is
[[15]
 [42]
 [66]]

将一个 3×2 的矩阵乘以一个 2×3 的矩阵。

如果您是用笔和纸手动完成的,您应该这样做:

img/515548_1_En_1_Fige_HTML.jpg

注意你手工做乘法的方式,第一行 x 第一列,第一行 x 第二列,第一行 x 第三列,然后第二行,然后第三行。当然,如果你使用 numpy 的 matmul 函数,这一切都是为你做的。

import numpy as np

a = np.array(([1,2],[3,4],[5,6]))

b = np.array(([7,8,9],[10,11,12]))

c = np.matmul(a,b)

print('matrix a is')
print(a)
print('matrix b is')
print(b)
print('matrix c is')
print(c)

Listing 1-5numpmat5.py

这输出

matrix a is
[[1 2]
 [3 4]
 [5 6]]
matrix b is
[[ 7  8  9]
 [10 11 12]]
matrix c is
[[ 27  30  33]
 [ 61  68  75]
 [ 95 106 117]]

本节探讨了 Python 中重要的数字数学函数。

数学图形函数

与我们在程序中包含 numpy 库类似,我们可以包含名为“matplotlib.pyplot”的图形绘制库,这样我们就可以用代码访问图形函数库

import matplotlib.pyplot as plt

在我们的程序中,这使得 plt 成为指向 matplotlib.pyplot 的指针。

您可以使用“pip”指令安装 matplotlib

pip install matplotlib

这里的程序将绘制一张人们在考试中得分的图表。

这个函数的代码在文件 mp1a.py 中:

mp1a.py
import matplotlib.pyplot as plt
# x values:
marks = list(range(0, 100, 10)) #marks (x values) divided into equal values up to 100
print(marks) # write the values calculated by the previous instruction

这产生了

[0, 10, 20, 30, 40, 50, 60, 70, 80, 90]
 # y values:
people = [4, 7, 9, 17, 22, 25, 28, 18, 6, 2]
# label the axes
plt.xlabel('marks')
plt.ylabel('people')
plt.plot(marks, people)
plt.show()

和输出

[0, 10, 20, 30, 40, 50, 60, 70, 80, 90]

这些绘制了如图 1-1 所示的图表。

img/515548_1_En_1_Fig1_HTML.png

图 1-1

绘制(x,y)点的示例

我们从图表中看到,大多数人的分数在 30 到 70 之间,这是你所期望的。几个得了低分,只有几个得了高分。

下一个程序 mp2aa.py 在相同的轴上绘制了两个图形。这里我们画出了女性和男性的考试分数。我们用一种颜色描绘女性,用另一种颜色描绘男性。

这个函数的代码在文件 mp2aa.py 中:

mp2aa.py
import matplotlib.pyplot as plt
# x values:
marks = list(range(0,100,10)) #marks (x values) divided into equal values up to 100
# y values (number of students whose marks lie within each x range):
male = [4, 7, 9, 17, 22, 25, 28, 18, 6, 2]
female = [2, 5, 8, 13, 28, 25, 23, 20, 18, 12]
plt.xlabel('marks')
plt.ylabel('number of students')

plt.title('Comparison of male / female examination scores')
#plot the female graph
plt.plot(marks, female, label="female")
plt.plot(marks, female, "ob")
#plot the male graph
plt.plot(marks, male, label="male")
plt.plot(marks, male, "or")

plt.legend()
plt.show()

这产生了如图 1-2 所示的下图。

img/515548_1_En_1_Fig2_HTML.png

图 1-2

绘制两个图形的示例

下一个程序 ml1pj.py 在相同的轴上绘制了三个图形。这里,我们画出 y = sin(x),y = 2sin(x),y = cos(x)。我们用不同的颜色画出每一个。

这演示了 matplotlib 可用的一些数学函数。

这个函数的代码在 ml1pj.py 文件中:

ml1pj.py
import matplotlib.pyplot as plt
import numpy as np
X = np.linspace(0, 2 * np.pi, 50, endpoint=True) # set x values as multiples of pi

F1 = 2 * np.sin(X) # y = 2sin(x)
F2 = np.sin(X) #y = sin(x)
F3 = np.cos(X) #y = cos(x)

plt.plot(X, F1, color="blue", linewidth=2, linestyle="-")
plt.plot(X, F2, color="red", linewidth=2, linestyle="-")
plt.plot(X, F3, color="green", linewidth=2, linestyle="-")

plt.plot(X, F1, label="2sin(x)")
plt.plot(X, F2, label="sin(x)")
plt.plot(X, F3, label="cos(x)")

plt.legend()
plt.show()

这就产生了图 1-3 。

img/515548_1_En_1_Fig3_HTML.png

图 1-3

绘制三幅图

本节展示了 matplotlib 在 Python 中的重要性。

用户编写的函数

除了有为你定义的函数(比如在 numpy 或 Matlab 中),你还可以为自己定义函数。

函数的格式如下

def funcname(arguments)

其中 funcname 是您希望调用函数的任何内容,参数是您需要传递给函数的信息。对于不同的函数调用,参数的实际内容可能会有所不同。

如果你想返回一个值给函数的调用者,你可以使用 return 命令。

这个函数的代码在文件 tst16b.py 中:

# Define our 3 functions
def func1():
    #basic function to output a string
    print("This is from func1")

def func2(name, pretax):
    # calculates a person's salary after tax is taken
   aftertax = pretax * 0.85
   print("%s This is from func1, Your salary after tax is %f"%(name,aftertax))

def func3(first,second,third):
    # simple arithmetic calculation on the 3 numbers submitted
    return 3.5*first + second/2 - third

# call func1
func1()

#call func2
func2("Bernard", 23.78)

#call func3
x = func3(1,2,3)
print(x)

这输出

This is from func1
Bernard This is from func1, Your salary after tax is 20.213000
1.5

实际上,您将在程序中定义的函数将比以前的函数更复杂,因为在前面的情况下,在程序的主体中编写代码本身与调用函数一样容易。

文件存取

在 Python 程序中,我们可以创建、读取、写入、更新和删除文件。

我们将使用 matplotlib 中的图形绘制函数,如“数学图形函数”一节所述同样,要在 Python 程序中使用 matplotlib,我们需要在程序的开头使用下面一行代码。

以下程序 re11pjc.py 读取 pjfiley.txt 文件,该文件包含以下 11 行数据:

#pjfiley.txt
a#This is my linexxxxxxxxxxxxxx
b#second linexxxx
c#third linexx
d#fourth linexxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
e#fifth line
f#sixth
g#seventh
h#eighth
i#nineth
j#tenth
k#eleventh

程序打开文件并在“fhand”中存储一个指向它的指针。然后,它执行一个 for 循环,从文件中读取每一行,并将当前行存储在“line”中。该程序的目标是找到行首带有字符“k”的行。当它找到这个时,它打印出该行的其余部分。当遇到“#”字符时,它使用函数“line.split”来拆分行。然后,将“k”存储在“a”中,其余的行存储在“b”中。

#re11pjc.py
fhand = open('pjfiley.txt')
# read each line from the file
for line in fhand:
   if line[0]=='k': # is the first character of the current line 'k'
      a,b = line.split('#') # split the line into two parts, separated by the '#' in the line
      print(b)

fhand.close()

this prints
eleventh

因为以 k 开头的行是 k #第 11 行,所以当我们在#的任一侧拆分它时,我们将“k”存储在存储位置“a”中,将“第 11 行”存储在存储位置“b”中。

以下程序读取 Peoplex.txt 文件,该文件包含以下内容:

#Peoplex
a-Jones-37-accountant

b-Smith-42-HR

c-Allen-28-Secretary

d-Bradley-26-Programmer

e-Edwards-41-Programmer

f-King-35-S/W engineer

g-Price-39-H/W engineer

h-Roberts-52-Manager

i-Foster-44-Analyst

j-Shannon-24-Programmer

k-Lewis-27-Receptionist

这是一个包含公司员工信息的数据文件。每条生产线供一名工人使用。该行的第一个字符是唯一标识工人的参考字符。该行中的其他字段标识他们的姓名、年龄和职务。每个字段由“-”字符分隔,我们使用 line.split()函数来分隔字段。

下面的程序通读文件,查找用户指定的 ID 为的工人。当程序找到它时,它会将该行分割成单独的字段。我们可以通过连接这些字段来打印出这些数据。

#re11pjd.py
fhand = open('Peoplex.txt')

# user is asked to enter the ID character of the line they wish to read.
n = input('Enter an ID: ')

for line in fhand:
   if line[0]==n:
      a,b,c,d = line.split('-') # specified line is found so split it into 4 components
      print(b+' '+c+' '+d) # concatenate the 2nd, 3rd and 4th components

fhand.close()

如果我们输入“d ”,就会得到输出

Enter an ID: d
Bradley 26 Programmer
Amend a field in one of the lines

pjfilezi.bin 文件包含以下数据:

a-Jones-37-accountant
b-Smith-33-welder
c-Allen-28-Secretary
d-Bradley-26-Programmer

我们想修改其中一个条目的年龄和工作描述。

下面的代码可以做到这一点。我们想使用一种方法来更新文件。该方法读取文件并将每一行写入另一个文件。完成后,它会将新文件复制到原始文件中。

#re11pjdga.py
finphand = open('pjfilezi.bin','r') # input file
fouthand = open('pjfilezo.bin','w') # output file
#ask the user to enter the ID for the row to be amended.
n = input('Enter an ID: ')
#We want to update the age and job description to the following values.
age = input('Enter age: ')
desc = input('Enter job description: ')
# find the correct line from the ID entered
for line in finphand:
   if line[0]==n:
       # we have found the correct line
      a,b,c,d = line.split('-') # split the line into its 4 components.
      print(a) #ID
      print(b) #name
      print(c) #age
      print(d) #occupation
      print(b+' '+c+' '+d) #concatenate and print the 2nd, 3rd and 4th
# update
      c=age
      d=desc
      print(b+' '+c+' '+d) # print the amended line
      line=(a+'-'+b+'-'+c+'-'+d+'\n') # store the amended line
      fouthand.write(line) # write the line to the output file

   else:
     # not found the line to be amended so write this line to the output file
      fouthand.write(line)

fouthand.close()
finphand.close()

#close and reopen the files and copy the output file to the input file
file1 = open("pjfilezo.bin", "r")
file2 = open("pjfilezi.bin", "w")
l = file1.readline()
while l:
   file2.write(l)
   l = file1.readline()
file1.close()
file2.close()

如果我们运行程序,输入“c”作为 ID,然后将年龄改为 32 岁,工作描述改为焊工,我们得到

Enter an ID: c
Enter age: 32
Enter job description: welder
c
Allen
28
Secretary

Allen 28 Secretary

Allen 32 welder

下面的程序从文件中读取数据,并使用 matplotlib 绘制图表。

在程序的不同阶段打印不同的存储位置,以便用户可以监视程序正在做什么。这些显示在图表之后。以下程序从 output.txt 文件中读取以下内容:

2.4*x+7.9
0, 20

第一行是要绘制的方程(y = 2.4 * x + 7.9)。

第二行是在绘图中使用的 x 值的范围。

# readfilec2.py###################

该程序读取这两行:

import matplotlib.pyplot as plt
import numpy as np

fhand = open('output.txt','r')
lines = [' ',' ']
count = 0
#store the two lines in lines[0] and lines[1]
for line in fhand:
    lines[count] = line
    count = count + 1
print('lines[0] The first line read from output.txt')
print(lines[0])
print('lines[1] The second line read from output.txt')
print(lines[1])
#strip the newline character from each of the lines
l1 = lines[0].rstrip('\n')
l2 = lines[1].rstrip('\n')
print('l1 The first line read from output.txt with newline character removed ')
print(l1)
print('l2 The second line read from output.txt with newline character removed ')
print(l2)

Import matplot lib is required only when we use this function, try to put the above blocks of code in different modules and import all into another file and plot
def graph(formula, x_range):
# function to plot the graph
    x = np.array(x_range)
    y = eval(formula) # evaluate the formula to give the y-values
    plt.xlabel('x values')
    plt.ylabel('y values')
    plt.title('Line Graph ')
    plt.plot(x, y)
    plt.show()
#get the second line and store the two points on aint and bint
aint=int(l2[3])
#b = 0
bint=int(l2[0])
# call the graph-plotting function with the equation and range as parameters
graph(l1, range(bint, aint))

程序产生如图 1-4 所示的图形。

img/515548_1_En_1_Fig4_HTML.png

图 1-4

y = 2.4x + 7.9 的曲线图

该程序输出以下内容:

lines[0] The first line read from output.txt
2.4*x+7.9

lines[1] The second line read from output.txt
0, 20

l1 The first line read from output.txt with newline character removed
2.4*x+7.9
l2 The second line read from output.txt with newline character removed
0, 20

回归

下一个程序绘制一条回归线和回归计算中使用的四个点。

回归是一系列点对一条直线的近似。所以这里的点是(1,2),(2,5),(3,6),(4,9)。这些点的回归线已经计算为 y = 0 + 2.2x。这些信息已经存储在程序读取的三个文件中。直线和四个点被绘制到图表上来说明回归。

下面的程序从三个文件中获取数据。

第一个文件包含四个点的 x 和 y 坐标。

第二个包含点的回归线。

第三是点数。

在程序的不同阶段打印不同的存储位置,以便用户可以监视程序正在做什么。这些显示在图表之后。

下列程序读取的文件及其内容:

capm.bin
1.000000     2.000000
2.000000     5.000000
3.000000     6.000000
4.000000     9.000000

capm2.bin
0.000000+2.200000*x

capm2cnt.bin
4

该程序使用两种方法访问文件:

fhand = open('capm2.bin','r')

z = np.loadtxt("capm2cnt.bin")
#readfile7a2.py
import matplotlib.pyplot as plt
import numpy as np

fhand = open('capm2.bin','r') #file containing the calculated regression equation
# 'capm.bin' is the file containing the coordinate points
# 'capm2cnt.bin' is the # file containing the number of coordinate points

z = np.loadtxt("capm2cnt.bin") # read the number of points and store in z
print("Data read from capm2cnt.bin")
print("z follows")
print(z)
a = z # this is the number of coordinate points
zint = int(a) # convert the number to an int
print("zint follows")
print(zint)
count = 0
y = np.loadtxt("capm.bin") # read the 4 points and store in y
print("Data read from capm.bin")
print(y)
# y now contains the x and y values of the 4 points
#[[1\. 2.]
# [2\. 5.]
# [3\. 6.]
# [4\. 9.]]

#zeroise the two arrays using zint as the count of points
xvals = [0]*zint
yvals = [0]*zint

print("xvalsfirst")
print(xvals)
print("yvalsfirst")
print(yvals)
#separate the x and y values
for x in range(zint):
    a,b = y[x]
    xvals[x] = a
    yvals[x] = b

print("xvals")
print(xvals)
print("yvals")
print(yvals)

plt.plot(xvals, yvals, "ob")
# read the calculated regression equation from 'capm2.bin' (pointed to by fhand)
count = 0
for line in fhand:
    line = line.rstrip() #rstrip() strips space characters from end of string
print(line) # the calculated regression equation

# set the x values for the graph

x = np.linspace(-5,5,10)
print('x follows')
print(x)
print('line follows')
print(line)
#line is 0.000000+2.200000*x

a = 'y='
b = a + line # b is y = 0.000000+2.200000*x

print(b)
# line contains the regression equation
# The eval command carries out the function contained in 'line'. In this case it is 'y = 0.0 + 2.2*x'
# It takes the values of x from the x = np.linspace(-5,5,10) code above and calculates y values.
y= eval(line) # use the regression equation to calculate the y-values from the x-values above
print('y follows')
print(y)

plt.plot(x, y, '-r', label=b)
#Plot the regression line and the four points
plt.title(b)
plt.xlabel('x', color='#1C2833')
plt.ylabel('y', color='#1C2833')
plt.legend(loc='upper left')
plt.grid()
plt.show()

程序产生如图 1-5 所示的图形。

img/515548_1_En_1_Fig5_HTML.png

图 1-5

y = 0.0 + 2.2x 的图

从图中可以看出,所有点都靠近直线。我们可以用一个数字来告诉我们这些点离直线有多近,而不仅仅是说这些点离直线很近,离直线相当近,或者离直线不是很近。这个号码有名字。它被称为“积矩相关系数”,通常缩写为 PMCC。在前面的例子中,如果点在直线上,PMCC 就是 1。当它们接近直线时,PMCC 大约为 0.92145。我们将在本书的后面讨论 PMCC。

该程序的输出如下:

从 capm2cnt.bin 读取的数据

z follows
4.0
zint follows
4

从 capm.bin 读取的数据

[[1\. 2.]
 [2\. 5.]
 [3\. 6.]
 [4\. 9.]]
xvalsfirst
[0, 0, 0, 0]
yvalsfirst
[0, 0, 0, 0]
xvals
[1.0, 2.0, 3.0, 4.0]
yvals
[2.0, 5.0, 6.0, 9.0]
0.000000+2.200000*x
x follows
[-5\.         -3.88888889 -2.77777778 -1.66666667 -0.55555556  0.55555556
  1.66666667  2.77777778  3.88888889  5\.        ]
line follows
0.000000+2.200000*x
y=0.000000+2.200000*x
y follows
[-11\.          -8.55555556  -6.11111111  -3.66666667  -1.22222222
   1.22222222   3.66666667   6.11111111   8.55555556  11\.        ]

本节探讨了 Python 中的文件处理。

摘要

本章展示了 Python 编程的基础。它展示了不同的数据类型、它们是如何定义的以及它们的属性、执行数学和图形功能的 numpy 和 matplotlib 链接以及文件处理。

下一章将探索 C 代码的基础和使用。

练习

  1. 执行与我们在 1.1.1 节的例子中对 int 值使用的相同的算术运算

    使用

    V1 = 2

    V2 = 3.5

    V3 = 5.1

    V4 = 6.75

  2. 来自第 1.1.3 节

    创建一个从 1 到 7 的数字列表。打印这个列表,然后使用 for 循环将接下来的 7 个数字(8 到 14)追加到列表中(参见“For 循环”一节)。

    创建包含元素{'a' : \one\,' b' :''two'}的字典。要求用户输入要测试的密钥。使用 for 循环测试该键是否在字典中(参见“For 循环”一节)。输出一条适当的消息,说明您是否找到了它。

    创建一个元组,元素为从 2 到 14 的偶数。使用 for 循环打印出元素(参见“For 循环”一节)。

  3. 来自第 1.1.10 节

    修改文件工人的数据文件程序,创建一个文件,在他们的名字后面也有他们的首字母,并在最后一行加上他们的工资。