python十分钟教程_10分钟学Python:极简Python教程

这是一篇极简Python教程,简单到谈不上是教程,更类似Python知识点的备忘或注记,力图在10分钟之内让你明白Python的基本概念,仅仅带你入门,不做深入讨论。

本文适用于Python 3。话不多说,直接入题。

【语言特性】

Python是强类型的语言:对变量只能执行当前类型定义的操作。

支持动态及隐式变量声明:不需要显式声明变量的类型,可以更改变量指向的对象从而改变其类型。

Python变量名大小写敏感:var和VAR是两个不同的变量。

Python是面向对象的:Python中一切皆为对象。

【获得帮助】

在Python解释器中可以随时获取帮助信息。

help() 可以知道对象是怎么工作的;

dir() 可以获取对象包含的属性和方法;

.__doc__ 可以显示对象的文档字符串。>> help(5)Help on int object:(...)>>> dir(5)['__abs__', '__add__', ...]>>> abs.__doc__Return the absolute value of the argument.

【语法规则】

Python中的语句不含结束符(不像c/c++那样以分号结尾)。

通过缩进定义一个代码块:以缩进开始,以回缩结束。语句末尾使用冒号(:)开始一个代码块。

单行注释以#开头,通过多行字符串(''' blabla ''')定义多行注释。

等号(=)用于给变量赋值(实际上是将对象绑定到一个变量名,也即变量名是对象的引用),双等号(==)用于相等判断。

+=和-=操作符用于对变量指向递增和递减操作,这两个操作符适用于多种数据类型,包括字符串。

可在一行代码中同时操作多个变量。#变量赋值与递增递减>>> myvar = 3>>> myvar += 2>>> myvar5>>> myvar -= 1>>> myvar4#多行注释"""This is a multiline comment.The following lines concatenate the two strings."""#使用+=进行字符串连接>>> mystring = "Hello">>> mystring += " world.">>> print(mystring)Hello world.# 同一行代码中操作连个变量:交换其值.# 注意,这两个变量非同一类型。这里的交换实际上分别构造了两个新对象,然后将其绑定到原来的变量名>>> myvar, mystring = mystring, myvar

【数据结构】

Python内置多种数据结构:list、tuple、set和dict。

list类似一维数组(支持list嵌套),dict是关联数组,tuple为不可变的list。这三个数据结构可以混合存储各种类型的数据。

Python“数组”下标起始为0,支持负数。负值表示从末尾开始索引,-1代表最后一个元素。

Python变量也可以指向函数。#list,混合多种类型数据,支持嵌套>>> sample = [1, ["another", "list"], ("a", "tuple")]#通过下标访问list>>> mylist = ["List item 1", 2, 3.14]>>> mylist[0] = "List item 1 again" # We're changing the item.>>> mylist[-1] = 3.21 # Here, we refer to the last item.#dict及其访问>>> mydict = {"Key 1": "Value 1", 2: 3, "pi": 3.14}>>> mydict["pi"] = 3.15 # This is how you change dictionary values.#tuple>>> mytuple = (1, 2, 3)#指向函数的变量>>> myfunction = len>>> print(myfunction(mylist))3

可以使用分号(:)访问指定范围的数组元素。

这种方式称为切片,用法为:

array[startIndex, endIndex, step]

startIndex为起始元素索引,endIndex为结束元素索引,

step为步长(默认为1)。

endIndex所在的元素并不包含在切片结果中,因此,

[,,]记法相当于数学中的左闭右开[)。>>> mylist = ["List item 1", 2, 3.14]#访问所有元素>>> print(mylist[:])['List item 1', 2, 3.1400000000000001]#索引为整数>>> print(mylist[0:2])['List item 1', 2]#索引为负数>>> print(mylist[-3:-1])['List item 1', 2]>>> print(mylist[1:])[2, 3.14]# 步长为2>>> print(mylist[::2])['List item 1', 3.14]

【字符串】

Python中的单行字符串是引号包含的一串字符,可以使用单引号或双引号。这两种引号可以互相包含,但必须成对使用。比如:'He said "hello"'。

Python支持多行字符串,通过三引号(‘’‘blabla‘’‘’)来定义。

Python字符串编码方式为Unicode。

Python支持以b开头的字节字符串,如:b'Hello \xce\xb1'。

Python支持使用以下方法对字符串进行格式化:%:                 '%type_of_var' % (var)

str.format:    '{}'.format(var)

f-strings:       f‘{var}’#%>>>print("Name: %s\Number: %s\String: %s" % (myclass.name, 3, 3 * "-"))Name: StavrosNumber: 3String: ---#多行字符串strString = """This isa multilinestring."""# WARNING: Watch out for the trailing s in "%(key)s".>>>print("This %(verb)s a %(noun)s." % {"noun": "test", "verb": "is"})This is a test.#str.format>>>name = "Stavros">>>"Hello, {}!".format(name)Hello, Stavros!#f-strings>>>print(f"Hello, {name}!")Hello, Stavros!

