Python核心语法看这一篇就够了丨【生长吧!Python】

举报
jackwangcumt 发表于 2021/07/09 14:45:49 2021/07/09
【摘要】 Python语言是一门非常流行的编程语言,它功能强大,语法简洁,在当前AI技术大行其道的情况下,作为一个开发者,如果需要开发大数据或者人工智能程序,那么是很难绕开Python的。本文用万字长文对Python中核心的语法进行了详细讲解,其中涉及到注释、变量声明、列表、元组、字典、逻辑判断与循环、函数和类等知识。这里梳理的核心语法知识,对学好Python语言来说具有非常好的参考价值。

       Python语言是一门非常流行的编程语言,特别在当前AI技术大行其道的情况下,非常多的大数据框架和人工智能框架都有大量的Python库。因此,在未来人工智能技术普惠的大背景下,作为一个开发者,通过对Python语言的系统学习,掌握Python语言的基础语法,并学以致用,是非常重要的一项技能。Python语言本身是开源的,而且语法非常的简洁。

       目前来说,Python语言主要有Python2.x和Python3.x两个大版本,而且这两个大版本有些地方是不兼容的。本文对Python3.x基础语法进行重点介绍,通过总结最常用的语法,让初学者可以快速掌握Python的核心语法。

    1 Python 环境安装

       首先,需要在电脑上安装Python开发环境,其中最主要的就是Python SDK的安装。打开浏览器访问https://www.python.org/downloads/网址,根据自己的操作系统,选择合适的版本进行安装。这里安装的是Window x64版本的Python 3.9.6 。下载界面如下图所示:

1.jpg

       其次,需要安装一款好用的Python语言开发工具,这里的IDE就比较多了,个人比较推荐使用微软的Visual Studio Code。它是开源的且可以进行免费使用。其中有大量的免费的插件,可以开发多种语言,比如Java / C# / Python / C++ / HTML / JavaScript 等。一般来说,安装好的Visual Studio Code界面如下:

2.jpg

       最后,我们也可以在命令行中进行Python语言的学习。具体如下图所示:

3.jpg

   2  Python核心语法总结

    任何一门编程语言,为了让其具有维护性,必须要进行合理的代码注释。代码编译后虽然是让计算机去执行的,但是更一般的情况是,代码是写给人看的,因此,不要过于追求技巧,让代码晦涩难懂。并给出合理的代码注释。

    首先,Python语言的代码注释语法如下:

# 单行注释

""" 多行注释
     可以详细介绍
"""

print(7)  # 7 , 注释也可以放于表达式后

   其次,Python中的变量无需显性声明,而是通过赋值进行定义的。变量的类型可以通过赋值进行改变,同一个变量的值可以是字符串,后面也可以根据需要重新赋值为数值类型。Python中的基本数据类型的用法如下:

>>> a = 3
>>> b = 10.0
>>> c = a + b
>>> c
13.0
>>> 35 / 7
5.0
>>> 36 / 7
5.142857142857143
>>> 36 // 7
5
>>> -36 // 7
-6
>>> 36 % 7
1
>>> -36 % 7
6
>>> 2 ** 5
32
>>> bool(0)
False
>>> bool(7)
True
>>> bool(-7)
True
>>> not True
False
>>> True and False
False
>>> True or False
True
>>> True and 0
0
>>> True and 1
1
>>> False and 0
False
>>> False and 1
False
>>> False or 1
1
>>> True + True
2
>>> True * 7
7
>>> 7 * True
7
>>> True - 7
-6
>>> False == 0
True
>>> True == 1
True
>>> True == 2
False
>>> True != 0
True
>>> 0 and 2
0
>>> 0 or 2
2
>>> 1 <= 2
True
>>> 1 <= 2 <= 7
True
>>> 1 <= 7 <= 2
False
>>> name = "jack"
>>> name
'jack'
>>> xh = 'c001'
>>> xh
'c001'
>>> name + xh
'jackc001'
>>> name[0]
'j'
>>> name[0:2]
'ja'
>>> len(name)
4
>>> bool("")
False
>>> bool(None)
False
>>> bool([])
False
>>> bool({})
False
>>> bool(())
False
>>> f"name is {name}"
'name is jack'
>>> age = 22
>>> f"age is {age}" # f后面不能有空格
'age is 22'
>>> 8 * "*"
'********'
# 8 + "*"  //error
>>> "" + str(8)
'8'

   从语法上来说,Python基础数据类型这块的用法非常简介,而且功能强大。这里需要注意不同基础类型的值进行混合计算后的值,比如 True and 1返回1,而8 * "*"则返回'********' 。Python中 1 <=2 <= 3 这种复核的判断,让表达式看起来更加的优雅。字符串可以看作是列表,可以通过下标进行切片。

   再次,给出Python语言的集合(Collections)基本语法,其中要注意一下 == is 的区别。具体用法如下:

