python基本语法

记录python的基本语法格式,便于快速查看

主要是对vamei君的教程:https://www.cnblogs.com/vamei/tag/Python/default.html?page=4 的一个摘要,感谢vamei的python教程,在此缅怀。

1. 基本数据类型

#basic data type

#使用分数
import fractions

a = 10
print(a) #10
print(type(a)) #<class 'int'>


a = 1.3
print(a) #1.3
print(type(a)) #<class 'float'>


a = True
print(type(a)) #<class 'bool'>


a = 'Hello'
print(type(a)) #<class 'str'>


a = 'W'
print(type(a)) #<class 'str'>


a = "E"
print(type(a)) #<class 'str'>


a = fractions.Fraction(1, 2) 
print(a) #1/2
print(type(a)) #<class 'fractions.Fraction'>


a = complex(2, 3)
print(a, type(a)) #(2+3j) <class 'complex'>


#tuple
s1 = (2, 2.6, 'Morning', 8.3, False)
print(s1, type(s1))  #(2, 2.6, 'Morning', 8.3, False) <class 'tuple'>

#tuple已经初始化后就不可更改
s1[0] = 9 #TypeError: 'tuple' object does not support item assignment


print(s1[2:])        #('Morning', 8.3, False)
print(s1[0:5:2])     #(2, 'Morning', False)
print(s1[5:0:-2])    #(False, 'Morning')
print(s1[5:0:-1])    #(False, 8.3, 'Morning', 2.6)
print(s1[0:5:1])     #(2, 2.6, 'Morning', 8.3, False)
print(s1[-1])        #False  

print(s1[:5])        #(2, 2.6, 'Morning', 8.3, False)

print(s1[:3])        #(2, 2.6, 'Morning')

print(s1[:100])      #(2, 2.6, 'Morning', 8.3, False)


#list
s2 = [1, 2.3, 'world', 8, True]
print(s2, type(s2)) #[1, 2.3, 'world', 8, True] <class 'list'>


#可以进行嵌套
s4 = [1, 2, [3, 4, 5, [6, 7, 8]]]
print(s4) #[1, 2, [3, 4, 5, [6, 7, 8]]]


#空的list
s5 = []
print(s5)  #[]

str = 'abcdefghijklmnopqrstuvwxyz'
print(str[2:8], type(str))    #cdefgh <class 'str'>
str[3] = 'h'                  #TypeError: 'str' object does not support item assignment

2.  控制语句

  if条件语句:

if 2<3:
    print("Hello")
print(2+3)

#Hello
#5



i = -1

if i > 0:
    print('postive i')
elif i == 0:
    print('i equals to 0')
else:
    print('negtive i')

#negtive i

for循环语句:

#对list等的遍历, 关键字"in"的用法
for a in [3, 4.4, 'hello']:
    print(a)

#3
#4.4
#hello



for a in range(10):
    print(a**2)

#0
#1
#4
#9
#16
#25
#36
#49
#64
#81

while循环:

i = 3
while i < 6:
    print(i)
    i = i + 1
#3
#4
#5

continue:

for a in range(4):
    if(a == 2):
        continue
    print(a)

#0
#1
#3

break:

for a in range(4):
    if(a == 2):
        break
    print(a)

#0
#1

 

3. function:

def squre_sum(a, b):
    c = a**2 + b**2
    return c

print(squre_sum(3, 4))

#25

传值与传指针(引用):

a = 1

def change_integer(a):
    a = a + 1
    return a

print(change_integer(a))
print(a)

#对于基本数据类型,函数传参时传递的是一份拷贝,即传值
#2
#1

b = [1, 2, 3]
def change_list(b):
    b[0] = b[0] + 1
    return b

print(change_list(b))
print(b)

#对于非基本数据类型,传递的是指针(即引用),不会进行值的拷贝,所以会改变原来的值(未对所有的内建的非基本数据类型进行测试)
#[2, 2, 3]
#[2, 2, 3]

类的定义:

class Bird(object):
    have_feather = True
    way_of_reproduction = 'egg'
    
    def Mov(self, dx, dy):
        position = [0, 0]
        position[0] = position[0] + dx
        position[1] = position[1] + dy
        return position

summer = Bird()
print(summer.have_feather, summer.way_of_reproduction)
#True egg

print(summer.Mov(2, 3))
#[2, 3]

类的继承:

