# 第一章 接触Python语言 --- Get Started with Python
#(《计量经济学编程:以Python语言为工具》严子中、张毅著;中国财经出版社,2024)
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:
print("Hello world!")
12-1 # 减法
3*3 # 乘法
3**3 # 取底的三次方
16**0.5 # 开根号
x = 10
print(x*3+10) # x乘以3并加10
y = 5; x = y
x
y = 5; Y = 15
y, Y
a = 3; b = 1
print(id(a), id(b))
a = 1; b = 1
print(id(a), id(b))
a = 1; b = a
print(id(a), id(b))
x = 4
x = x+1
x
x += 1
x
x = 4
x *= 1 # x乘以1并对x重新赋值
print(x) # 输出新赋值的x结果
x /= 2 # 对于新赋值的x进行除以2
print(x) # 输出新赋值的x结果
x **= 2 # 对于新赋值的x进行2次方
print(x) # 输出新赋值的x结果
x = 10; y = 10.0; z = 10.1 # 定义变量x,y,z并赋值
type(x), type(y), type(z) # 输出变量x,y,z的数据类型
import sys
# 查看Python中可定义最大和最小浮点数
print(sys.float_info.max, sys.float_info.min)
x = 1.8e+308; y = -1.8e+308
x, type(x), y, type(y)
x = 1e-20+1
y = 1e-30+1
print(id(x), id(y))
x == y # 判断变量x与y的取值是否相等
x = "Hello my colleagues"
print(x)
x = "1" ; y = "2"
x+y
x = 'You are my "sunshine"'
print(x)
y = "You are my 'sunshine'"
print(y)
z = "This is Mike's basketball"
print(z)
x = "Hello"
y = "my colleagues"
z = x + y
print(z)
z = x + " " + y
print(z)
z.split(), z
x = "今天阳光明媚。今天温度较高。今天傍晚去篮球场。"
y = x.split("。")
y
"。".join(y)
name = "python prograMMing fOr ecoNOmeTRics: a BEGINNER's guiDE"
print(name.upper()) # 全部使用大写
print(str.upper(name)) # 同上
print(name.lower()) # 全部使用小写
print(str.lower(name)) # 同上
name = "python prograMMing fOr ecoNOmeTRics: a BEGINNER's guiDE"
print(name.capitalize()) # 首字母大写,其余均采用小写
print(name.title())
a = "10"
int(a), type(a), type(int(a))
b = "10.09"
eval(b), type(b), type(eval(b))
c = 10
d = 10.123
str(c), type(str(c)), str(d), type(str(d))
math
Module¶import math
math.log(1) # 输出模块m中的log函数并计算log(1)的值
math.pi
math.log(math.e), math.cos(math.pi)
print
Function¶print("Line one\nLine two")
print("Word one\tWord two")
d = "Fourth line"
print("First line\n"+"Second line\n"+"Third line\n" +d)
# 输出一串字符,其中beta的显示格式是integer,alpha的显示格式是float
print("beta = %d, alpha = %f" % (10,2.56))
# 输出格式为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))
import os # 引入os模块
cwd = os.getcwd() # 定义变量cwd,记录现在工作的路径
cwd
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()
read_file = open(cwd+"/example_text.txt", "r")
text = read_file.read()
read_file.close()
print(text)
a = (10,20,30.56,"Hello")
print(a, type(a))
a = 10,20,30.56,"Hello"
print(a, type(a))
a = [10,20,30.56,"Hello"]
print(a, type(a))
min
, max
and sum
of a List¶x = [0,1,2,3,4,5,10.85]
[min(x), max(x), sum(x)]
letters = ["a","b","c","d"]
[min(letters), max(letters)]
words = ["Python","Stata","R","Java"]
[min(words), max(words)]
x = "Hello"
y = "my colleagues"
len(x), len(y)
print([x,y])
len([x,y])
a = [10,20,30]
b = [10,20,30,"Hello"]
print(a+b)
a.append(b)
a
a = [10,20,30,"Hello"]
a.remove(20)
a
a = [10,20,30,"Hello"]
a[0], a[1], a[2], a[3]
a[-1], a[-2], a[-3]
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)
a = [10,20,30,"Hello"]
a[0:3]
a[0:]
a[:-1]
a= "Hello IESR Colleagues"
# 对于字符串,列表索引对应字符串中字符的顺序
print(a[0:3])
print(a[:3])
print(a[2:3])
print(a[:])
if-elif-else
Statements¶x = 10
if x > 0: # 如果变量x满足x>0
print("x is greater than 0")
x = 0
if x > 0: # 如果满足x>0条件
print("x is greater than 0")
else: # 如果不满足x>0条件
print("x is negative or 0")
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")
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")
for i in ["Kitten","Cat","Feline"]:
print(i, end=", ")
for i in [0,1,2,3]:
print(i, end=", ")
for
-loop¶j = 0
for i in [0,1,2,3]:
j += i
print("i = %d, j = %d" % (i,j))
j = 0
for i in range(0,4):
j += i
print("i = %d, j = %d" % (i,j))
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¶x = 5
y = 0
while y < x:
print(y, end = " ")
y += 1
print("Exit while-loop")
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¶for i in "ABCDEF":
if i == "D":
break
print(i)
print("The end")
for i in "ABCDEF":
if i == "D":
continue
print(i)
print("The end")
def square_values(x):
return x*x
square_values(10)
def upper_lower(s):
return s.upper(), s.lower()
sentence = 'python prograMMing fOr ecoNOmeTRics'
upper_lower(sentence)
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]) )
def double_k(k):
k = k+k
return k
k_string = "Hello"
double_k(k_string)
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)
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
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
def multiply_m(j, m=3):
print("%d * %d = %d" % (j,m,j*m))
multiply_m(5)
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
class Puppy:
# 实例(instances)共用的Class变量
kind = 'Snoopy'
def __init__(self, name):
# 仅一个实例使用的实例变量
self.name = name
d = Puppy('Fido')
print(d.kind)
print(d.name)
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
y = [] # 定义一个空list
for x in range(4):
z = x*2
y.insert(x,z)
y
[x*2 for x in range(4)]
[x*1 for x in range(10) if x >5]
def f(x):
return(2*x)
f(1)
lambda x: 2*x
(lambda x: 2*x)(1)
def f(x, y, z):
return(7*x + x**5 + 3*y + 6/z)
f(1,2,3)
(lambda x,y,z: 7*x + x**5 + 3*y + 6/z)(1,2,3)
def f(x):
return(2*x + x**2)
h = []
for x in range(0,11):
h.append(f(x))
h
list(map(f, range(0,11)))
list(map(lambda x: 2*x + x**2, range(0,11)))
def positive_checker(x):
if x > 0:
return(True)
else:
return(False)
positive_checker(1), positive_checker(-1)
list(filter(positive_checker, range(-10,10,1)))
list(filter(lambda x: x > 0, range(-10,10,1)))
# 配置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
from pystata import stata
# 运行一段Stata代码
stata.run(
'''clear all
sysuse auto
sum price''')
stata.get_return()