>>> a = [1, 2, 3, 4]  # 定义一个新的列表  [1, 2, 3, 4]
>>> b = a             #  a b指向同一个对象
>>> b is a            # => True,  a b指向同一个对象
True
>>> b == a            # => True,  a b对象的值一致
True
>>> b = [1, 2, 3, 4]  # b指向另一新对象,值为 [1, 2, 3, 4]
>>> b is a            # => False, a b指向不同的对象
False
>>> b == a            # => True, a b对象的值一致
True
>>> a = "hello"  
>>> b = a          
>>> b is a          
True
>>> b == a          
True
>>> b = "hello"  
>>> b is a       # => True,  字符串特殊       
True
>>> b == a      
True
>>> alist = []
>>> blist = [1,2,3]
>>> alist.append(4)
>>> alist
[4]
>>> alist.append(5)
>>> alist
[4, 5]
>>> alist + blist
[4, 5, 1, 2, 3]
>>> clist = alist + blist
>>> clist
[4, 5, 1, 2, 3]
>>> clist[0]
4
>>> clist[:]
[4, 5, 1, 2, 3]
>>> clist[:3]
[4, 5, 1]
>>> clist[1:3]
[5, 1]
>>> clist[::3]
[4, 2]
>>> clist[::-1]
[3, 2, 1, 5, 4]
>>> clist[-1]
3
>>> clist[-2]
2
>>> clist.pop()
3
>>> clist
[4, 5, 1, 2]
>>> clist.remove(4)
>>> clist
[5, 1, 2]
>>> clist.index(1)
1
>>> clist.index(5)
0
>>> clist.extend(clist)
>>> clist
[5, 1, 2, 5, 1, 2]
>>> 5 in clist
True
>>> 7 in clist
False
>>> len(clist)
6

Python语言中,列表是用中括号进行定义,我们非常方便的可以对列表中的数据进行维护,比如添加,删除,插入等操作,并可以判断元素是否在列表中。列表中的元素类型可以相同,也可以不同。而除了列表外,还有一个就是元组类型,它用圆括号()进行定义。而大括号{}可以定义Set或字典,这取决于是否有Key。基本用法如下:

>>> a = (1,2,"hello")  # 元组
>>> a[0]
1
>>> a[2]
'hello'
>>> a[0:1]
(1,)
>>> a[0] = 1 #error 元组中元素是不可变对象

>>> type((7)) # 类型检测
<class 'int'>
>>> type((7,))
<class 'tuple'>
>>> type(())
<class 'tuple'>
>>> a[:]  
(1, 2, 'hello')
>>> a[0:2]  #左闭合右开,不好含索引为2的值"hello"
(1, 2)
>>> a[0:3]
(1, 2, 'hello')
>>> len(a)
3
>>> a + (7,8) #元组合并
(1, 2, 'hello', 7, 8)
>>> b = a + (7,8)
>>> 7 in b
True
>>> b
(1, 2, 'hello', 7, 8)
>>> n1,n2,n3 = b # unpack错误,个数不匹配
>>> n1,n2,*n3 = b # *n3可匹配多个值
>>> n1,n2
(1, 2)
>>> n3
['hello', 7, 8]
>>> n1,*n2,n3 = b
>>> n1
1
>>> n2
[2, 'hello', 7]
>>> n3
8
>>> n1,n2 = n2,n1 #交互值
>>> n1
[2, 'hello', 7]
>>> n2
1
>>> dict = {} # 字典
>>> dict["one"] = 1
>>> dict
{'one': 1}
>>> dict[2.5] = 2.5
>>> dict
{'one': 1, 2.5: 2.5}
>>> dict[(1,2)] = (1,2)
>>> dict
{'one': 1, 2.5: 2.5, (1, 2): (1, 2)}
>>> dict[[1,2]] = [1,2] # error  unhashable type: 'list'
>>> dict
{'one': 1, 2.5: 2.5, (1, 2): (1, 2)}
>>> dict.keys()
dict_keys(['one', 2.5, (1, 2)])
>>> list(dict.keys())
['one', 2.5, (1, 2)]
>>> list(dict.values())
[1, 2.5, (1, 2)]
>>> "one" in dict
True
>>> (1,2) in dict
True
>>> 1 in dict
False
>>> dict["key"] # error 不存在的key访问错误
>>> dict.get("key")
>>> dict.setdefault("key","001") #设置值
'001'
>>> dict.update({"key":"002"}) # 更新值
>>> dict
{'one': 1, 2.5: 2.5, (1, 2): (1, 2), 'key': '002'}
>>> myset = set()  # Set 无重复值
>>> myset
set()
>>> myset = {1,1,2,2,3,4}
>>> type(myset)
<class 'set'>
>>> myset
{1, 2, 3, 4}
>>> myset.add(7) # 添加元素
>>> myset
{1, 2, 3, 4, 7}
>>> myset.add((8,9))
>>> myset
{1, 2, 3, 4, 7, (8, 9)}
>>> myset.add([7,8]) # error unhashable type: 'list'
>>> myset2 = {2,7,9}
>>> myset & myset2 # set 交集
{2, 7}
>>> myset | myset2  # set 并集
{1, 2, 3, 4, 7, 9, (8, 9)}
>>> myset - myset2
{(8, 9), 1, 3, 4}
>>> myset ^ myset2
{1, 3, 4, 9, (8, 9)}
>>> {1,2} <= {1,2,7}
True
>>> 7 in {1,2}
False
>>> 2 in {1,2}
True
>>> myset3 = myset.copy()
>>> myset3
{1, 2, 3, 4, (8, 9), 7}
>>> myset3 is myset
False
>>> myset3 == myset
True
>>>

 注意:元组的元素是不可变对象,因此无法重新进行赋值。另外,列表List是一个不能进行hash的数据类型,它不能作为字典的Key或者Set中的元素。

 再次,下面给出Python基本的流程控制语句,比如if条件判断,for循环,while循环等。 Python的代码块是根据缩进进行定义的,而不是通过类似C语言的大括号,因此,同一个代码块的缩进必须要严格一致。具体的用法如下:

