CS50's Introduction to Python

0. How do Python Program Run

Interactive Mode of Python

1. Functions, Variables

1.1 Your Very First Python Program

我们将Hello world!输出到console作为我们的第一个python程序。下面就是我们的第一个python程序。如果你使用过C,你就会发现,在python中,一切来的如此简单自然。

print("Hello world!")  # Literally prints out "Hello world!"
# or in this way
print('Hello world!')  # Same as above, Python does not distinguish between '' and ""

# But be aware to match them, the following examples would be incorrect:

# print('Hello world!")
# print("Hello world!')
# print("Hello "world")

# This would be fine with back slash:

print("Hello \"world")

print()函数的功能类似于C语言中的printf(),但不同于C语言,我们在使用input()的时候并不需要包含任何头文件等等。这是因为print()函数是一个内置函数(build-in function),这些内置函数作为python语言的一部分存在。要使用这些内置函数,我们并不需要import任何的python标准库或其他的库。

如果注意力惊人。当你运行了程序,你就会发现虽然我们程序中并没有换行的需求,print() 函数还是默认在输出的字符串后添加一个换行符。这和print()函数的原型有关。

这里你可以找到所有的python内置函数。print()的函数原型如下:

def print(*objects, sep=' ', end='\n', file=None, flush=False):
"""
Prints the given objects to the standard output or to the specified file.

Parameters:
    1. *objects: Any number of objects to be printed.
    2. sep: A string inserted between the objects, default is a space.
    3. end: A string appended after the last object, default is a newline.
    4. file: A file-like object (stream); defaults to the current sys.stdout.
    5. flush: Whether to forcibly flush the stream.
Return value: No return values.
"""

当你没有指定第二个参数end时,end参数默认会在字符串最后追加一个换行符,也就是'\n'。如果你不想在输出时换行,你只需要:

print("Hello world!", end = '')

1.2 Hi, David!

学习过了如何用print()在console中打印一个字符串。这小节我们来编写一个简单的交互式程序吧。我们将学到另一个内置函数——input()。它的作用是从用户哪里读取一行输入,并将其作为一串字符串返回给一个变量。下面是input()的函数原型。

def input(prompt):
"""
Reads a line from input, converts it to a string (stripping a trailing newline), and returns that.

Parameters:
    1. prompt: A string, representing a message to display before the input (optional).

Return value: The input from the user as a string.
"""

input()函数会等待用户按下回车并将用户输入作为str类型的返回值返回。所以我们使用input()时往往需要一个变量来存储我们输入的字符串信息。在python中,我们不需要在变量前面指明string类型。一个简单的“你是?我是xxx。”的交互式程序如下:

print("Who are you?")
s = input() # Input your name.
print("I am", end = ' ')
print(s)

由于input()有一个参数prompt用来标识一个可选择性输入的提示信息。所以我们可以直接用input()输出一些提示信息:

s = input("Who are you?") # Input your name.
print("I am", end = ' ')
print(s)

此外,我们还可以用以下的方法来打印我是xxx的信息:

print("I am " + name)
print("I am", name)

# format string
print(f"I am {name}")

1.2.1 Bulid-in String Methods

round and formatted string

1.3 Variable

变量是用于存储数据的命名位置,即我们用变量来标识一个地址。在上面的程序中我们看到,要储存一个信息(不仅仅是字符串),我们需要定义一个变量。当我们用赋值运算符=,信息就会被储存到变量所在的位置。

Python解释器为我们内置了很多类型,这些内置类型是python语言中预定义的数据类型。当你将一个值赋给变量时,变量会自动采用该值的类型。常见的内置类型有:

  1. 整数(int)
  2. 浮点数(float)
  3. 浮点数(bool)
  4. 字符串(str)
  5. 列表(list)
  6. 字典(dict)
  7. ......

趁热打铁,我们来用input()输入两个数字实现一下我们第一个python的加法程序:

n = input("Enter a interger number:") # Enter 5
m = input("Enter a float number:") # Enter 0.5
print(f"The result is {n + m}") # Print out 50.5

我们运行了上面的程序,但是我们发现输出完全是错误的。这是因为在之前我们使用s = input()时,由于input()会返回一个str类型的值。为了实现加法程序,我们需要将输入的数据进行转换,具体步骤如下:

n = input("Enter a interger number:") # Enter 5
n = int(n)
m = input("Enter a float number:") # Enter 0.5
m = float(m)
print(f"The result is {n + m}") # Print out 5.5

再简化一下,我们让里面input()函数的返回值作为外面函数的参数:

n = int(input("Enter a interger number:")) # Enter 5
m = float(input("Enter a float number:")) # Enter 0.5
print(f"The result is {n + m}") # Print out 5.5

甚至,你可以将输入放到print()函数中。那么一行代码可能会变得很长,可读性就会下降。

上面,我们用input() 函数获取用户输入并返回一个字符串。然后,我们使用内置函数 int()float() 函数将字符串转换为整数(默认10进制)或浮点数。如果用户输入的内容不能转换为数字,就会引发 ValueError 异常。

和上面的string build-in methods一样,其他build-in类型也有相应的build-in methods。

row = line.rstrip().split(",")
row[0],row[1]

name, house = line.rstrip().split(",")

1.4 Functions

在Python中,函数的定义确实非常简单。我们使用def关键字来引入函数的定义。Python并不像C或其他语言那样用分号表示一个语句的结束,而是用换行符来表示语句的结束。此外,Python使用缩进来表示代码块的层次结构和逻辑关系,而不是像C语言那样使用大括号{}

下面是一个简答的python函数示例:

def greet(name):
    print(f"Hello, {name}!")

greet("David")

Python中并没有C语言里面的函数声明等的东西。而且函数引入了变量的作用域(scope)。在函数里面出现的变量就是局部变量,相比之下C语言中我们称大括号里面的变量为局部变量。

2. Conditionals

>>=<<===!=

to many if

enif(else if) and else

or and and

pythonic code:

def is_even(n):
	return (n % 2 == 0) else False

match case

3. Exceptions

try:
    x = int(input("what's x:"))
    print(f"x = {x}")
except ValueError:
    print("x is not a integer")

try:
    x = int(input("what's x:"))
except ValueError:
    print("x is not a integer")
print(f"x = {x}")
try:

except Error:
	pass
else:

raise

4. Libraries

def main():
    print("This is the main function.")

if __name__ == "__main__":
    main()

modules

command pip install module

5. Unit Tests

unit means function

assert

pytest

with

test a folder
once the testor find a __init__.py in the folder, it would treat this folder into a package

my_project/
    ├── my_package/
    │   ├── __init__.py
    │   ├── module1.py
    │   └── module2.py
    └── test/
        ├── __init__.py
        └── test_module1.py

6. File I/O

file = open()

with with statement, you can automatically close the file

Comma-Separated Values