What & How & Why

Procedural Programming

Week 2 notes


Procedural Programming

What is Procedural Programming

  • Functional Programming
    • Function: A segment of code that performs a specific task, sometimes taking some input and sometimes returning some output
    • Method: A function that is part of a class in object-oriented programming (but colloquially, often used interchangeably with function).
  • Object-Oriented Programming: A programming paradigm where programmers define custom data types that have custom methods embedded within them.
  • Event-Driven Programming: 程序会等待用户的输入(event),根据输入再进行计算。
Procedural Programming in Python
  • type & variables
  • operators
    • arithmetic op
    • logical op
Comments and Documentation
  • Comments: Notes from the programmer supplied in-line alongside the code itself, designated in a way that prevents the computer from reading or attempting to execute them as code.
  • Documentation: Collected and set-aside descriptions and instructions for a body of code.
  • Self-Documenting Code: 使用变量名来解释程序的意义
  • python 使用
    • # 作为单行 comment 的起点,终点是 end of the line
python IDLE
  • 使用 IDLE 直接可以进入
  • Immediate Mode:交互型模式(类似计算器)
  • Scripting Mode
    • Ctrl+N 创建新文件,F5 运行
    • input() 函数可以用于输入(类似cin)比如:

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

Variables

  • 由 name 和 value 组成
  • name 不变, value 会变
  • variable 的命名:骆驼(camel case)和下划线 (under_score)(python 用后面)
variable in python
  • variable 的类型在赋值的时候决定。如果改变了赋值的类型,那么 variable 的类型会随之改变
  • 命名规则:
    • rule
      • variable 只能由数字和字符(还有下划线)组成
      • variable 只能从字母开始
      • varibale 不能使用 reserve word
    • convention
      • variable 名应该是有意义的,比如 age

Assigning Variables

  • order relation ship: x = 5,而不是 5=x(systax error)
  • 在 variables 使用之前需要进行赋值(name error)
  • None:意味着没有值。但这种情况是可以打印的,而没有赋值的不行(没赋值意味着没定义)

Data Types

  • basic types
  • custom types
  • 某些 data type 是不可比较的,如果需要比较,需要人为的指定规则。
data type in python
  • python 是弱类型语言
    • python 变量的类型由其 value 决定(C++ 是由 name 决定)
  • 类型检测函数: type()
  • python 并没有严格意义上的 primitive data.
mixing types
  • 如果做没有意义的,不同 type 之间的运算,会导致 TypeError.
    • 注意看错误输出,解释器会提示是什么导致了不兼容。
None and NoneType
  • None 类型是根据 null 的概念而来,代表没有值的变量
  • None 类型被称为 NoneType,不能与任何其他类型适配
  • 创建 None type
    • 直接赋值 None,比如 x = None
None and functions

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

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

  • print©c 的内容输出到终端,并返回 NoneType
  • None 赋值给了 d

Type conversion in python

string 与 数字

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

  • “123” 以文本形式存储
  • 123 是以整型的形式存储
string 转换函数
  • str():将当前 argument 转换并返回 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)

  • 如果转换的后的结果不能转化为指定的类型,那么结果是 ValueError,比如 “5a” 不能转换为 int
  • 即便存在对应的转换关系, literal 只能转化为对应的类型,比如 “5.1” 不能转换为 int 类型,会导致 ValueError.
  • 例外:
    • 不丢失信息的转换可以实现,比如 int 的 string 可以转换为 float,但反之不行
    • 绝大部分数据都可以转化为 boolean
User input
  • input() 打印指定内容,并返回用户的输入。用户的输入的内容是 str 类型,因此需要转换:

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)

  • Importing Libraries. import, from. Not covered explicitly, but you'll see these in a few places throughout our material, especially when we're dealing with dates, turtles, or random numbers.
  • Logical Operators. and, is, not, or, False, True, None. Covered in Chapter 2.3.
  • Control Structures. as, break, continue, if, elif, else, for, in, while, pass, with. Covered throughout Unit 3. if, elif, and else are covered in 3.2; for, while, pass, continue, and break are covered in 3.3. as and with are not covered explicitly. in comes up in Chapters 2.3, 3.2, 3.3, and other places.
  • Functions. def, return. Covered in Chapter 3.4.
  • Object-Oriented Programming Syntax. class. Covered in Chapter 5.1.
  • Error Handling. except, finally, raise, try. Covered in Chapter 3.5. else also comes up here.

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

function 名不是 reserve keyword
  • 使用 function 名作为变量名会掩盖 function 原有的意思(也就是 name 的 bind 变了)
  • 实际使用中应该避免使用 function 名作为变量名
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

  • Mathematical Operators:Operators that perform mathematical functions
  • Logical Operators:Operators that perform logical operations, such as comparing relative values, checking equality, checking set membership, or evaluating combinations of other logical operators.

Relational Operators

  • Relational Operators: Operators that check the relationships between multiple variables
  • Numeric Comparison Operators: Operators that facilitate numeric comparison between values.
  • Boolean Operators
  • Non-Numeric Equality Comparisons:不比较大小,但比较是否相等。比如苹果和橘子可以定义为不相等。
  • Set Operators:Check to see if a value is a member of a set of multiple values. Most often this comes up in strings and lists.
Relational Operators in Python
  • == equal operator
  • in 查看一个 string 是否包含另外一个 string(也可以用于元素是否在 List 里)
    • 该运算返回 t/f,区分大小写

Boolean Operators

  • and
  • or
  • not

Ture Tables

  • 可以通过真值表快速查询复杂逻辑表达式的真假
逻辑运算符的性质
  • 交换律
  • 分配律
  • 德摩根律(not( A and B)→ not A or not B

Mathematical Operators

  • Assignment Operator
  • Mathematical Operators: add, sub, mul, div, mod
  • Additional Operators: floor div //, exponent(base ** exp)
  1. floor div 会往最小的数进行取整。比如 3 // -2, 浮点结果是 -1.5,最小可以取到的整数是 -2,因此结果是 -2
  2. floor div 中,如果有浮点数参与运算,结果也是浮点数

self assignement

  • self assignement
  • incrementing
  • 自增可以用 += 之类的缩写(比如 -=, *=)表示,string 也可以用。
sincermenting and loops
  • 自增一般与 loop 连用。
Parentheses Errors
  • 括号需要匹配。
  • 括号不匹配的出错信息往往在别的行