无题
python——摘自cs50
hello world!
到目前为止,代码如下所示:
1
2
3
4
5
6
7
8// A program that says hello to the world
int main(void)
{
printf("hello, world\n");
}今天,您会发现编写和编译代码的过程已简化。
例如,上面的代码将在 Python 中呈现为:
1
2
3# A program that says hello to the world
print("hello, world")请注意,分号已消失。
在 C 中,您可能还记得以下代码:
1
2
3
4
5
6
7
8
9
10// get_string and printf with %s
int main(void)
{
string answer = get_string("What's your name? ");
printf("hello, %s\n", answer);
}此代码在 Python 中转换为:
1
2
3
4
5
6# get_string and print, with concatenation
from cs50 import get_string
answer = get_string("What's your name? ")
print("hello, " + answer)您可以通过在终端窗口中执行来编写此代码。然后,您可以通过运行 来执行此代码。请注意符号和 的连接方式。
code hello.py``python hello.py``+``"hello, "``answer
同样,您可以将上述代码实现为:
1
2
3
4
5
6# get_string and print, with format strings
from cs50 import get_string
answer = get_string("What's your name? ")
print(f"hello, {answer}")请注意大括号如何允许函数插入出现在其中的此类内容。
print``answer``answer
类型
Python 中的数据类型不需要显式声明。例如,您看到了上面的字符串,但我们不必告诉解释器是这种情况:它自己知道。
answer
在 Python 中,常用的类型包括:
1
2
3
4bool
float
int
str请注意,缺少 和。Python 将处理应该对较大和较小的数字使用哪种数据类型。
long``double
Python 中的其他一些数据类型包括:
1
2
3
4
5range
list
tuple
dict
set这些数据类型中的每一种都可以在 C 中实现,但在 Python 中它们可以更简单地实现。
拼写
为了说明这种简单性,让我们在终端窗口中键入“代码 dictionary.py”并编写如下代码:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30# Words in dictionary
words = set()
def check(word):
"""Return true if word is in dictionary else false"""
if word.lower() in words:
return True
else:
return False
def load(dictionary):
"""Load dictionary into memory, returning true if successful else false"""
file = open(dictionary, "r")
for line in file:
word = line.rstrip()
words.add(word)
file.close()
return True
def size():
"""Returns number of words in dictionary if loaded else 0 if not yet loaded"""
return len(words)
def unload():
"""Unloads dictionary from memory, returning true if successful else false"""
return True请注意,上面有四个函数。在函数中,如果 a 在 中,则返回 。比用 C 语言实现容易得多!同样,在函数中打开字典文件。对于该文件中的每一行,我们将该行添加到 .使用 ,从添加的单词中删除尾随的新行。 只需返回 的 或 长度。 只需要返回,因为 Python 自行处理内存管理。
check``word``words``True``load``words``rstrip``size``len``words``unload``True
上面的代码说明了为什么存在高级语言:简化并允许您更轻松地编写代码。
但是,速度是一种权衡。因为 C 允许你(程序员)做出有关内存管理的决策,所以它可能比 Python 运行得更快——这取决于你的代码。虽然 C 只运行你的代码行,但当你调用 Python 的内置函数时,Python 会运行所有隐藏的代码。
您可以在 Python 文档中了解有关函数的更多信息
图像识别
- 许多库是由Python的贡献者编写的。
- 您可以在自己的代码中使用这些库。
- 例如,您可以简单地使用 Python 库(如 .
PIL
- David提供了一个使用Python和第三方库进行面部识别的演示。
CS50 图书馆
与C一样,CS50库可以在Python中使用。
以下功能将特别有用:
1
2
3get_float
get_int
get_string您还可以选择仅从 CS50 库中导入特定函数,如下所示:
1
from CS50 import get_float, get_int, get_string
条件
在 C 语言中,你可能还记得这样的程序:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25// Conditionals, Boolean expressions, relational operators
int main(void)
{
// Prompt user for integers
int x = get_int("What's x? ");
int y = get_int("What's y? ");
// Compare integers
if (x < y)
{
printf("x is less than y\n");
}
else if (x > y)
{
printf("x is greater than y\n");
}
else
{
printf("x is equal to y\n");
}
}
在 Python 中,它如下所示:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
# Conditionals, Boolean expressions, relational operators
from cs50 import get_int
# Prompt user for integers
x = get_int("What's x? ")
y = get_int("What's y? ")
# Compare integers
if x < y:
print("x is less than y")
elif x > y:
print("x is greater than y")
else:
print("x is equal to y")请注意,不再有大括号。而是使用缩进。其次,语句中使用冒号。此外,替换 .和语句中也不再需要括号。
if``elif``else if``if``elif
变量
- 变量声明也得到了简化。在 C 语言中,您可能有 .在 Python 中,同样的一行将读作 .无需声明变量的类型。
int counter = 1;``counter = 1
- Python 倾向于递增 1,失去了 C 语言中键入 .
counter += 1``counter++
循环
Python 中的循环与 C 非常相似。您可能还记得 C 中的以下代码:
1
2
3
4
5
6
7
8
9
10
11
12
13// Demonstrates while loop
int main(void)
{
int i = 0;
while (i < 3)
{
printf("meow\n");
i++;
}
}在 Python 中,此代码显示为:
1
2
3
4
5
6# Demonstrates while loop
i = 0
while i < 3:
print("meow")
i += 1for
循环可以在 Python 中实现,如下所示:1
2
3
4# Better design
for i in range(3):
print("meow")类似地,可以将上面的代码表示为:
1
2
3
4
5
6
7
8
9
10
11
12
13# Abstraction with parameterization
def main():
meow(3)
# Meow some number of times
def meow(n):
for i in range(n):
print("meow")
main()请注意,使用一个函数来抽象出喵喵叫。
计算器
我们可以像在 C 中所做的那样实现一个简单的计算器。 在终端窗口中键入并编写如下代码:
code calculator.py
1
2
3
4
5
6
7
8
9
10
11
12# Addition with int [using get_int]
from cs50 import get_int
# Prompt user for x
x = get_int("x: ")
# Prompt user for y
y = get_int("y: ")
# Perform addition
print(x + y)请注意 CS50 库是如何导入的。然后,并从用户那里收集。最后,打印结果。请注意,在 C 程序中可以看到的功能完全消失了!虽然可以使用一个功能,但它不是必需的。
x``y``main``main
可以卸下CS50库的训练轮。按如下方式修改代码:
1
2
3
4
5
6
7
8
9
10# Addition with int [using input]
# Prompt user for x
x = input("x: ")
# Prompt user for y
y = input("y: ")
# Perform addition
print(x + y)请注意执行上述代码如何导致奇怪的程序行为。为什么会这样?
你可能已经猜到解释器理解并且是字符串。您可以通过使用函数来修复代码,如下所示:
x``y``int
1
2
3
4
5
6
7
8
9
10# Addition with int [using input]
# Prompt user for x
x = int(input("x: "))
# Prompt user for y
y = int(input("y: "))
# Perform addition
print(x + y)请注意 和 的输入是如何传递给将其转换为整数的函数的。
x``y``int
我们可以扩展计算器的功能。按如下方式修改代码:
1
2
3
4
5
6
7
8
9
10
11# Division with integers, demonstration lack of truncation
# Prompt user for x
x = int(input("x: "))
# Prompt user for y
y = int(input("y: "))
# Divide x by y
z = x / y
print(z)请注意,执行此代码会产生一个值,但是如果您在看到更多数字之后会看到我们面临浮点不精确性。
.333333
We can reveal this imprecision by modifying our codes slightly:
1
2
3
4
5
6
7
8
9
10
11# Floating-point imprecision
# Prompt user for x
x = int(input("x: "))
# Prompt user for y
y = int(input("y: "))
# Divide x by y
z = x / y
print(f"{z:.50f}")Notice that this code reveals the imprecision. Python still faces this issue, just as C does.
比较
在C语言中,当我们想要比较两个值时,我们面临着挑战。请考虑以下代码:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25// Conditionals, Boolean expressions, relational operators
int main(void)
{
// Prompt user for integers
int x = get_int("What's x? ");
int y = get_int("What's y? ");
// Compare integers
if (x < y)
{
printf("x is less than y\n");
}
else if (x > y)
{
printf("x is greater than y\n");
}
else
{
printf("x is equal to y\n");
}
}在 Python 中,我们可以按如下方式执行上述操作:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15# Conditionals, Boolean expressions, relational operators
from cs50 import get_int
# Prompt user for integers
x = get_int("What's x? ")
y = get_int("What's y? ")
# Compare integers
if x < y:
print("x is less than y")
elif x > y:
print("x is greater than y")
else:
print("x is equal to y")请注意,CS50 库已导入。此外,声明中还存在细微的更改。
if
进一步查看比较,请考虑以下 C 代码:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20// Logical operators
int main(void)
{
// Prompt user to agree
char c = get_char("Do you agree? ");
// Check whether agreed
if (c == 'Y' || c == 'y')
{
printf("Agreed.\n");
}
else if (c == 'N' || c == 'n')
{
printf("Not agreed.\n");
}
}以上可以按如下方式实现:
1
2
3
4
5
6
7
8
9
10
11
12# Logical operators
from cs50 import get_string
# Prompt user to agree
s = get_string("Do you agree? ")
# Check whether agreed
if s == "Y" or s == "y":
print("Agreed.")
elif s == "N" or s == "n":
print("Not agreed.")请注意,C 中使用的两个竖线替换为 。事实上,人们经常喜欢Python,因为它更容易被人类阅读。另外,请注意,这在 Python 中不存在。而是使用 s。
or``char``str
相同代码的另一种方法如下:
1
2
3
4
5
6
7
8
9
10
11
12# Logical operators, using lists
from cs50 import get_string
# Prompt user to agree
s = get_string("Do you agree? ")
# Check whether agreed
if s in ["y", "yes"]:
print("Agreed.")
elif s in ["n", "no"]:
print("Not agreed.")请注意我们如何能够表达多个关键字,例如 和 。
y``yes
面向对象编程
到目前为止,我们在本课程中的程序一直是线性的:顺序的。
某些类型的值不仅可以在其中具有属性或属性,还可以具有函数。在 Python 中,这些值被称为对象
在 C 中,我们可以创建一个,您可以在单个自创建数据类型中关联多个变量。在 Python 中,我们可以做到这一点,也可以在自己创建的数据类型中包含函数。当函数属于特定对象时,它被称为方法。
struct
例如,在Python中有一个内置的方法。因此,您可以按如下方式修改代码:
strs
1
2
3
4
5
6
7
8
9
10
11
12# Logical operators, using lists
from cs50 import get_string
# Prompt user to agree
s = get_string("Do you agree? ")
# Check whether agreed
if s.lower() in ["y", "yes"]:
print("Agreed.")
elif s.lower() in ["n", "no"]:
print("Not agreed.")请注意我们如何能够表达多个关键字,例如并将任何用户输入转换为小写。
y``yes
这可以进一步简化为:
1
2
3
4
5
6
7
8
9
10
11
12
13
14# Logical operators, using lists
from cs50 import get_string
# Prompt user to agree
s = get_string("Do you agree? ")
s = s.lower()
# Check whether agreed
if s in ["y", "yes"]:
print("Agreed.")
elif s in ["n", "no"]:
print("Not agreed.")请注意 的旧值是如何被 的结果覆盖的。
s``s.lower()
在本课程中,我们只会触及 Python 的表面。因此,随着您的继续,Python 文档将特别重要。
您可以在 Python 文档中了解有关字符串方法的更多信息
猫叫声
从几周前返回,回顾以下代码:
meow.c
1
2
3
4
5
6
7
8
9
10
11
12
13// Demonstrates while loop
int main(void)
{
int i = 0;
while (i < 3)
{
printf("meow\n");
i++;
}
}以上可以在 Python 中实现为:
1
2
3
4
5
6# Demonstrates while loop
i = 0
while i < 3:
print("meow")
i += 1同样,使用循环,我们可以编写如下代码:
for
1
2
3
4# Better design
for i in range(3):
print("meow")正如我们今天早些时候所暗示的,您可以使用函数进一步改进此代码。按如下方式修改代码:
1
2
3
4
5
6
7
8
9
10
11
12# Abstraction
def main():
for i in range(3):
meow()
# Meow once
def meow():
print("meow")
main()请注意,该函数抽象出该语句。此外,请注意,该函数显示在文件的顶部。在文件底部,调用该函数。按照惯例,你应该在 Python 中创建一个函数。
meow``print``main``main``main
实际上,我们可以在函数之间传递变量,如下所示:
1
2
3
4
5
6
7
8
9
10
11
12
13# Abstraction with parameterization
def main():
meow(3)
# Meow some number of times
def meow(n):
for i in range(n):
print("meow")
main()注意现在如何采用变量 。在函数中,您可以调用并传递一个类似的值。然后,利用循环中的值。
meow``n``main``meow``3``meow``n``for
阅读上面的代码,请注意你作为一个C程序员,如何能够非常容易地理解上面的代码。虽然有些约定不同,但您之前学习的构建块在这种新的编程语言中非常明显。
马里奥
回想一下几周前我们面临的挑战,即在彼此之上建造三个方块,就像在马里奥中一样。
在 Python 中,我们可以实现类似这样的东西,如下所示:
1
2
3
4# Prints a column of 3 bricks with a loop
for i in range(3):
print("#")在 C 语言中,我们有一个循环的优势。但是,在Python中,使用循环是惯例,因为Python没有循环。您可以在名为 的文件中编写如下代码:
do-while``while``do while``mario.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19# Prints a column of bricks, using a helper function to get input
from cs50 import get_int
def main():
height = get_height()
for i in range(height):
print("#")
def get_height():
while True:
n = get_int("Height: ")
if n > 0:
return n
main()请注意,一旦为函数赋值,函数中的范围就会无处不在。另请注意,按照惯例,函数之间有双空格。
n``get_height
我们可以拿走 CS50 库的训练轮,如下所示:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19# Prints a column of bricks, catching exceptions
def main():
height = get_height()
for i in range(height):
print("#")
def get_height():
while True:
try:
n = int(input("Height: "))
if n > 0:
return n
except ValueError:
print("Not an integer")
main()请注意,用于尝试转换为整数。如果无法执行此操作,则会输出错误。
try``n
请考虑下图:
在 Python 中,我们可以通过修改您的代码来实现,如下所示:
1
2
3
4
5# Prints a row of 4 question marks with a loop
for i in range(4):
print("?", end="")
print()请注意,您可以重写函数的行为,使其与上次打印保持在同一行上。
print
与以前的迭代类似,我们可以进一步简化这个程序:
1
2
3# Prints a row of 4 question marks without a loop
print("?" * 4)请注意,我们可以利用 print 语句乘以重复次数。
*``4
一大块砖呢?
要实现上述内容,您可以按如下方式修改代码:
1
2
3
4
5
6# Prints a 3-by-3 grid of bricks with loops
for i in range(3):
for j in range(3):
print("#", end="")
print()注意一个循环如何存在于另一个循环中。该语句在每行砖块的末尾添加一个新行。
for``print
您可以在 Python 文档中了解有关该函数的更多信息
print
分数
list
s是Python中的一个数据结构。list
其中内置了方法或函数。例如,请考虑以下代码:
1
2
3
4
5
6
7
8
9
10
11
12
13# Averages three numbers using a list and a loop
from cs50 import get_int
# Get scores
scores = []
for i in range(3):
score = get_int("Score: ")
scores.append(score)
# Print average
average = sum(scores) / len(scores)
print(f"Average: {average}")请注意,您可以使用内置方法,从而可以将分数添加到列表中。另请注意,我们使用函数添加列表中的所有元素。
append``append``sum
您甚至可以使用以下语法:
1
2
3
4
5
6
7
8
9
10
11
12
13# Averages three numbers using a list and a loop with + operator
from cs50 import get_int
# Get scores
scores = []
for i in range(3):
score = get_int("Score: ")
scores += [score]
# Print average
average = sum(scores) / len(scores)
print(f"Average: {average}")请注意,用于将分数追加到列表中。在这种情况下,我们用方括号括起来,因为只有 a 可以使用 or 添加到另一个。
+=``score``list``list``+``+=
您可以在 Python 文档中了解有关列表的更多信息
您还可以在 Python 文档中了解更多信息
len
大写
同样,请考虑以下代码:
1
2
3
4
5
6
7# Uppercases string one character at a time
before = input("Before: ")
print("After: ", end="")
for c in before:
print(c.upper(), end="")
print()请注意,每个字符一次一个大写。
Python 有一个内置的 s 方法。您可以按如下方式修改代码:
str
1
2
3
4
5# Uppercases string all at once
before = input("Before: ")
after = before.upper()
print(f"After: {after}")请注意,该方法用于一次将整个字符串大写。
upper
迎接
与 C 一样,您也可以使用命令行参数。请考虑以下代码:
1
2
3
4
5
6
7
8# Prints a command-line argument
from sys import argv
if len(argv) == 2:
print(f"hello, {argv[1]}")
else:
print("hello, world")请注意,它是使用格式化字符串打印的,在语句中由 present 表示。
argv[1]``f``print
您可以按如下方式打印所有参数:
argv
1
2
3
4
5
6# Printing command-line arguments, indexing into argv
from sys import argv
for i in range(len(argv)):
print(argv[i])请注意,如果执行,上述内容将不会显示单词,第一个参数将是正在运行的文件的名称。你可以认为这个词类似于我们在 C 中运行程序时。
python``python``./
您可以将列表片段切开。请考虑以下代码:
1
2
3
4
5
6# Printing command-line arguments using a slice
from sys import argv
for arg in argv[1:]:
print(arg)请注意,执行此代码将导致您正在运行的文件的名称被切掉。
您可以在 Python 文档中了解有关该库的更多信息
sys
退出状态
该库还具有内置方法。我们可以使用特定的退出代码退出程序:
sys``sys.exit(i)
1
2
3
4
5
6
7
8
9
10# Exits with explicit value, importing sys
import sys
if len(sys.argv) != 2:
print("Missing command-line argument")
sys.exit(1)
print(f"hello, {sys.argv[1]}")
sys.exit(0)请注意,点表示法用于利用 的内置函数。
sys
搜索
Python也可以用来搜索。在终端窗口中,键入并编写代码,如下所示:
code names.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18# Implements linear search for names
import sys
# A list of names
names = ["Bill", "Charlie", "Fred", "George", "Ginny", "Percy", "Ron"]
# Ask for name
name = input("Name: ")
# Search for name
for n in names:
if n == name:
print("Found")
sys.exit(0)
print("Not found")
sys.exit(1)请注意,此代码起作用。事实上,它实现了线性搜索。
您可以按如下方式利用 Python 的内置功能:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17# Implements linear search for names using `in`
import sys
# A list of names
names = ["Bill", "Charlie", "Fred", "George", "Ginny", "Percy", "Ron"]
# Ask for name
name = input("Name: ")
# Search for name
if name in names:
print("Found")
sys.exit(0)
print("Not found")
sys.exit(1)请注意,使用了介词。Python 了解如何实现较低级别的代码来进行线性搜索。
in
电话簿
回想一下,字典或是键**值对的集合。
dict
您可以在 Python 中实现字典,如下所示:
1
2
3
4
5
6
7
8
9
10
11
12
13# Implements a phone book
from cs50 import get_string
people = {
"Carter": "+1-617-495-1000",
"David": "+1-949-468-2750"
}
# Search for name
name = get_string("Name: ")
if name in people:
print(f"Number: {people[name]}")请注意,字典是使用大括号实现的。然后,该语句搜索以查看 是否在字典中。此外,请注意,在语句中,我们如何使用 的值索引到 People 字典中。非常有用!
if name in people``name``people``print``name
Python已经尽最大努力使用其内置搜索来获得恒定时间。
比较
我们可以在 Python 中实现如下比较:
1
2
3
4
5
6
7
8
9
10
11
s = input("s: ")
t = input("t: ")
if s == t:
print("Same")
else:
print("Different")注意 Python 如何利用 来比较两个变量。此外,请注意,Python 允许您比较两个字符串,而无需像 C 中那样使用指针逐个字符检查字符串。
==
请注意,每个值都是交换的,使用一些非常 Python 语法。
x, y = y, x
.CSV
您还可以利用Python来处理CSV文件。考虑以下程序,称为:
phonebook.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14# Saves names and numbers to a CSV file
import csv
# Get name and number
name = input("Name: ")
number = input("Number: ")
# Open CSV file
with open("phonebook.csv", "a") as file:
# Print to file
writer = csv.writer(file)
writer.writerow([name, number])请注意,利用代码块,在其下方缩进 及其工作,可以防止我们在完成后需要我们的文件。
with``writer``close
通常,CSV 文件具有带有特定名称的列。A 可用于创建 CSV 文件并为每列分配特定名称。请考虑对代码进行以下修改:
DictWriter
1
2
3
4
5
6
7
8
9
10
11
12
13
14# Saves names and numbers to a CSV file using a DictWriter
import csv
# Get name and number
name = input("Name: ")
number = input("Number: ")
# Open CSV file
with open("phonebook.csv", "a") as file:
# Print to file
writer = csv.DictWriter(file, fieldnames=["name", "number"])
writer.writerow({"name": name, "number": number})请注意,和 列在代码的倒数第二行中定义,值在最后一行中添加。
name``number
您可以在 Python 文档中了解有关 Python 中 CSV 文件的更多信息
演讲
使用第三方库,Python可以进行文本到语音转换。
1
2
3
4
5
6
7
8# Says hello to someone
import pyttsx3
engine = pyttsx3.init()
name = input("What's your name? ")
engine.say(f"hello, {name}")
engine.runAndWait()此外,您可以运行以下代码:
1
2
3
4
5
6
7# Says "This was CS50"
import pyttsx3
engine = pyttsx3.init()
engine.say("This was CS50")
engine.runAndWait()
交换
此外,我们可以实现一个交换值的程序,就像我们在 C 中所做的那样。
1
2
3
4
5
6
7
8# Swaps two integers
x = 1
y = 2
print(f"x is {x}, y is {y}")
x, y = y, x
print(f"x is {x}, y is {y}")Notice that each value is swapped, using some very Pythonic syntax .
x, y = y, x
总结
在本课中,您学习了如何在 Python 中实现先前课程中的编程构建块。此外,您还了解了 Python 如何允许更简化的代码。此外,您还学习了如何使用各种 Python 库。最后,您了解到您作为程序员的技能不仅限于一种编程语言。您已经看到了如何通过本课程发现一种新的学习方式,该学习方式可以用任何编程语言为您服务 - 也许,几乎可以在任何学习途径中!具体来说,我们讨论了…
- 蟒
- 变量
- 条件
- 循环
- 类型
- 图书馆
- 字典
- 命令行参数
- 正则表达式