class Bird(object):
    have_feather = True
    way_of_reproduction = 'egg'
    
    def Mov(self, dx, dy):
        position = [0, 0]
        position[0] = position[0] + dx
        position[1] = position[1] + dy
        return position


class Chicken(Bird): #将要继承的类写在括号里
    way_of_move = 'walk'
    possible_in_KFC = True
    
class Oriole(Bird):
    way_of_move = 'fly'
    possible_in_KFC = False
    

summer = Chicken()
print(summer.have_feather, summer.way_of_move, summer.possible_in_KFC)
#True walk True

类中调用类自身的成员方法:

class Human(object):
    laugh = 'aaaaa'
    
    def show_laugh(self):
        print(self.laugh)
    
    def laugh_5th(self):
        for i in range(5):
            self.show_laugh() #通过self调用自己的方法
            #show_laugh()  #没有self是不能识别的
            
li_lei = Human()
li_lei.laugh_5th()

#aaaaa
#aaaaa
#aaaaa
#aaaaa
#aaaaa

类中调用自身的成员变量:

class Human(object):
    laugh = 'aaaaa'
    
    def show_laugh(self):
        print(self.laugh)
    
    def laugh_2th(self):
        for i in range(2):
            laugh = 'bbbbb' #被认为是定义了一个新的局部变量laugh,而不是对类的成员变
                            #量laugh的赋值,故对自身成员变量的引用都要使用self前缀
            print(laugh)
            print(self.laugh)
            
li_lei = Human()
li_lei.laugh_2th()

#bbbbb  #局部变量laugh
#aaaaa  #成员变量laugh
#bbbbb
#aaaaa

__init__函数:

class Bird(object):
    have_feather = True
    way_of_reproduction = 'egg'
    
    def __init__(self, words):  #类的初始化函数,在对象被创建后会被自动调用
        print(words)
    
    def Mov(self, dx, dy):
        position = [0, 0]
        position[0] = position[0] + dx
        position[1] = position[1] + dy
        return position
      
summer = Bird("Happy, Happy")

通过__init__函数来初始化成员变量:

class Human(object):
    def __init__(self, input_gender):
        self.gender = input_gender
    def printGender(self):
        print(self.gender)

li_lei = Human('male') # 这里,'male'作为参数传递给__init__()方法的input_gender变量。
print(li_lei.gender)
li_lei.printGender()

#male
#male

 

dir, help两个函数查看类的属性:

比如:dir(list), help(list)

 

特殊方法的重写:

print [1,2,3] - [3,4]
#TypeError: 'builtin_function_or_method' object is not subscriptable
#运算符作为特殊的操作符,‘-’在list中被定义为__sub__, 但这里因为内置的函数
#中要求长度一致,所以不能相减
#但我们可以通过继承的方式来重新定义list的“-”
class superList(list):
    def __sub__(self, b):
        a = self[:]     # 这里,self是supeList的对象。由于superList继承
                        #于list,它可以利用和list[:]相同的引用方法来表示整个对象。
        b = b[:]        
        while len(b) > 0:
            element_b = b.pop()
            if element_b in a:
                a.remove(element_b)
        return a

print(superList([1,2,3]) - superList([3,4]))

#[1, 2]

词典:

1)元素为键-值对

2)元素是没有顺序的

dic = {'tom':11, 'jerry':22, 'tony':33}
print(dic, type(dic))

#{'tom': 11, 'jerry': 22, 'tony': 33} <class 'dict'>

#添加一个新的元素
dic['Harry'] = 55
print(dic)

#{'tom': 11, 'jerry': 22, 'tony': 33, 'Harry': 55}

#遍历元素
for key in dic:
    print(dic[key])
#11
#22
#33
#55

print(dic.keys())
#dict_keys(['tom', 'jerry', 'tony', 'Harry'])

print(dic.values())
#dict_values([11, 22, 33, 55])

print(dic.items())
#dict_items([('tom', 11), ('jerry', 22), ('tony', 33), ('Harry', 55)])
    

key_list = dic.items()
for item in key_list:
    print(item)
#('Harry', 55)])
#('tom', 11)
#('jerry', 22)
#('tony', 33)
#('Harry', 55)

文件操作:

open(filename, mode).其中mode:

'r' when the file will only be read

'w' for only writing (an existing file with the same name will be erased)

'a'  opens the file for appending; any data written to the file is automatically added to the end

'r+'  opens the file for both reading and writing. The mode argument is optional; 

