Python 是一种面向对象的、解释型的、通用的、开源的脚本编程语言。它简单易用,学习成本低,且拥有众多标准库与第三方库。现如今,python在web应用开发、自动化运维、人工智能、网络爬虫、科学计算上都有了广泛的应用。本文旨在利用5分钟时间带你了解python。
python特性
Python 是动态、隐式类型(即不必声明变量)、区分大小写(即var和VAR是两个不同的变量)和面向对象(即一切都是对象)。
获取帮助
当我们想了解一个函数或对象的时候,我们可以调用help(object),或者是dir(object),它会显示对象的所有方法,以及object.doc,它会获取这个对象的注释内容也就是描述信息。
help(int)
Help on class int in module builtins:
class int(object)
| int(x=0) -> integer
| int(x, base=10) -> integer
|
| Convert a number or string to an integer, or return 0 if no arguments
| are given. If x is a number, return x.__int__(). For floating point
| numbers, this truncates towards zero.
……
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| denominator
| the denominator of a rational number in lowest terms
|
| imag
| the imaginary part of a complex number
|
| numerator
| the numerator of a rational number in lowest terms
|
| real
| the real part of a complex number
dir(int)
['__abs__',
'__add__',
'__and__',
'__bool__',
'__ceil__',
'__class__',
'__delattr__',
'__dir__',
'__divmod__',
……
'bit_length',
'conjugate',
'denominator',
'from_bytes',
'imag',
'numerator',
'real',
'to_bytes']
int.__doc__
"int(x=0) -> integer\nint(x, base=10) -> integer\n\nConvert a number or string to an integer, or return 0 if no arguments\nare given. If x is a number, return x.__int__(). For floating point\nnumbers, this truncates towards zero.\n\nIf x is not a number or if base is given, then x must be a string,\nbytes, or bytearray instance representing an integer literal in the\ngiven base. The literal can be preceded by '+' or '-' and be surrounded\nby whitespace. The base defaults to 10. Valid bases are 0 and 2-36.\nBase 0 means to interpret the base from the string as an integer literal.\n>>> int('0b100', base=0)\n4"
语法
Python 的代码块不使用大括号 {} 来控制类、函数以及其他逻辑判断。python最具特色的就是用缩进来写模块,它缩进的数量是可变的,但是所有代码块语句必须包含相同的缩进空白数量。如需注释以井号#开头,是单行的,或使用’’’ ‘’'来进行多行注释。使用等号=来分配值,将等号=右边的值赋给左边的变量,并且使用两个等号==来判断符号两边是否相等。同时我们也可以分别使用+=和-=运算符按右侧的数量递增/递减值。这适用于许多数据类型,包括字符串。我们还可以在一行上使用多个变量。
"""
多
行
注
释
"""
num = 1
num += 2
print (num)
str_ = 'hello'
str_ += ' world'
print (str_)
num, str_ = str_, num
print ('now num is ', num)
print ('now str_ is ', str_)
3
hello world
now num is hello world
now str_ is 3
数据类型
python有5个标准的数据类型,分别是string(字符串)、numbers(数字)、list(列表)、tuple(元组)、dictionary(字典)
字符串
python字符串可以使用单引号或双引号,并且可以在使用另一种类型的字符串中包含一种类型的引号(即"He said ‘hello’.“是有效的)。Python字符串内存编码始终是 Unicode。多行字符串包含在三重双(或单)引号(”"")中。当我们需要将值填入字符串中时,可以使用%加元组的形式,每个%s都被元组中的一个项替换,从左到右,也可以使用format。
print ("my name is %s" % ("little Q"))
print ("""This is
a multiline
string.
""")
print ("%(name)s is %(nationality)s"%{'name':'Q','nationality':'Chinese'})
name = 'Q'
print ("Hello,{}".format(name))
print (f"Hello,{name}")
my name is little Q
This is
a multiline
string.
Q is Chinese
Hello,Q
Hello,Q
数字
Python Number 数据类型用于存储数值。数据类型是不允许改变的,这就意味着如果改变 Number 数据类型的值,将重新分配内存空间。数字类型是数值型数据,支持整型、浮点、布尔类型和复数。数值型即数值数据,用于表示数量,并可以进行数值运算。数值型数据由整数、小数、布尔值和复数组成,分别对应整型类型、浮点类型、布尔类型和复数类型。
列表
列表在python中的使用很频繁,列表可以完成大多数集合类的数据结构实现。它支持字符,数字,字符串甚至可以包含列表(即嵌套)。列表用[]标识。列表是有序可变的,在列表中第一项索引为0。可以通过:来来对列表进行切片操作,将冒号前面的作为索引的第一项,冒号后面的作为结束索引,但不包含最后一项。同时将-1作为逆索引的第一项。
list_sample = [1, 'Q', ['another', 'list'],'q']
print(list_sample[0])
list_sample[0] = 2
print (list_sample)
print (list_sample[:2])
print (list_sample[-1])
1
[2, 'Q', ['another', 'list'], 'q']
[2, 'Q']
q
元组
元组类似于列表,但元组不能二次赋值,相当于只读。
tuple_sample = (1, 'Q', ['another', 'list'],'q')
print (tuple_sample[0])
print (tuple_sample * 2)
1
(1, 'Q', ['another', 'list'], 'q', 1, 'Q', ['another', 'list'], 'q')
字典
字典是python中除列表外最为灵活的数据结构,字典是无序的,用于存放具有映射关系的数据,它把“键”(key)映射到“值”(value),通过key可以快速找到value。字典的每个键值对用冒号 : 分割,每个键值对之间用逗号 , 分割,整个字典包括在花括号 {} 中。“键”,可以是任意不可变的类型对象,“值”可以是任何类型的数据。
d1 = {'a': 1, 'b': [1,2], 'c': 'my name is Q'}
d1['d'] = 'append new value'
print (d1['a'])
print (d1.keys())
print (d1.values())
1
dict_keys(['a', 'b', 'c', 'd'])
dict_values([1, [1, 2], 'my name is Q', 'append new value'])
控制语句
python中控制语句有if,for和while。使用for枚举列表的元素。要获得可以迭代的数字序列,请使用range(number)。
print(range(10))
rangelist = list(range(10))
print(rangelist)
for number in range(10):
if number in (3, 4, 7, 9):
print (number)
else:
continue
print ('*' * 20)
n = 10
while n !=0:
print (n)
n-=1
range(0, 10)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
3
4
7
9
********************
10
9
8
7
6
5
4
3
2
1
函数
函数是用def关键字声明的。通过分配默认值,在强制参数之后的函数声明中设置可选参数。对于命名参数,参数的名称被赋予一个值。函数可以返回一个元组(并且使用元组解包可以有效地返回多个值)。Lambda 函数是由单个语句组成的临时函数。参数通过引用传递,但被调用者不能在调用者中更改不可变类型(元组、整数、字符串等),这是因为只传递了项目的内存位置。函数内容以冒号起始,并且缩进。
# 与def funcvar(x)相同,返回x+1
funcvar = lambda x: x + 1
print(funcvar(1))
#这里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 = 4
return a_list, an_int, a_string
my_list = [1, 2, 3]
my_int = 10
print (passing_example(my_list, my_int))
print (my_list)
print (my_int)
2
([1, 2, 3, 'A new item'], 4, 'A default string')
[1, 2, 3, 'A new item']
10
类
类用来描述具有相同的属性和方法的对象的集合。它定义了该集合中每个对象所共有的属性和方法。对象是类的实例。类变量在整个实例化的对象中是公用的。类变量定义在类中且在函数体之外。类变量通常不作为实例变量使用。在Python中,类通过class关键字定义,类名通用习惯为首字母大写,Python3中类基本都会继承于object类。
class MyClass(object):
common = 10
def __init__(self):
self.myvariable = 3
def myfunction(self, arg1, arg2):
return self.myvariable
# 类的实例化
classinstance = MyClass()
classinstance.myfunction(1, 2)
# 变量会被所有实例共享
classinstance2 = MyClass()
print (classinstance.common)
print (classinstance2.common)
# 这里更改类的变量
MyClass.common = 30
print (classinstance.common)
print (classinstance2.common)
# 这样改不了类的变量
classinstance.common = 10
print (classinstance.common)
print (classinstance2.common)
MyClass.common = 50
#这里因为已经是一个实例变量,所以没变
print (classinstance.common)
print (classinstance2.common)
#这个类继承自上面的MyClass
class OtherClass(MyClass):
def __init__(self, arg1):
self.myvariable = 3
print(arg1)
classinstance = OtherClass("hello")
print (classinstance.myfunction(1, 2))
#这里向实例添加了一个test,但是这只在classinstance中生效
classinstance.test = 10
print (classinstance.test)
10
10
30
30
10
30
10
50
hello
3
10
异常
Python中的异常由try-except来处理。
def some_function():
try:
#除以0引发异常
10 / 0
except ZeroDivisionError:
print ("发生错误")
else:
pass
finally:
#在代码块运行后执行
print ("完成")
some_function()
发生错误
完成
导入
当需要导入外部库时,使用import [libname],也可以使用from libname import funcname来使用。
import random
from time import clock
randomint = random.randint(1, 100)
print (randomint)
14
文件I/O
Python内置了大量库。如利用open等函数进行文件的读写
#打开文件
myfile = open(r"D:\\my_file.txt", "w")
#写入
myfile.write("My name is Q")
myfile.close()
newfile = open(r"D:\\my_file.txt")
print (newfile.read())
newfile.close()
My name is Q
总结
Python拥有大量库与极为丰富的功能,本文并没有列举python所有的知识点与方法,只是带你初步了解python,希望能对你学习python有所帮助。