In [ ]:
# 第一章 接触Python语言 --- Get Started with Python
#(《计量经济学编程:以Python语言为工具》严子中、张毅著;中国财经出版社,2024)

Introduction¶

From now on, we will start to program in Python. A long-held belief in the programming world is printing a "Hello world!" message to the screen as our first look at a new language. To begin, you can either access a Jupyter Notebook online or on your device, write the code, and run the command:

In [ ]:
print("Hello world!")

Basics of Math and Variables¶

Python Calculator¶

In [ ]:
12-1 # 减法
In [ ]:
3*3 # 乘法
In [ ]:
3**3 # 取底的三次方
In [ ]:
16**0.5 # 开根号

Variables¶

Define a Variable¶

In [ ]:
x = 10
print(x*3+10) # x乘以3并加10
In [ ]:
y = 5; x = y
x
In [ ]:
y = 5; Y = 15
y, Y

Variable Identifier¶

In [ ]:
a = 3; b = 1
print(id(a), id(b))
In [ ]:
a = 1; b = 1
print(id(a), id(b))
In [ ]:
a = 1; b = a
print(id(a), id(b))

Assignment Operator¶

In [ ]:
x = 4
x = x+1
x
In [ ]:
x += 1
x
In [ ]:
x = 4
x *= 1    # x乘以1并对x重新赋值
print(x)  # 输出新赋值的x结果
x /= 2    # 对于新赋值的x进行除以2
print(x)  # 输出新赋值的x结果
x **= 2   # 对于新赋值的x进行2次方
print(x)  # 输出新赋值的x结果

Numbers and Characters¶

Integers and Floats¶

In [ ]:
x = 10; y = 10.0; z = 10.1  # 定义变量x,y,z并赋值
type(x), type(y), type(z)   # 输出变量x,y,z的数据类型
In [ ]:
import sys
# 查看Python中可定义最大和最小浮点数
print(sys.float_info.max, sys.float_info.min)
In [ ]:
x = 1.8e+308; y = -1.8e+308
x, type(x), y, type(y) 
In [ ]:
x = 1e-20+1
y = 1e-30+1
print(id(x), id(y))
x == y # 判断变量x与y的取值是否相等

Strings¶

In [ ]:
x = "Hello my colleagues"
print(x)
In [ ]:
x = "1" ; y = "2"
x+y

Use Quotation in String¶

In [ ]:
x = 'You are my "sunshine"'
print(x)
y = "You are my 'sunshine'"
print(y)
z = "This is Mike's basketball"
print(z)

Concatenate and Split in String Variables¶

In [ ]:
x = "Hello"
y = "my colleagues"
z = x + y
print(z)
In [ ]:
z = x + " " + y   
print(z)          
In [ ]:
z.split(), z
In [ ]:
x = "今天阳光明媚。今天温度较高。今天傍晚去篮球场。"
y = x.split("。")
y
In [ ]:
"。".join(y)

Upper Case, Lower Case and Capitalization¶

In [ ]:
name = "python prograMMing fOr ecoNOmeTRics: a BEGINNER's guiDE"
print(name.upper())     # 全部使用大写
print(str.upper(name))  # 同上
print(name.lower())     # 全部使用小写
print(str.lower(name))  # 同上
In [ ]:
name = "python prograMMing fOr ecoNOmeTRics: a BEGINNER's guiDE"
print(name.capitalize()) # 首字母大写,其余均采用小写
In [ ]:
print(name.title()) 

Convert between String and Number¶

In [ ]:
a = "10"
int(a), type(a), type(int(a))
In [ ]:
b = "10.09"
eval(b), type(b), type(eval(b))
In [ ]:
c = 10
d = 10.123
str(c), type(str(c)), str(d), type(str(d))

Built-in Functions and Modules¶

Built-in math Module¶

In [ ]:
import math
math.log(1) # 输出模块m中的log函数并计算log(1)的值
In [ ]:
math.pi
In [ ]:
math.log(math.e), math.cos(math.pi)

Built-in print Function¶

Print the Output¶

In [ ]:
print("Line one\nLine two")
In [ ]:
print("Word one\tWord two")
In [ ]:
d = "Fourth line"
print("First line\n"+"Second line\n"+"Third line\n" +d)

Formatted Print¶

In [ ]:
# 输出一串字符,其中beta的显示格式是integer,alpha的显示格式是float
print("beta = %d, alpha = %f" % (10,2.56))
In [ ]:
# 输出格式为float
print("Est. value = %f" % (12345.12345))
# 输出格式为integer
print("Est. value = %d" % (12345.12345))
# 输出格式为float,总计宽度8位,且小数点后1位
print("Est. value = %8.1f" % (12345.12345))
# 输出格式为float,总计宽度10位,且小数点后1位
print("Est. value = %10.1f" % (12345.12345))
# 输出格式为float,总计宽度15位,且小数点后3位
print("Est. value = %15.3f" % (12345.12345))