>>> # if 条件判断
>>> n = 5
>>> if n > 7:
...     print(f"{n} > 7")
... elif n < 7:
...     print(f"{n} < 7")
... else:
...     print(f"{n} = 7")
...
5 < 7
>>> #for循环
>>> for n in [1,2,3,"hello"]:
...     print(" => {}".format(n))
...
 => 1
 => 2
 => 3
 => hello
>>> nlist = [1,2,3,"hello"]
>>> for i, v in enumerate(nlist):
...     print(i, v)
...
0 1
1 2
2 3
3 hello
>>> #range(lower, upper)或 range(lower, upper, step)
>>> #不支持float
>>> for n in range(1,12,3):
...     print(n)
...
1
4
7
10
>>>
>>> #while 循环
>>> x = 0
>>> while x < 4:
...     if (x == 2):
...         break #退出循环
...     print(x)
...     x += 1
...
0
1
>>> # try..except..finally 异常处理
>>> try:
...     #print(2/0) # ZeroDivisionError: division by zero
...     # raise抛出异常
...     raise TypeError("TypeError")
... except (TypeError, NameError) as e :
...     # pass 跳过
...     print(e)
... else:
...     print("run ok") #正确执行后执行的语句
... finally:
...     print("finally") #总会执行
...
TypeError
finally
>>>

下面在介绍一下Python中的函数,Python可以看作是一门函数式编程语言,函数可以作为参数进行传递,函数可以进行嵌套等,它和普通的数据类型类似。因此合理进行函数的定义,可以实现高阶功能。函数的基本用法如下:

>>> #def 定义函数
>>> def sum(x, y):
...     print("x = {} y = {}".format(x, y))
...     return x + y
...
>>> #函数调用
>>> sum(2, 7)
x = 2 y = 7
9
>>> #顺序可以不一致
>>> sum(y=7, x=2)
x = 2 y = 7
9
>>> #*args 可选个数参数
>>> def sum2(*args):
...     ret = 0
...     for n in args:
...         ret += n
...     return ret
...
>>> sum2()
0
>>> sum2(2,3)
5
>>> sum2(2,3,7)
12
>>> args = (1, 2, 3, 4)
>>> #用*去展开元组,列表等
>>> sum2(*args)
10
>>> sum2(*[2,7])
9
>>> #**kwargs可以指定keyword的可变个数
>>> def fn_kwargs(**kwargs):
...     return kwargs
...
>>> fn_kwargs(func="x^2-1", syms="x")
{'func': 'x^2-1', 'syms': 'x'}
>>>
>>> #用 ** 去展开 kwargs
>>> kwargs = {'func': 'x^2-1', 'syms': 'x'}
>>> fn_kwargs(**kwargs)
{'func': 'x^2-1', 'syms': 'x'}
>>> x = 7
>>> def set_local_x(n):
...     #局部变量x
...     x = n
...
...
>>> def set_global_x(n):
...     global x #全局变量x
...     x = n
...
>>> set_local_x(9)
>>> print(x)
7
>>> set_global_x(9)
>>> print(x)
9
>>> # Python 函数是第一等公民,闭包
>>> def adderCls(x):
...     def addfunc(y):
...         return x + y
...     return addfunc
...
>>> add_7 = adderCls(7)
>>>
>>> add_7(3)
10
>>> # lambda函数
>>> (lambda x, y: x ** 2 + y ** 2)(2, 3)
13
>>> #集合上调用函数
>>> list(map(add_7, [3, 7]))
[10, 14]
>>> list(map(max, [1, 2, 7], [4, 9, 1]))
[4, 9, 7]
>>> list(filter(lambda x: x > 6, [7, 4, 1, 6, 9]))
[7, 9]
>>> [add_7(i) for i in [3,7]]
[10, 14]
>>> [x for x in [7, 4, 5, 6, 9] if x > 6]
[7, 9]
>>> {x for x in 'abc091cdef878' if x not in '0123456789'}
{'f', 'd', 'a', 'b', 'e', 'c'}
>>> {"key"+str(x): x**3 for x in range(1,5)}
{'key1': 1, 'key2': 8, 'key3': 27, 'key4': 64}
>>>

