当前位置:   article > 正文

python速成一小时_Python一小时入门

python1h速成

基础语法

变量定义:

test = 1

test2 = 'abc'

区块 使用 :与缩进对齐来标示一个区块, 如其他语言中大括号中内容

if True:

a = 1

b = 2

...

函数定义

def fun(a, b, c = 1, d = 'a'):

print(a, b, c)

# 可变参数与缺省参数可以同时使用

def fun2(*nums, end='\n'):

for n in nums:

print(n)

print(end)

控制结构

if cond1 or cond2 and cond3 and not cond4:

pass

elif condition:

pass

else:

pass

# 列表或者迭代器

for i in range(5):

print(i);

a = 5;

while a > 0:

print(a)

a = a - 1

容器

# 列表

l = [1, 2, 'a', 'abc']

l.append('end')

l.remove('a')

l.pop(3)

# tuple 不可更改 但是可以更改内部的list元素

t = (1,) # 单个元素必须后续逗号,否则就不是tuple了

t = ('a', 1, [1, 2])

# dict

d = {'a':1, 'b':2, 'c':[1,2,3]}

d.get('d', -1) # 无值时返回提供的默认值

# set 支持并集 交集

s = set([1,2,3]) # 使用列表来初始化

s1 = set([3,4])

print(s & s1) # (3,)

print(s | s1) # (1,2,3,4)

# 容器的切片功能

l[0:3] 或 l[:3] 获取前三项

l[3:] # 获取第三到最后一项

l[-3:] # 最后三项

l[::-1] # 倒序

L[:10:2] # 前10个每两个选一个

关键字

import keyword

print(keyword.kwlist)

['False', 'None', 'True', 'and', 'as', 'assert', 'break', 'class',

'continue', 'def', 'del', 'elif', 'else', 'except', 'finally',

'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda',

'nonlocal', 'not', 'or', 'pass', 'raise', 'return', 'try',

'while', 'with', 'yield']

读写文件

import os

f = open(filepath, 'r')

f = open(filepath, 'r', encoding='gbk', errors='ignore')

f.read() # 全部读取

f.read(size) # 读取指定大小

f.readlines() # 读取所有并每一行放在列表中

f.write("something")

f.close()

# 使用with 则不用手动调用close 保证关闭

with open(filepath, 'w') as f:

pass

# path 相关

os.path.join('/Users/michael', 'testdir') # 链接路径 返回字符串

os.path.split('/Users/michael/testdir/file.txt') # 分拆路径最后的文件名 或 最后的路径,返回tuple

os.path.splitext('/path/to/file.txt') # 分拆扩展名 返回tuple

# 当前目录下所有的文件夹

[x for x in os.listdir('.') if os.path.isdir(x)]

面向对象

class TestClass(object): # 继承 object 也可以继承其他类

__slots__ = ('name', 'age') # 特殊变量 __slots__可以限制可能存在的成员

static_name = 'TestClass' # 相当于静态变量 可以通过class直接访问

# __init__相当于构造函数

# 所有函数的第一个参数都要是self 除非不需要对象的‘静态函数’?

def __init__(self, name):

self.name = name # 这里定义self的各个字段

self.load(name) # 调用函数使用self调用

def load(self, name):

pass

# 以__开头的函数或成员为private 实际上是被重命名了,加了 _TestClass前缀

def __private_fun(self):

pass

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/知新_RL/article/detail/721014
推荐阅读
相关标签
  

闽ICP备14008679号