Read and Write Text Files¶

In [ ]:
import os # 引入os模块
cwd = os.getcwd() # 定义变量cwd,记录现在工作的路径
cwd
In [ ]:
write_file = open(cwd+"/example_text.txt", "w")
write_file.write("The 1st line\n"+"The 2nd line\n"+"The 3rd line")
write_file.close()
In [ ]:
read_file = open(cwd+"/example_text.txt", "r")
text = read_file.read()
read_file.close()
print(text)

Data Structures¶

Tuples and Lists¶

Tuples¶

In [ ]:
a = (10,20,30.56,"Hello")
print(a, type(a))
In [ ]:
a = 10,20,30.56,"Hello"
print(a, type(a))

Lists¶

In [ ]:
a = [10,20,30.56,"Hello"]
print(a, type(a))

Operations¶

min, max and sum of a List¶

In [ ]:
x = [0,1,2,3,4,5,10.85] 
[min(x), max(x), sum(x)]
In [ ]:
letters = ["a","b","c","d"] 
[min(letters), max(letters)] 
In [ ]:
words = ["Python","Stata","R","Java"]
[min(words), max(words)]

Length of Sequences¶

In [ ]:
x = "Hello"
y = "my colleagues"  
len(x), len(y)       
In [ ]:
print([x,y])
len([x,y])

Combine Lists and Remove Elements from a List¶

In [ ]:
a = [10,20,30]
b = [10,20,30,"Hello"]
print(a+b)
In [ ]:
a.append(b)
a
In [ ]:
a = [10,20,30,"Hello"]
a.remove(20)
a

Indexing and Slicing¶

Index Rule¶

In [ ]:
a = [10,20,30,"Hello"]
a[0], a[1], a[2], a[3]
In [ ]:
a[-1], a[-2], a[-3]
In [ ]:
a = [10,20,30,"Hello"]
a.insert(1,'IESR')
print("Add 'IESR' to position 1:", a)

a = [10,20,30,"Hello"]
a.insert(-1,'IESR')
print("Add 'IESR' to position -1:", a)

Slice Rule¶

In [ ]:
a = [10,20,30,"Hello"]
a[0:3] 
In [ ]:
a[0:] 
In [ ]:
a[:-1] 
In [ ]:
a= "Hello IESR Colleagues"
# 对于字符串,列表索引对应字符串中字符的顺序
print(a[0:3]) 
print(a[:3])  
print(a[2:3]) 
print(a[:])   

Control Flow¶

if-elif-else Statements¶

In [ ]:
x = 10
if x > 0: # 如果变量x满足x>0
    print("x is greater than 0")
In [ ]:
x = 0
if x > 0: # 如果满足x>0条件
    print("x is greater than 0")
else:     # 如果不满足x>0条件
    print("x is negative or 0")
In [ ]:
x = -10
if x == 0:  # 如果满足x=0条件
    print("x is 0")
elif x > 0: # 如果满足x>0条件
    print("x is greater than 0")
else:       # 如果同时不满足以上条件
    print("x is negative")
In [ ]:
x = 5
y = 10
z = 15
if x > y:     
    if x > z: 
        print("x is greater than y and z")
    else:
        print("x is greater than y but not greater than z")
elif y > z:   
    print("x is not greater than y, y is greater than z")
else:
    print("z is the largest")

Loop Statements¶

In [ ]:
for i in ["Kitten","Cat","Feline"]:
    print(i, end=", ")
In [ ]:
for i in [0,1,2,3]: 
    print(i, end=", ")

Examples of for-loop¶

In [ ]:
j = 0
for i in [0,1,2,3]:
    j += i 
    print("i = %d, j = %d" % (i,j))
In [ ]:
j = 0
for i in range(0,4):
    j += i 
    print("i = %d, j = %d" % (i,j))
In [ ]:
import os 
cwd = os.getcwd()
# 写入文件
write_file = open(cwd+"/example_iterative_text.txt", "w")
for i in range(1, 4):
    write_file.write("%d x 5 = %d \n" % (i,i*5))
write_file.close()
# 读取文件内容
read_file = open(cwd+"/example_iterative_text.txt", "r")
text = read_file.read()
read_file.close()
print(text)

while Statements¶

In [ ]:
x = 5
y = 0
while y < x:
    print(y, end = " ")
    y += 1 
print("Exit while-loop")
In [ ]:
amount = 10000 # 初始10000元人民币
rate = 0.0175 # 1.75%的年利率
year = 0
while amount < 20000: # 重复直至amount达到20000
    amount = amount + amount*rate
    year = year+1
print('We need', year , 'years to reach', amount , 'yuan RMB.')