Python中的函数可以和表达式进行混合书写,这样编写的代码非常优雅。而且可以实现很酷的功能。我们知道,函数可以根据功能划分成不同的模块,在Python中为了组织代码,也需要将一个复杂的功能划分为各个模块进行维护。Python导入模块基本用法如下:

>>> # import导入模块
>>> import math
>>> #调用模块下的函数
>>> print(math.sqrt(8))
2.8284271247461903
>>>
>>> #导入特定的函数
>>> from math import sin, floor
>>> print(sin(1))
0.8414709848078965
>>> print(floor(7.1))
7
>>>
>>> #导入所有,有点影响性能
>>> from math import *
>>>
>>> #导入并重命名
>>> import math as mt
>>> print(mt.pow(2,3))
8.0
>>>
>>> # dir可查看模块中的函数或属性定义
>>> import math
>>> dir(math)
['__doc__', '__loader__', '__name__', '__package__', '__spec__', 'acos', 'acosh', 'asin', 'asinh', 'atan', 'atan2', 'atanh', 'ceil', 'comb', 'copysign', 'cos', 'cosh', 'degrees', 'dist', 'e', 'erf', 'erfc', 'exp', 'expm1', 'fabs', 'factorial', 'floor', 'fmod', 'frexp', 'fsum', 'gamma', 'gcd', 'hypot', 'inf', 'isclose', 'isfinite', 'isinf', 'isnan', 'isqrt', 'lcm', 'ldexp', 'lgamma', 'log', 'log10', 'log1p', 'log2', 'modf', 'nan', 'nextafter', 'perm', 'pi', 'pow', 'prod', 'radians', 'remainder', 'sin', 'sinh', 'sqrt', 'tan', 'tanh', 'tau', 'trunc', 'ulp']


最后,介绍一下Python关于OOP编程中的类,这里简单进行介绍类的基本用法,限于篇幅,而不对继承等OOP编程进行特别说明。感兴趣的读者,可以自行收集资料进行学习。类的基本用法如下:

# class 类
class Student:
    #属性定义
    name = "Jack"
    #初始化
    def __init__(self, name, age):     
        self.name = name
        # Initialize property
        self._age = age

    # 实例方法
    def work(self, hw):
        print("{name} do {homework}".format(name=self.name, homework=hw))

    def get_info(self):
        return f"{self.name}"

    #类方法
    @classmethod
    def get_name(cls):
        return cls.name

    #静态方法
    @staticmethod
    def say_msg(msg):
        return f"say {msg}"

    # age getter.
    @property
    def age(self):
        return self._age

    # age setter
    @age.setter
    def age(self, age):
        self._age = age


if __name__ == '__main__':
    print(Student.say_msg("Hello static")) #say Hello static
    stu = Student(name="JackWang",age=33)
    print(stu.get_info()) #JackWang         
    stu.name = "smith"
    stu.work("math") #smith do math
    stu.age = 32
    Student.name = "smith02"
    print(stu.get_name()) #smith02

至此,对Python中的核心语法进行了较为详细的说明。Python对于数据处理、数据分析以及人工智能方面有一定的优势,因此对Python语法进行学习并多加练习,至关重要。【生长吧!Python】有奖征文火热进行中:https://bbs.huaweicloud.com/blogs/278897

【版权声明】本文为华为云社区用户原创内容,转载时必须标注文章的来源(华为云社区)、文章链接、文章作者等基本信息, 否则作者和本社区有权追究责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@huaweicloud.com
  • 点赞
  • 收藏
  • 关注作者

评论(0

0/1000
抱歉,系统识别当前为高风险访问,暂不支持该操作

全部回复

上滑加载中

设置昵称

在此一键设置昵称,即可参与社区互动!

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。

举报
请填写举报理由
0/200