【流程控制】

Python中流程控制语句包含if、for和while。if用于选择分支,for用于迭代。

可以使用range()获得1个数字序列。>>>print(range(10))range(0, 10)>>>rangelist = list(range(10))>>>print(rangelist)[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]for number in range(10):if number in (3, 4, 7, 9):breakelse:continueif rangelist[1] == 2:print("The second item (lists are 0-based) is 2")elif rangelist[1] == 3:print("The second item (lists are 0-based) is 3")else:print("Dunno")while rangelist[1] == 1:print("We are trapped in an infinite loop!")

【函数】

使用def来定义一个函数。函数可带有若干参数,带有默认值的参数称为可选参数,需要位于必选参数之后。

函数可以通过返回tuple的方式来返回多个值,使用tuple解压方法可以获得这些返回值。

Python支持匿名函数(lambda),这些函数通常只包含单条语句,用在一些简单的计算场景。

Python参数以引用方式进行传递,但是如果参数是不可变类型(tuple、int、string等),函数内部对这些参数的修改不会影响到它们原来的值。#匿名函数funcvar = lambda x: x + 1>>> print(funcvar(1))2# an_int和a_string是可选参数,它们带有默认值。#这里,an_int和a_string都是不可变类型,函数内部对其赋值,并不影响调用者环境里的原值def passing_example(a_list, an_int=2, a_string="A default string"):a_list.append("A new item")an_int = 4return a_list, an_int, a_string>>> my_list = [1, 2, 3]>>> my_int = 10>>> print(passing_example(my_list, my_int))#这里,an_int的输出值为4([1, 2, 3, 'A new item'], 4, "A default string")>>> my_list[1, 2, 3, 'A new item']>>> my_int#my_int仍保持原值10

【类】

通过关键字class来定义一个类,实现数据和代码的封装。

类中私有变量和私有方法可通过下划线(_)前缀的方式进行声明。比如:_m_var。#类的定义class MyClass(object):#定义一个类变量,common为所有实例共享common = 10#初始化函数def __init__(self):#通过self定义成员变量,每个实例拥有自己的变量self.myvariable = 3#成员函数def myfunction(self, arg1, arg2):return self.myvariable# This is the class instantiation#定义一个实例>>> classinstance = MyClass()>>> classinstance.myfunction(1, 2)3>>> classinstance2 = MyClass()#两个实例中共享一个common变量>>> classinstance.common10>>> classinstance2.common10# 通过类名修改共享变量>>> MyClass.common = 30>>> classinstance.common30>>> classinstance2.common30# 通过实例名修改类变量时,实例中的共享变量被绑定到新的对象上>>> classinstance.common = 10# 不再影响到其他实例>>> classinstance.common10>>> classinstance2.common30#也不再受原共享变量的影响>>> MyClass.common = 50>>> classinstance.common10>>> classinstance2.common50#继承class OtherClass(MyClass):def __init__(self, arg1):self.myvariable = 3print(arg1)>>> classinstance = OtherClass("hello")hello>>> classinstance.myfunction(1, 2)3# 可以动态给实例(而非类)增加成员。这并非良好的设计风格。>>> classinstance.test = 10>>> classinstance.test10

Python类支持有限的多重继承:

class OtherClass(MyClass1, MyClass2, MyClassN)

【异常处理】

通过try-except代码块处理异常。def some_function():try:10 / 0except ZeroDivisionError:#捕获异常print("Oops, invalid.")else:#无异常passfinally:# 无论何时try代码块都最终会执行到这里print("We're done with that.")>>>some_function()Oops, invalid.We're done with that.

【模块导入】

可通过import来导入外部模块,也可以通过from ... import ...来导入模块中的变量或方法。import randomfrom time import clockrandomint = random.randint(1, 100)>>>print(randomint)64

【文件I/O】

Python包含众多的内置库。比如,可以使用pickle完成对象序列化到文件的操作。import pickle#将list序列化到文件mylist = ["This", "is", 4, 13327]myfile = open(r"C:\\binary.dat", "wb")pickle.dump(mylist, myfile)myfile.close()#写文件myfile = open(r"C:\\text.txt", "w")myfile.write("This is a sample string")myfile.close()#读文件myfile = open(r"C:\\text.txt")>>>print(myfile.read())'This is a sample string'myfile.close()#从文件读出listmyfile = open(r"C:\\binary.dat", "rb")loadedlist = pickle.load(myfile)myfile.close()>>>print(loadedlist)['This', 'is', 4, 13327]

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值