目录
1、print
print(1) # 1
print('we are going to do something') # we are going to do something
print("we're going to do something") # we're going to do something
print("we\'re going to do something") # we're going to do something
print('apple'+'car') #applecar
print('apple'+str(4)) #apple4
print(1+2) # 3
print(int('1')+2) # 3
print(float('1.2')+2) # 3.2
2、数学
+ - * /
** 2**2=4
% 8%2=0
// 9//3=3
3、自变量
命名规则
apple_egg APPLE_EGG appleEgg
定义
a = 1
b = 2
c = 3
a,b,c = 1,2,3
4、while循环
condition = 1
while condition < 10:
print(condition)
condition = condition +1
#相当于while(1)
while True:
print("I'm True")
注意:while结尾处的“:” 有“:”后光标会调到下行会自动缩进
中断循环
注意下面的程序中要退出需要ctrl+c,否则一直在循环中,没法运行下一个程序
a = True
while a:
b = input('type something')
if b=='1':
a = False
else:
pass
print('still in while')
print('finish run')
-------------------------------
type something2
still in while
type something1
still in while
finish run
while True:
b = input('type something')
if b=='1':
break
else:
pass
print('still in while')
print('finish run')
---------------------------------
type something2
still in while
type something1
finish run
while True:
b = input('type something')
if b=='1':
continue
else:
pass
print('still in while')
print('finish run')
------------------------------
type something2
still in while
type something1
type something2
still in while
type something
5、for循环
example_list=[1,2,3,4,5,6,7,8,9,10]
for i in example_list:
print(i)
print("outer of for")
print("outer of for")
for i in range(1,10):
print(i)
注意:range是1,2,3,4,5,6,7,8,9
小技巧: ctrl+[ 可以将选中部分前的缩进消除,一同对齐,然后在Tab
6、if条件
常用符号 < <= > >= == != 可以连着比较大小
x,y,z = 1,2,3
if x<y<z:
print('true')
x,y,z = 1,2,1
if x<y>z:
print('true')
if x>y:
print('x is greater than y')
else:
print('x is less or equal than y')
if else
if x>1:
print('x > 1')
elif x<1:
print('x < 1')
else:
print('x = 1')
if elif else
先满足先跳出
x = -2
if x>1:
print('x > 1')
elif x<-1:
print('x < -1')
elif x<1:
print('x < 1')
else:
print('x = 1')
print('finish running')
---------结果-----------
x < -1
finish running
7、def函数
1、定义
def function():
print('This is a function')
a=1+2
print(a)
2、调用
def function():
print('This is a function')
a=1+2
print(a)
function()
3、参数
def fun(a,b):
c=a*b
print('the c is',c)
fun(2,3)
4、默认参数
无默认参数
def sale_car(price,color,brand,is_second_hand):
print('price',price,
'color',color,
'brand',brand,
'is_second_hand',is_second_hand)
sale_car(100,'red','carmy',True)
---------------------------------------------------
price 100 color red brand carmy is_second_hand True
有默认参数
def sale_car(price,color='red',brand='carmy',is_second_hand=True):
print('price',price,
'color',color,
'brand',brand,
'is_second_hand',is_second_hand)
sale_car(100)
sale_car(123,color='bule')
-----------------------------------------------------------------
price 100 color red brand carmy is_second_hand True
price 123 color bule brand carmy is_second_hand True
注意情况:输入参数时要注意与默认参数的顺序匹配,这个等具体用的再说。
5、return
def fun():
a = 10
print(a)
return a+100
fun()
print(fun())
---------------------
10
110
8、全局&局部变量
全局变量全部一般大写
#没有将a定义为全局变量
APPLE = 100
a = None
def fun():
a = 20
return a+100
print('a past=',a)
print(fun())
print('a now=',a)
----------------------
a past= None
120
a now= None
#将a定义为全局变量 global a(global a = 20会报错)
APPLE = 100
a = None
def fun():
global a
a = 20
return a+100
print('a past=',a)
print(fun())
print('a now=',a)
----------------------
a past= None
120
a now= 20
9、文件读写
text = 'This is my first test.\nThis is next line.\nThis is last line.'
my_file=open('my file1.txt','w')
my_file.write(text)
my_file.close()
append_text = '\nThis is appended line'
my_file=open('my file1.txt','a')
my_file.write(append_text)
my_file.close()
注意:文件打开后要关闭(close),否则文件是空白的
file = open('my file1.txt','r')
content = file.readline()
second_read_time = file.readline()
print(content,second_read_time)
---------------------------------
This is my first test.
This is next line.
readline是逐行读,readlines是存到list中
file = open('my file1.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 line']
10、类class
class Calculator:
name = 'Good calculator'
price = 18
def add(self,x,y):
print(self.name)
print(x+y)
def minius(self,x,y):
print(x-y)
def times(self,x,y):
print(x*y)
def divide(self,x,y):
print(x/y)
calcul = Calculator()
print(calcul.price)
calcul.add(1,2)
calcul.minius(2,4)
calcul.times(3,2)
calcul.divide(8,2)
------------------------------
18
Good calculator
3
-2
6
4.0
注意:self不要漏
init
注意 是 def __init__()
class Calculator:
def __init__(self,name,price,height,width,weight):
self.name = name
self.price = price
self.h = height
self.wi = width
self.we = weight
c = Calculator('Good calculator',12,1,2,3)
print(c.wi)
class Calculator:
def __init__(self,name,price,height=1,width=2,weight=3):
self.name = name
self.price = price
self.h = height
self.wi = width
self.we = weight
c = Calculator('Good calculator',12)
print(c.h)
b = Calculator('Good calculator',12,10)
print(b.h)
--------------------------------------
1
10
11、input
a_input = int(input('Please give a number:')) # input() --- return a string '1'
if a_input == 1:
print('This is a good one')
elif a_input == 2:
print('See you next time')
else:
print('Good luck')
12、元组
a_tuple = (12,3,5,25,6)
another_tuple = 12,3,5,25,6
13、列表
a_list = [12,3,67,7,82]
for content in a_list:
print(content)
for index in range(len(a_list)):
print('index=',index,'number in list=',a_list[index])
----------------------------------------------------------
12
3
67
7
82
index= 0 number in list= 12
index= 1 number in list= 3
index= 2 number in list= 67
index= 3 number in list= 7
index= 4 number in list= 82
a = [1,2,3,4,2,3,1,1]
a.append(0) # [1, 2, 3, 4, 2, 3, 1, 1, 0]
a.insert(0,0) # [0, 1, 2, 3, 4, 2, 3, 1, 1] 在0位插入0
a.remove(1) # [2, 3, 4, 2, 3, 1, 1] 去掉第一个出现的1
a.sort() # [1, 1, 1, 2, 2, 3, 3, 4] 从小到大排序
a.sort(reverse=True) # [4, 3, 3, 2, 2, 1, 1, 1] 从大到小排序
print(a.index(1)) # 0 第一次出现 1 的位置
print(a.count(1)) # 3 出现1的个数
左闭右开 :
a = [1,2,3,4,2,3,1,5]
print(a[0]) # 1
print(a[-1]) # 5
print(a[0:3]) # [1, 2, 3] 左闭右开
print(a[:3]) # [1, 2, 3]
print(a[3:5]) # [4, 2]
print(a[-3:]) # [3, 1, 5]
多维列表
a = [1,2,3,4,5]
multi_dim_a = [[1,2,3],
[2,3,4],
[3,4,5]]
print(a[1]) # 2
print(multi_dim_a[0][1]) # 2
print(multi_dim_a[0]) # [1,2,3]
14、字典
key:value
a = [1,2,3,4,5]
d1 = {'apple':1,'pear':2,'orange':3}
d2 = {1:'a','c':'b'}
print(d1['apple'],d2[1]) # 1 a
del d1['pear']
print(d1) #删除 {'apple': 1, 'orange': 3}
d1['b'] = 20
print(d1) #添加 {'apple': 1, 'orange': 3, 'b': 20}
def fun():
return 1+2
d3 = {'apple':[1,2,3],'pear':{1:3,3:'a'},'orange':fun()} #字典中可含列表、字典、函数
print(d3['apple'][0]) # 1
print(d3['pear'][3]) # a
print(d3['orange']) # 3
15、import模块
注意time.localtime()中的()
#第一种方式
import time
print(time.localtime())
#第二种方式
import time as t
print(t.localtime())
#第三种
from time import time,localtime
print(localtime())
print(time())
#第四种
from time import *
print(localtime())
print(time())
print(gettime())
自己的模块
被调用模块(m1.py)和程序(python1.py)在同一文件夹下 或者把m1.py放到和numpy在一起的文件夹下
#m1.py
def printdata(data):
print('I am m1')
print(data)
#python1.py
import m1
m1.printdata('I am python1')
----------------------------
I am m1
I am python1
16、错误处理try
try:
file = open('eee','r+') #只读+写入
except Exception as e:
print('there is no file named as eee')
response = input('do you want to create a new file')
if response == 'y':
file = open('eee','w')
else:
pass
else:
file.write('sss')
file.close()
17、zip & lambda & map
a = [1,2,3]
b = [4,5,6]
print(zip(a,b)) # <zip object at 0x000001905D33A688>
print(list(zip(a,b))) # [(1, 4), (2, 5), (3, 6)]
for i,j in zip(a,b): # 0.5 8
print(i/2,j*2) # 1.0 10
# 1.5 12
print(list(zip(a,a,b))) # [(1, 1, 4), (2, 2, 5), (3, 3, 6)]
def fun1(x,y):
return(x+y)
print(fun1(2,3))
#lambda用于定义简单的方程
fun2 = lambda x,y:x+y
print(fun2(2,3))
18、copy
#第一种copy a,b指向同一内存空间
a = [1,2,3]
b = a
print( id(a) ) # 1719550582216
print( id(b) ) # 1719550582216
b[0] = 11
print(a) # [11, 2, 3]
a[1] = 22
print(b) # [11, 22, 3]
print(id(a)==id(b))
#第二种copy copy.copy 第一层的东西列表指定到不同的内存空间,第二层指向同一层空间
import copy
a = [1,2,3]
c = copy.copy(a)
print(id(a)==id(c)) # False
c[1] = 0
print(c) # [11, 0, 3]
print(a) # [11, 22, 3]
a = [1,2,[3,4]]
d =copy.copy(a)
print(id(a)==id(d)) # False
print(id(a[2])==id(d[2])) # True
a[0] = 0
a[2][0] = 0
print(d) # [1, 2, [0, 4]] 第一项没改变,但列表里面的改变了
#第三种copy copy.deepcopy 完完全全的copy,内存空间不会重复
import copy
a = [1,2,[3,4]]
e = copy.deepcopy(a)
print(id(e[2])==id(a[2])) # False