Python基本语法学习

来源:互联网 发布:安知玉如意txt书本网 编辑:程序博客网 时间:2024/06/06 08:46

记录下自己学习Python之路,把这几天的学习工作做一个总结,有需要的同学可以从中获取自己想要的。

Python为了处理大数据“简单的”,“高效”,“智能”的脚本语言。接下来就开始Python的学习之路。

变量的定义和初始化操作

APPLE_EGG = 20appleEgg = 50apple = 10+13a, b, c = 1, 2, 3print(apple)print(a, b, c)

定义一个变量,以便自己在后面使用这个。define a variable and can use it

说明:变量定义可以是APPLE_EGG全部大写,做常量使用。可以使用连接符”_“,可以使用”驼峰类型”

while循环使用

condition = 1while condition < 10:    print(condition)    condition = condition+1;print('end')

循环条件在条件后面要加“:”,使用缩进符号来表示“块”代码属于while循环内。

说明:print关键词后面需要加"()",单引号和双引号都可以作为表示字符串。

for循环使用

# forexample_list = [1,2,3,4,5,6,7]total_val = 0for 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 programif x >= y <= z:    print('x is greater than y and y is less than z')else:    print('result is not our respect')# if elif elseif 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 = 100def func():    a = 10    print('global var:', APPLE)    return aprint('local var:', func())# example 2#val = Nonedef func2():    global val    val = 20    return val+20print(func2())print(val)

全局和局部变量的使用,一般和其他的编程语言一样。global val说明在函数中使用的是全局变量。

说明:如果在函数中定义了一个和全局变量一样名字的变量,就使用最近原则,不改变全局变量值。

install 和 uninstall 的使用

# install numpypip install numpy# uninstall numpypip uninstall numpy

windows安装控件需要在cmd下使用pip或者pip3命令。

说明:更新的话 pip install -U numpy

text的使用

# texturetext = 'this is my text \n this is the next line'print(text)# write a text to my_file.txt file flodermy_file = open('my file.txt', 'w')my_file.write(text)my_file.close()# rewrite a text to my flodermy_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 classclass 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 functionnumber = 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 lista_tuple = (1, 2, 34, 5)another_touple = 3, 4, 5, 66, 4a_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 functiondef fuc(a, b):    print('start..')    c = a*b    print('the c is ', c)    # function initial valuedef 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  librarymulti_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 operatora_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'] = 3print('add dictionary:', dictionary)print(dictionary['watermelon']['w'])

字典的使用是十分随意的,可以通过任意类型指定任意类型。

import导入需要的包,python不是本省就有,需要自己加。

# import timeimport time as tprint(t.localtime())print(t.time())from time import time, localtimeprint(time())print(localtime())from time import *# own write import

说明:可以自定义一个包,通过调用使用。

continue和break的使用

# continue and breakBOOLTYPE = Truewhile BOOLTYPE:    val = input('get number:')    if val == 'hello':        BOOLTYPE = True        continue    else:        BOOLTYPE = False        print('willing break block')        breakprint('continue and break test')

使用和其他的编程语言一样使用。

try except Exception as e使用

# try catch errorimport time as ttry:    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:        passelse:    file.write(str(t.time()))    file.close()    print('output current time to hello.txt file')

通过捕获异常来处理数据。

说明:和C++中的try catch类似

zip map lambda的使用

# zip lamda mapaList = [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+yprint(func2(1, 2))print('map...')map(func1, [1], [2])             # objectlist(map(func1, [2,3], [4,5]))   # result [257, 566]
zip是对象的数据合并,map是处理函数,lambda是缩短函数定义。

copy包含了deep and shallow

# shallow copy and deepcopyimport copya = [1, 2, 3]b = a# shallow copyprint(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);# deepcopyprint('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]复制的地址是一致的。


原创粉丝点击