Basic grammers in Python

Introduction to data structures, types of variables, condition control, loop structrue etc.

Posted by Yingshan Li on July 8, 2020

Preface

Hello everyone! My name is Yingshan Li. This is a basic tutorial for greeners to start Python programming. Python is one of the most elegant and simple programming languages with incredibly simple grammar. It is sometimes as easy to read Python code as plain English, which is ideal for absolute beginners. There are numerous powerful and convenient machine learning and big data analysis packages in Python, so it may also be helpful for people who are interested in big data and AI to learn Python.

To master a language, whether it is a human language or programming language, the most important thing is to learn the rules specific to this language, generally regarded as grammars. Python is not an exception. Here in this article, I would familiarize you with the most essential rules in Python, including data structures, variable types, condition types, and loop structures, etc. Once you have a good understanding of these rules, I would continue to discuss the more advanced content in the next article.

Without further ago, let’s get started!

Quick Start

Python的安装我就不用介绍了,对应自己电脑的类型到官网下载安装就好了,非常简单。安装好了之后你可以在命令行中键入命令python进入交互模式,也可以使用一款你喜欢的文本编辑器来编写python脚本,然后在命令行中执行。几乎对于所有的编程语言来说,第一个程序都是打印”hello, world!”。试用一下代码就可以打印出“hello, world!”。

greeting = input()	#从键盘中输入“hello, world!”,记住input()函数输出的都是字符串
print(greeting)

记住在python3中print后面一定要打括号。你也可以将你的脚本保存为“hello.py”,然后在命令行中执行

$ python3 hello.py

这样就可以输出:

hello, world!

Data types

Python的语法相对比其它编程语言简单的地方之一就是它不用申明变量类型。直接用“=”给一个变量赋值后这个变量就被创建了。Python中常见的数据类型有以下几种:

Number

python可以支持整数int(只有长整型), 浮点型float, 布尔型bool以及复数型complex。内置的type()函数可以用来判断变量的类型,记住type()函数的返回值需要用print()打印出来。

(a, b, c, d) = (10, 5.5, False, 2+5j)
print(type(a))

String

Python中的字符串表示用单引号’ ‘或者双引号” “括起来的任意字符,比如‘hello, world’, 或者“hello, world”,但如果引号里面又有引号的话,就需要用反斜线\来转义。

str = "python"
str.replace('p', 'P')

切片:Python中字符串可以很方便的截取其中一部分,字符串的第一个字符索引值为0,第二个为1,后面一次累加,最后一个字符串索引为-1。截取的语法为:变量[第一个索引值:第二个索引值]

str1 = str[0]
str2 = str[2:4]

连接和复制:两个字符串可以用(+)连接成一个字符串,用星号*可以复制字符串

str3 = str1 + str2
str4 = str1 * 3

多行输出:可以用’'’…’'’的格式来输出多行字符串

print('''line1
line2
line3''')

判断是否存在:in或者not in

if "n" not in str:
	...

格式化输出:和C语言中的printf用法相同

print("My name is %s and I'm %d years old" % ("Mike", 16))
print("Pi is %f" % (3.1415926)) # %f默认保留小数点后6位有效数字
print("Pi is %.2f" % (3.1415926))

Data structure

列表 (List)

列表应该可以说是Python中最重要最常用的一种数据类型了,python中的列表很像Perl中的数组(array)结构。列表用方括号[]括起来,用逗号隔开,列表中的每一个元素都从0开始索引,-1为最后一个元素的索引,同样也可以进行连接(+)和复制(*)操作。

list = [10, "python", 8.2]
list1 = list[0:2]
list2 = list[1:]
list3 = list*2
"python" in list

List的常用内置函数

  1. len():获得list的长度
  2. max()、min():列表元素最大值和最小值(只支持相同类型元素)
  3. append():往list的末尾添加元素
  4. extend():往列表末尾添加多个值
  5. insert(i, NewItem):插入任意元素
  6. pop():删除末尾的元素
  7. pop(i):删除索引是i的元素
  8. count(obj):统计某个元素在列表中出现的次数
  9. reverse():反向列表
  10. sort():列表排序
  11. clear():清空列表
  12. list(tuple):将元组转化为列表

Tuple

元组和列表非常像,唯一不同的是元组中的元素不能修改,用小括号()括起来,用逗号分开,当元组中只有一个元素时,也要加上逗号。