break and continue Statements¶

In [ ]:
for i in "ABCDEF":
    if i == "D":
        break
    print(i)
print("The end")
In [ ]:
for i in "ABCDEF":
    if i == "D":
        continue
    print(i)
print("The end")

Functions and Classes¶

Functions¶

In [ ]:
def square_values(x):
    return x*x
square_values(10)

Examples of Functions¶

In [ ]:
def upper_lower(s):
    return s.upper(), s.lower()
sentence = 'python prograMMing fOr ecoNOmeTRics'
upper_lower(sentence)
In [ ]:
results = upper_lower(sentence)
print("The orginal sentence is `%s`. \nIts upper case is `%s`. \nIts lower case is `%s`." % (sentence,results[0],results[1]) )
In [ ]:
def double_k(k):
    k = k+k
    return k
k_string = "Hello"
double_k(k_string)
In [ ]:
def double_values(k):
    for i in range(len(k)):
        k[i] = k[i]*2
        print(k)
k_input = [0,1,2,10,20]
double_values(k_input)
In [ ]:
import copy
def double_values_local1(k):
    k_local = copy.copy(k)
    for i in range(len(k)):
        k_local[i] = k_local[i]*2
    return k_local
k_input = [0,1,2,10,20]
double_values_local1(k_input), k_input
In [ ]:
def double_values_local2():
    global k_input
    k_local = copy.copy(k_input)
    for i in range(len(k_input)):
        k_local[i] = k_local[i]*2
    return k_local
k_input = [0,1,2,10,20]
double_values_local2(), k_input

Setting Default Values of Parameters¶

In [ ]:
def multiply_m(j, m=3):
    print("%d * %d = %d" % (j,m,j*m))
multiply_m(5)

Functions and Modules¶

Classes¶

In [ ]:
class First_class:
    def __init__(self, x1, x2):
        # 该函数首个参数为self
        self.r = x1
        self.i = x2

x = First_class(x1=3.0, x2=-4.5)
x, x.r, x.i
In [ ]:
class Puppy:
    # 实例(instances)共用的Class变量
    kind = 'Snoopy'
    def __init__(self, name):
        # 仅一个实例使用的实例变量
        self.name = name

d = Puppy('Fido')
print(d.kind) 
print(d.name) 
In [ ]:
class Puppy:
    kind = 'Snoopy'
    def __init__(self, name):
        self.name = name
        self.tricks = []
    def add_trick(self, trick):
        self.tricks.append(trick)
d = Puppy('Fido')
d.add_trick('Piu')
d.tricks

Functional Programming¶

List Comprehensions¶

In [ ]:
y = [] # 定义一个空list
for x in range(4):  
    z = x*2         
    y.insert(x,z)   
y
In [ ]:
[x*2 for x in range(4)]
In [ ]:
[x*1 for x in range(10) if x >5]

Anonymous Function¶

In [ ]:
def f(x):
    return(2*x)
f(1)
In [ ]:
lambda x: 2*x
In [ ]:
(lambda x: 2*x)(1)
In [ ]:
def f(x, y, z):
    return(7*x + x**5 + 3*y + 6/z)
f(1,2,3)
In [ ]:
(lambda x,y,z: 7*x + x**5 + 3*y + 6/z)(1,2,3)

Map a Function¶

In [ ]:
def f(x):
    return(2*x + x**2)
In [ ]:
h = []
for x in range(0,11):
    h.append(f(x))
h
In [ ]:
list(map(f, range(0,11)))
In [ ]:
list(map(lambda x: 2*x + x**2, range(0,11)))

Filter Elements in a Sequence¶

In [ ]:
def positive_checker(x):
    if x > 0:
        return(True)
    else:
        return(False)
positive_checker(1), positive_checker(-1)
In [ ]:
list(filter(positive_checker, range(-10,10,1)))
In [ ]:
list(filter(lambda x: x > 0, range(-10,10,1)))

Using Python and Stata Together¶

Configurations¶

In [ ]:
# 配置Python-Stata交互
import os
os.chdir('/Applications/Stata/utilities')
from pystata import config
config.init('mp')
___  ____  ____  ____  ____ ©
 /__    /   ____/   /   ____/      17.0
___/   /   /___/   /   /___/       MP—Parallel Edition

 Statistics and Data Science       Copyright 1985-2021 StataCorp LLC
                                   StataCorp
                                   4905 Lakeway Drive
                                   College Station, Texas 77845 USA
                                   800-STATA-PC        https://www.stata.com
                                   979-696-4600        stata@stata.com

Call Stata from Python¶

In [ ]:
from pystata import stata
# 运行一段Stata代码
stata.run(
    '''clear all
    sysuse auto
    sum price''')
In [ ]:
stata.get_return()