记录下自己学习Python之路,把这几天的学习工作做一个总结,有需要的同学可以从中获取自己想要的。Python为了处理大数据“简单的”,“高效”,“智能”的脚本语言。接下来就开始Python的学习之路。
变量的定义和初始化操作
APPLE_EGG = 20
appleEgg = 50
apple = 10+13
a, b, c = 1, 2, 3
print(apple)
print(a, b, c)
定义一个变量,以便自己在后面使用这个。define a variable and can use it
说明:变量定义可以是APPLE_EGG全部大写,做常量使用。可以使用连接符”_“,可以使用”驼峰类型”
while循环使用
condition = 1
while condition < 10:
print(condition)
condition = condition+1;
print('end')
循环条件在条件后面要加“:”,使用缩进符号来表示“块”代码属于while循环内。
说明:print关键词后面需要加"()",单引号和双引号都可以作为表示字符串。
for循环使用
# for
example_list = [1,2,3,4,5,6,7]
total_val = 0
for i in example_list:
total_val = total_val + i
print('inner of for')
print(total_val)
print('outer of for')
for i in range(1, 10, 2):
print(i)
for循环条件和上面说的while一样,需要使用“:”。
range(1, 10, 2)表示[1, 10)每次加2的一个列表。注意:列表用"[]"表示
if else elif使用
x, y, z = 1, 2, 3
# if else program
if x >= y <= z:
print('x is greater than y and y is less than z')
else:
print('result is not our respect')
# if elif else
if x >= y:
print('x is greater than y')
elif y >= z:
print('y is greater than x, z')
else:
print('y is less than x, z')
# if elif elif ..... else
条件判断可以连续使用 ps: a>b<c>=3这种样子。
说明:if else是基本的变成语法,这里添加了elif,和else if类似。
global 和 local变量使用
APPLE = 100
def func():
a = 10
print('global var:', APPLE)
return a
print('local var:', func())
# example 2
#val = None
def func2():
global val
val = 20
return val+20
print(func2())
print(val)
全局和局部变量的使用,一般和其他的编程语言一样。global val说明在函数中使用的是全局变量。
说明:如果在函数中定义了一个和全局变量一样名字的变量,就使用最近原则,不改变全局变量值。
install 和 uninstall 的使用
# install numpy
pip install numpy
# uninstall numpy
pip uninstall numpy
windows安装控件需要在cmd下使用pip或者pip3命令。
说明:更新的话 pip install -U numpy
text的使用
# texture
text = 'this is my text \n this is the next line'
print(text)
# write a text to my_file.txt file floder
my_file = open('my file.txt', 'w')
my_file.write(text)
my_file.close()
# rewrite a text to my floder
my_file = open('my file.txt', 'a')
my_file.write('\n'+text)
my_file.close()
my_file = open('my file.txt', 'r')
# content = my_file.read()
content_list = my_file.readlines()
# print(content)
print(content_list)
for text in content_list:
print(text)
使用 open 命令时需要记住几个命令 r(read) w(write) a(append) rb(read binary)
class 的使用
# base class
class Calculator:
name = 'calculator'
price = 10
def __init__(self, price):
self.price = price
def add(self, x, y):
print(self.name, x+y)
def minus(self, x, y):
print(self.price, x-y)
def times(self, x, y):
print('*:', x*y)
def devide(self, x, y):
print('/:', x/y)
# class init()
class的定义,需要在函数的第一个参数处写self表示是class中的函数,__init__初始化函数。
input函数的使用
# input function
number = input('please input a number:')
print('This input number is ', number)
if float(number) > 10:
print(' Its a good number')
else:
print('a bad number')
使用input函数用户可以通过键盘输入数据,进行处理。
说明:input出入的参数都是string类型的。
tuple和list的使用
# tuple list
a_tuple = (1, 2, 34, 5)
another_touple = 3, 4, 5, 66, 4
a_list = [1, 23, 45, 5]
print('list data')
for content in a_list:
print(content)
print('tuple data')
for content in a_tuple:
print(content)
for index in range(len(a_list)):
print('index:', index, 'number in list:', a_tuple[index])
print(range(len(a_list)))
print('--------------')
bList = [23, 234, 234 , 25, 234, 5, 256, 54, 232]
bList.insert(1, 233)
print(bList)
bList.remove(5)
print(bList)
print(bList[2:5])
print(bList.index(234))
print(bList.count(234))
print('---------------')
bList.sort()
print(bList)
bList.sort(reverse = True)
print(bList)
tuple使用的是(),list使用的是[]
说明:list相关操作 insert remove index count sort(reverse=True)def的使用
# define function
def fuc(a, b):
print('start..')
c = a*b
print('the c is ', c)
# function initial value
def sale_car(price, length, height, color='red', brand='carmy', is_second_hand=False):
print('price is ', price,
',color is ', color,
',brand is ', brand,
',second hand is ', is_second_hand,
',length is ', length,
'height is ', height)
sale_car(1000, 39, 48, brand='blue')
def可以在形参数中使用默认值,没有指定默认值的形参必须在指定形参的前面。
说明:True and False必须是这样子写,其他的不行。
多维数组的使用
# multi-dimension list
# numpy pandas library
multi_dim_list = [[1, 2, 3],
[2, 3, 4],
[3, 4, 5]]
print(multi_dim_list[1])
print(multi_dim_list[0][1])
多维数组的使用可以通过[]之间的嵌套使用。访问和其他的编程语言一样。
dictionary的使用# dictionary and list operator
a_list = [12, 3, 5, 54, 45, 75]
dictionary = {'apple':2, 'pear': [12, 312, 32], 'watermelon':{'w':1, 'a':2}}
print('dictionary:',dictionary['apple'])
print('list:', a_list[1])
del dictionary['apple']
print('del dictionary:', dictionary)
dictionary['banana'] = 3
print('add dictionary:', dictionary)
print(dictionary['watermelon']['w'])
字典的使用是十分随意的,可以通过任意类型指定任意类型。
import导入需要的包,python不是本省就有,需要自己加。
# import time
import time as t
print(t.localtime())
print(t.time())
from time import time, localtime
print(time())
print(localtime())
from time import *
# own write import
说明:可以自定义一个包,通过调用使用。
continue和break的使用
# continue and break
BOOLTYPE = True
while BOOLTYPE:
val = input('get number:')
if val == 'hello':
BOOLTYPE = True
continue
else:
BOOLTYPE = False
print('willing break block')
break
print('continue and break test')
使用和其他的编程语言一样使用。
try except Exception as e使用
# try catch error
import time as t
try:
file = open('hello.txt', 'r+')
except Exception as e:
response = input('do you want create hello.txt file (y/n):')
if response == 'y':
file = open('hello.txt', 'w')
print('file create successful')
file.close()
else:
pass
else:
file.write(str(t.time()))
file.close()
print('output current time to hello.txt file')
通过捕获异常来处理数据。
说明:和C++中的try catch类似
zip map lambda的使用
# zip lamda map
aList = [1, 2, 3]
bList = [2, 3, 4]
list(zip(aList, bList))
print('zip...')
for i,j in zip(aList, bList):
print(i/2, j**2)
print('lambda...')
def func1(x, y):
return (x+y)
func2 = lambda x, y: x+y
print(func2(1, 2))
print('map...')
map(func1, [1], [2]) # object
list(map(func1, [2,3], [4,5])) # result [257, 566]
zip是对象的数据合并,map是处理函数,lambda是缩短函数定义。
copy包含了deep and shallow
# shallow copy and deepcopy
import copy
a = [1, 2, 3]
b = a
# shallow copy
print(id(a), id(b))
print('id(b) = id(a):', id(a) == id(b))
c = copy.copy(a)
print('copy.copy(), id(c) == id(a):', id(c) == id(a))
a = [1, 2, [3, 4]]
d = copy.copy(a);
# deepcopy
print('copy, id(a) == id(d):', id(a[2]) == id(d[2]))
e = copy.deepcopy(a)
print('deepcopy id(id(a) == id(e):', id(a[2]) == id(e[2]))
上面的=copy是shallow。import copy的copy也是shallow copy,deepcopy()是deep copy
说明:=中复制嵌套数组,例子中的[3, 4]复制的地址是一致的。