tuple1 = (8, "tuple", 6.6")
tuple2 = ("hello",)
tuple3 = tuple1[2]
tuple4 = (8, "tuple",[3, 10], 6.6")
tuple4[2][1] = 6  #tuple4中的一个列表中的元素是可以更改的

Dictionary

Python中的字典就是Perl中的哈希(Hash),或者很多其它语言中的映射Map,字典和列表的区别是字典中的元素是无序的,用大括号{}来标识,并且是通过健(key)和值(Vavule)来存储的,健必须是唯一的。

dic1 = {}
dic1["hello"] = "world"
"hello" in dic1	#判断字典中是否存在某个key
dic2 = {"Yingshan" : "Li", "site" : "www.yingshanli.com"}

字典的常用内置函数

  1. dic.keys()
  2. dic.values()
  3. dic.pop(“site”) #删除一个key
  4. del dic[“site”] #删除一个key
  5. dic.clear()
  6. key in dic
  7. dic.items()

Set

集合用来存放一组无序且不可重复的元素,用大括号{}或者set()函数创建,如果要创建一个空集合就需要用set(),而不是{},因为{}是用来创建空字典的。set()函数只能接纳一个list作为参数

num1 = {1, 5, 3, 8}
5 in num	#判断5是否在集合中
num2 = set([10, 8, 5, 8])	#num2中只有10、8、5三个元素
num2.add(9) #添加元素
num2.remove(8)	#删除元素
num1 & num2	#并集运算
num1 | num2	#交集运算

Condition

条件判断很简答,这里就不赘述了

num = 10
if num > 0:
	print "positive number!"
elif num < 0:
	print "negative number!"
else:
	print "0!"

Loop

Python主要有两种循环,for…in循环和while循环。for…in循环可以遍历一个列表、元组或者字符串等等

range()函数

range(n)输出0到n-1的整数列表

range(m,n)输出m到n-1的整数列表

range(m,n,i)生成从m开始到n-1以i为增量的等差数列

range(len())结合可以遍历一个大小未知的列表

for…in循环

names = ["John", "Mike", "Bob"]
for name in names:
	print(name)
sum = 0
for i in range(101):
	sum = sum + i

while循环

n = 10
sum = 0
while n > 0:
	n = n-1
	sum = sum + n

break和continue

break可以跳出整个循环体,而continue只是跳出当前循环,进入下一个循环

Iterator and generator

列表生成式

列表生成式就是生成一个特定列表的表达式,基本语法:[exp for iter_var in iterable],例如:

list1 = [2*a for a in range(10)]

还可以加入一层循环:

list2 = [a*b for a in range(3) for b in range(4)]

还可以加入判断语句:

list3 = [2*a for a in range(10) if a%2 == 1]

这样写比用循环语句来写要简单很多。注意不要忘记把式子用中括号括起来,因为你要生成的是列表。

生成器

用列表生成式生成的列表会把列表中所有的数据全部放入内存中,当列表非常大时,会消耗很多的内存,并且列表的大小是有限的,因此有些时候我们不必把一个完整的列表一下子生成放在内存中,我们可以只保存一个算法,当需要的时候可以一个一个的推出后续的元素,这种方法就叫做生成器(generator),构造生成器主要有两种方式:

1.像列表生成式一样,只要中括号[]改为小括号():

generator1 = (2*a for a in range(10))

2.当程序比较复杂难以用列表生成式的方式产生生成器时,使用yield函数:

def cube(num1, num2):
	for i in range(num1, num2):
		yield i^3

当函数看到yield关键字时,这个函数就不再是一个普通函数了,而成了一个生成器generator,每一次调用next()函数时就执行一次,遇到yield就返回不再继续执行,程序会记住当前的位置,直到下一次继续调用next()再执行下一次,一直到不能再返回值了就报出StopIteration错误。

除了可以用next()函数调用生成器中的元素,更普遍的用法是用for循环来遍历生成器中的元素:

g = cube(3, 8)
for n in g:
	print(n)

迭代器

我们现在已经知道在Python中,可以用for循环迭代的对象包括:

  1. string, list, tuple, dictionary, set
  2. 生成器generator Python中可以用for循环迭代的对象统称为”可迭代对象Iterable“。我们可以使用isinstance()函数来判断对象的类型:
from collections import Iterable
print(isinstance(g, Iterable))

与之相应的,Python中定义可以next()函数调用,并不断返回下一个值的对象称之为迭代器Iterator,我们知道generator既可以被使用for循环,也可以使用next()函数,所以generator既是Iterable也是Iterator。但是string, list, tuple, dictionary, set等等不能使用next()函数,因此只是Iterable,但是可以使用iter()函数将Iterable变成Iterator。

isinstance([], Iterable)
isinstance(iter([]), Iterable)

以上差不多就是Python3最核心最基本的语法了,后面我会接着更新Python高级一点的知识,函数与模块,祝大家学习愉快!