新建Python文件,输入
def function():
print('This is a function')
a = 1 + 2
print(a)
function()
得到
This is a function
3
5.2 函数参数
新建Python文件,输入
def fun(a, b):
c = a * b
print('the c is', c)
print('the a is', a)
fun(2, 5)
fun(a=2, b=5)
fun(b=2, a=5)
得到
the c is 10
the a is 2
the c is 10
the a is 2
the c is 10
the a is 5
5.3 函数默认参数
新建Python文件,输入
def sale_car(price, colour, is_second_hand):
print('price:', price,
'colour:', colour,
'is_second_hand:', is_second_hand,)
sale_car(1000, 'red', True)
得到
price: 1000 colour: red is_second_hand: True
输入
def sale_car(price, colour='red', is_second_hand=True):
print('price:', price,
'colour:', colour,
'is_second_hand:', is_second_hand,)
sale_car(1000)
得到
price: 1000 colour: red is_second_hand: True
输入
def sale_car(price, colour='red', is_second_hand=True):
print('price:', price,
'colour:', colour,
'is_second_hand:', is_second_hand,)
sale_car(1233, colour='blue')
得到
price: 1233 colour: blue is_second_hand: True
输入
def sale_car(price, brand, colour='red', is_second_hand=True):
print('price:', price,
'colour:', colour,
'brand:', brand,
'is_second_hand:', is_second_hand,)
sale_car(1233, 'cramy', colour='blue')
得到
price: 1233 colour: blue brand: cramy is_second_hand: True
Ps:没有被定义的值要放在已被定义的值的前面。
Ps:输出是根据print的顺序来的。
新建Python文件,输入
APPLE = 100
c = None
d = None
def fun():
a = APPLE
global b
b = 20
global c
c = 50
d = 80
return a + 100
print(APPLE)
print('c past=', c)
print('d past=', d)
print(fun())
print(b)
print('c now=', c)
print('d now=', d)
得到
100
c past= None
d past= None
200
20
c now= 50
d now= None
APPLE、b、c、d是全局变量,a是局部变量。
若只在函数内定义全局变量,则需要运行函数后在print该变量。
建议直接安装Anaconda。
Anaconda包括Conda、Python以及一大堆安装好的工具包,比如:numpy、pandas等。
新建Python文件,输入
text = 'This is my first test.\nThis is next line.\nThis is last line'
my_file = open('my file.txt', 'w')
my_file.write(text)
my_file.close()
会在当前python文件目录下生成一个txt文件,内容为:
目的:在8.1节创建的txt文件上追加文字
在新建的Python文件里输入
append_text = '\nThis is appended file.'
my_file = open('my file.txt', 'a')
my_file.write(append_text)
my_file.close()
得到
file = open('my file.txt', 'r')
content = file.read()
print(content)
得到
This is my first test.
This is next line.
This is last line
This is appended file.
输入
file = open('my file.txt', 'r')
first_read_time = file.readline()
second_read_time = file.readline()
print(first_read_time, second_read_time)
得到
This is my first test.
This is next line.
输入
file = open('my file.txt', 'r')
content = file.readlines()
print(content)
得到
['This is my first test.\n', 'This is next line.\n', 'This is last line\n', 'This is appended file.']