目录

Procedural Programming

Week 2 notes


Procedural Programming

What is Procedural Programming

Procedural Programming in Python
Comments and Documentation
python IDLE

user_input = input("Enter some text: ")
print("You entered:", user_input)

Variables

variable in python

Assigning Variables

Data Types

data type in python
mixing types
None and NoneType
None and functions

这里的例子主要是 print()print() 函数实际上并没有返回值(也可以说返回类型是 NoneType),以此以下程序中:

a = "Hello"
b = "world"
c = a + b
d = print(c)
print(d)
d = print© 实际上做了两步:

Type conversion in python

string 与 数字

“123”123 是两种不同的数据:

string 转换函数

#convert int
my_int = 5
my_string = str(my_int)
#convert date
from datetime import date
myDate = date.today()
myDateAsString = str(myDate)
以上转换多半可以通过隐式转换来进行。但需要注意的是,print() 内部无法进行隐式转换。比如下面的例子会造成 TypeError
print("Today's date: " + myDate)
可选的做法:
print("Today's date: " + str(myDate))
另外一种做法是使用 , 运算符,print() 会将 , 两边的分别衡量,因此也不会产生因 + 带来的类型不匹配了:
print("Today's date:", date.today())

string 转换为其他类型

转换为 int

my_int_as_str = "5"
my_int = int(my_int_as_str)
转换为 float
my_float_as_str = "5.1"
my_float = float(my_float_as_str)
转换为 bool
my_boolean_as_str = "True"
my_boolean = bool(my_boolean_as_str)

User input

myUserInput = input("Enter an int")
myInt = int(myUserinput)
print(myInt * myInt)

不输入任何信息直接回车会得到一个空 string。该 string 无法转化为 float

Reserved Keywords in Python

查看 python 的 keywords:

import keyword
print(keyword.kwlist)

使用 keywords 做变量名会导致 systax error.

function 名不是 reserve keyword
Dot Notation in Python

. 运算符是成员运算符,用于访问类中的成员;比如:

#date is a class, today() is its member function
from datetime import date
myDate = date.today()
print(myDate.year)
print(myDate.month)
print(myDate.day)
成员函数取决于类(library)提供什么样的功能。比如 datetime 类就能提供与 date 类不一样的功能:
import datetime
currentTime = datetime.datetime.now()
print(crrentTime.hour)
print(crrentTime.minute)
print(crrentTime.second)

Logical Operators

Relational Operators

Relational Operators in Python

Boolean Operators

Ture Tables

逻辑运算符的性质

Mathematical Operators

  1. floor div 会往最小的数进行取整。比如 3 // -2, 浮点结果是 -1.5,最小可以取到的整数是 -2,因此结果是 -2
  2. floor div 中,如果有浮点数参与运算,结果也是浮点数

self assignement

sincermenting and loops
Parentheses Errors