作者 | yuquanle
Python基本语法
第一个字符必须是英文字母或下划线 _ 。标识符的其他的部分由字母、数字和下划线组成。标识符对大小写敏感。
保留字即关键字,不能用作任何标识符名称。keyword 模块可以输出当前版本的所有关键字:
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']单行注释采用#,注释是给人看的,可以是任意内容,解释器会忽略掉注释。
行与缩进
注意Tab和四格空格混用会报错,这个错误还不容易被察觉。
通常是一条语句一行,如果语句很长,我们可以使用反斜杠(\)来实现多行语句。在 , {}, 或 中的多行语句,则不需要反斜杠。
sentence1 = "I love " + \
"python"
sentence2 = ["I", "love",
"python"]
计算机程序要处理不同的数据,需要定义不同的数据类型。Python 中的变量不需要声明,每个变量在使用前都必须赋值,变量赋值以后该变量才会被创建。
数字类型(Number)
关于数值运算,可以同时为多个变量赋值,如a, b = 1, 2。一个变量可以通过赋值指向不同类型的对象。
字符串类型(String)
列表类型(List)
元组类型(Tuple)
集合类型(Set)
注意:创建一个空集合必须用 set 而不是 {},因为 {} 是用来创建一个空字典。
a={'a','b','c'}
b=set('abc')
c=set
d={}
print(a)
print(b)
print(type(a), type(b), type(c), type(d))
#无序性
a = set('python')
print(a)
#互异性
a = set('good')
print(a)
#add方法:为集合添加元素
a = set('good')
a.add('p')
print(a)
#update方法:给集合添加元素
a = set('good')
a.update('p')
print("添加一个元素", a)
a.update(['a', 'b', 'c'])
print("添加多个元素", a)
a.update(['H', 'e'], {'l', 'l', 'o'})
print('添加列表和集合', a)
#remove方法:移除指定元素
s = {'P', 'y', 't', 'h', 'o', 'n'}
s.remove('t')
print("去掉t", s)
#pop方法:随机移除元素
s = {'P', 'y', 't', 'h', 'o', 'n'}
print("随机删除元素:", s.pop)
#clear方法:移除集合中的所有元素
s = {'P', 'y', 't', 'h', 'o', 'n'}
s.clear
print("清空集合:", s, len(s))
#issubset方法:判断指定集合是否为该方法参数集合的子集
A = set('abcd')
B = set('cdef')
C = set('ab')
print("C是否A子集:", C.issubset(A))
#union方法:返回两个集合的并集,也可以用 |
print("A和B并集:", A|B)
print("A和B并集:",A.union(B))
#intersection方法:返回集合的交集,也可以用&
print("A和B交集:", A&B)
print("A和B交集:",A.intersection(B))
#difference方法:差集,也可以用-
print("A和B差集:", A-B)
print("A和B差集:",A.difference(B))字典类型是可变类型。在同一个字典中,键(key)必须是唯一的。
条件判断和循环
每个条件后面要使用冒号:,表示接下来是满足条件后要执行的语句块。使用缩进来划分语句块,相同缩进数的语句在一起组成一个语句块。在Python中没有switch–case语句。
#if操作
x = 5
if x > 3:
print("yes")
#if嵌套:if...elif...else
#也可以把 if...elif...else 结构放在另外一个 if...elif...else 结构中
x = 99
if x<60:
print("不及格")
elif x<80:
print("良好")
else:
print("优秀")
#while循环
sum = 0
counter = 1
while counter <= 10:
sum = sum + counter
counter += 1
print("1 到 10 之和为: %d" % sum)
#while 循环使用 else 语句
count = 0
while count < 5:
print (count, " 小于 5")
count = count + 1
else:
print (count, " 大于或等于 5")
#for 语句:for循环可以遍历任何序列(列表、字符串等)
str = 'python'
list1 = ['I', 'love', 'python']
print("遍历字符串")
for i in str:
print(i)
print("遍历列表")
for i in list1:
print(i)
#range函数:遍历数字序列,可以使用内置range函数生成数列
for i in range(5):
print(i)
#也可以使用range指定区间的值
for i in range(2,6):
print(i)
#也可以使range以指定数字开始并指定不同的增量(步长),可以是负数
for i in range(0, 10, 3):
print(i)
for i in range(-10, -100, -30):
print(i)
#可以结合range和len函数以遍历一个序列的索引
list1 = ['I', 'love', 'Python']
for i in range(len(list1)):
print(list1[i])
#break语句:跳出 for 和 while 的循环体
list1 = ['I', 'love', 'Python']
for i in list1:
if i == 'love':
break
print('当前为 :', i)
#continue语句:跳过当前循环块中的剩余语句,然后继续进行下一轮循环
var = 10
while var > 0:
var = var -1
# 变量为 5 时跳过输出
if var == 5:
continue
print ('当前值 :', var)
print ("hello world!")
#pass 语句:pass是空语句,是为了保持程序结构的完整性,pass 不做任何事情,一般用做占位语句
while True:
pass # 等待键盘中断 (Ctrl+C)
函数是组织好的,可重复使用的,用来实现单一,或相关联功能的代码段。函数能提高应用的模块性,和代码的重复利用率。
类
类变量:类变量在整个实例化的对象中是公用的。类变量定义在类中且在函数体之外。类变量通常不作为实例变量使用。
类的继承
通过继承创建的新类称为子类或派生类,被继承的类称为基类、父类或超类。
#编写一个名为Fruit的class,执行run方法可以直接打印
#编写Apple和Orange类时,就可以直接从Fruit类继承
class Fruit(object):
'父类Animal'
def run_father(self):
print('调用父类方法...')
class Apple(Fruit):
'子类1 Apple'
def run_son(self):
print('调用子类方法...')
class Orange(Fruit):
'子类2 Orange'
def run_son(self):
print('调用子类方法...')
#实例化子类
apple = Apple
orange = Orange
#调用父类方法
apple.run_father
orange.run_father
#调用子类方法
apple.run_son
orange.run_son如果父类方法的功能不能满足你的需求,你可以在子类重写你父类的方法
class Fruit(object):
'父类Animal'
def run(self):
print('调用父类方法...')
class Apple(Fruit):
'子类1 Apple'
def run(self):
print('子类1 Apple 重写父类方法...')
class Orange(Fruit):
'子类2 Orange'
def run(self):
print('子类2 Orange 重写父类方法...')
#实例化子类
apple = Apple
orange = Orange
#调用父类方法
apple.run
orange.runPython 模块(Module),是一个 Python 文件,以 .py 结尾,包含了 Python 对象定义和Python语句。模块让你能够有逻辑地组织你的 Python 代码段。
声明:本文为公众号「 AI小白入门」投稿,版权归作者所有。
【END】