'r'  will be assumed if it’s omitted. 缺省时为 ' r '

fd = open("test.txt", "r+")
fd.write("Hello World\n")

buf = fd.readline()
print(buf)
#Hello World

fd.close()

使用with语句进行操作:

with open("test.txt", 'r') as f:
    read_data = f.read()
    print(read_data)
    #输出文件内容

f.read()
#ValueError: I/O operation on closed file.
#with语句结束后,f已经被关闭

 

模块:

#文件test.py
def Test():
    print("testing ...")

#文件user.py
import test  #引入test模块

for i in range(3):
    test.Test()   #通过模块.对象来调用模块中的对象

#testing ...
#testing ...
#testing ...

引入模块的格式有:

import a as b     #引入模块a,并将模块a重命名为b
from a import function1 #引入模块a中的function1对象,相当于C++中using namespace XXX,之后
                        #就可以直接使用function1, 而不用a.function1
from a import *    #引入a中的所有对象,这样可以直接使用a中的对象,而不用a.XX,不推荐这种

python解释器搜索包时的路径:

     参考:https://blog.csdn.net/colourful_sky/article/details/79672279

     1.当前文件夹路径

     2.PYTHONPATH环境变量所对应文件路径

     3.Python安装的标准链接库等文件夹路径

     4.PTH文件列出的文件夹路径

模块包:

from picture.filters import gaussblur   #picture是一个包,filters是包里面的一个模块

包中必须包含一个文件__init__.py

详解可以参考: https://liam.page/2017/07/23/modules-and-packages-of-python/

 

迭代器:

list = [1, 2, 3, 4]
it = iter(list)  #创建迭代器
for x in it:
    print(x, end=' ')
#1 2 3 4

创建对象的迭代器:

http://www.runoob.com/python3/python3-iterator-generator.html

实现__iter__() , __next__()方法

StopIteration 异常用于标识迭代的完成,防止出现无限循环的情况

配合yield关键字

 

Lambda函数:

#x,y为参数, x*y为对参数的处理,并且表达式会返回x*y
func = lambda x,y: x*y
print(func(2,3))
#6

#等价于:
def func(x,y):
    return x*y

函数作为参数:

def func(x,y):
    return x*y

def test(f, a, b):
    print('test')
    print(f(a,b))

test(func,2,3)
#test
#6    

map()函数:

将定义的函数依次作用于后面的参数,并返回一个循环对象

def square(x):
    return x**2
mmap = map(square, [1,2,3,4,5]) #返回一个循环对象,用迭代器处理
for item in mmap:
    print(item)
#1
#4
#9
#16
#25

#多组参数时
mmap = map(lambda x,y: x+y, [1,2,3], [10,11,12])
for item in mmap:
    print(item)    
#11
#13
#15

filter()函数:

将定义的函数依次作用于后面的参数,如果函数结果为True,则将对应的输入放到返回的迭代器中。

def bigger_than_five(x):
    if x > 5:
        return True
    else:
        return False
    
filmap = filter(bigger_than_five, [2, 3, 7, 4, 5, 6])
for item in filmap:
    print(item)
#7
#6

reduce()函数:

import functools as fc

result = fc.reduce(lambda x,y:x*y, range(1, 10))  #依次作用在参数上并将上一次的结果作为下一
                                                  #次运算的参数再进行计算,这里是求10的阶乘
print(result)
#362880

异常处理:

try:
    print(2/0) #产生除以0的异常
except TypeError:
    print("TypeError")
except ZeroDivisionError:
    print("ZeroDivisionError")

#ZeroDivisionError

异常没有被捕获时自动向更上层抛出:

def error_test():
    try:
        open("sdljfl.txt", 'r')  #只读打开一个不存在的文件
    except TypeError:
        print("TypeError")
    except ZeroDivisionError:
        print("ZeroDivisionError")

try:
    error_test() #产生的错误FileNotFoundError在此函数中没有被catch,会抛到此函数的上一层
except FileNotFoundError:
    print('FileNotFoundError')
    
#FileNotFoundError

使用else, finally:

def divide(x, y):
    try:
        result = x / y
    except ZeroDivisionError: #有异常执行
        print("division by zero!")
    else:  #无异常执行
        print("result is", result)
    finally:  #最终都会执行
        print("executing finally clause")

divide(3, 0)
#division by zero!
#executing finally clause

divide(3, 2)
#result is 1.5
#executing finally clause

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值