[TOC]
1. Variable basis and simple data type 1.1 variable interpretation
The value that the variable is stored in memory. This means that a space is created in memory when you create a variable.
name = ‘python‘number = 2017print(name);print(number);output:python2017
1.2 Variable naming rules
b variable names contain numbers, captions, underscores, but cannot start with a number, can start with a letter or an underscore
Variable names cannot contain spaces
The variable name cannot be a python keyword, nor can it be a python built-in function name
The name of the variable is best known as the name
1.3 String 1.3.1 String concatenation
name = ‘python‘;info = ‘hello world‘;#python 中字符串拼接使用(+)实现print(name+" "+info);output:python hello world
1.3.2 Common functions for string production
Title: Capitalize the first letter to display each word
Upper: string Convert all Uppercase
Lower: all strings converted to lowercase
Strip: Delete Spaces at both ends of a string
Lstript: Remove whitespace from the left side of the string
Rstrip: Delete the space at the right end of the string
STR: Non-characters are represented as strings
#使用示例name = ‘python‘;number = 2017;info = ‘Hello world‘;#python 中字符串拼接使用(+)实现newstr = name+" "+info;print(newstr);print(newstr.title());print(newstr.lower());print(newstr.upper());output:python Hello worldPython Hello Worldpython hello worldPYTHON HELLO WORLD
2. List 2.1 List explanation
A list is a collection of elements arranged in a particular order, a list can contain multiple elements, and each element can have no relationship
2.2 List Definitions
Use brackets [] in Python to represent a list of elements in the list separated by commas
The index of the element in the ① list is 0-based ② the index is specified as-1 points to the last element ③ the specified index exceeds the length of the list, error
2.3 Accessing elements in a list
citys = [‘北京‘,‘beijing‘,‘上海‘,‘深圳‘,‘广州‘,‘武汉‘,‘杭州‘,‘成都‘,‘重庆‘,‘长沙‘,‘南京‘];print(citys);print(citys[0]);print(citys[-1]);print(citys[1].upper());output:[‘北京‘, ‘beijing‘, ‘上海‘, ‘深圳‘, ‘广州‘, ‘武汉‘, ‘杭州‘, ‘成都‘, ‘重庆‘, ‘长沙‘, ‘南京‘]北京南京BEIJING
2.4 List Operations 2.4.1 modifying elements in a list
citys = [‘北京‘,‘beijing‘,‘上海‘,‘深圳‘,‘广州‘,‘武汉‘,‘杭州‘,‘成都‘,‘重庆‘,‘长沙‘,‘南京‘];print(citys);#修改列表citys中第二个元素的值citys[1] = ‘雄安新区‘;print(citys);output[‘北京‘, ‘beijing‘, ‘上海‘, ‘深圳‘, ‘广州‘, ‘武汉‘, ‘杭州‘, ‘成都‘, ‘重庆‘, ‘长沙‘, ‘南京‘][‘北京‘, ‘雄安新区‘, ‘上海‘, ‘深圳‘, ‘广州‘, ‘武汉‘, ‘杭州‘, ‘成都‘, ‘重庆‘, ‘长沙‘, ‘南京‘]
2.4.2 adding elements to a list
citys = [‘北京‘,‘beijing‘,‘上海‘,‘深圳‘,‘广州‘,‘武汉‘,‘杭州‘,‘成都‘,‘重庆‘,‘长沙‘,‘南京‘];print(citys);#在列表末尾追加新的元素citys.append(‘南昌‘);citys.append(‘厦门‘);#在列表指定的索引位置添加新的元素citys.insert(1,‘石家庄‘);print(citys);output[‘北京‘, ‘beijing‘, ‘上海‘, ‘深圳‘, ‘广州‘, ‘武汉‘, ‘杭州‘, ‘成都‘, ‘重庆‘, ‘长沙‘, ‘南京‘][‘北京‘, ‘石家庄‘, ‘beijing‘, ‘上海‘, ‘深圳‘, ‘广州‘, ‘武汉‘, ‘杭州‘, ‘成都‘, ‘重庆‘, ‘长沙‘, ‘南京‘, ‘南昌‘, ‘厦门‘]
2.4.3 deleting elements from a list
citys = [‘北京‘,‘beijing‘,‘上海‘,‘深圳‘,‘广州‘,‘武汉‘,‘杭州‘,‘成都‘,‘重庆‘,‘长沙‘,‘小岛‘,‘南京‘];print(citys);#删除指定索引的元素del citys[1];print(citys);#弹出列表末尾或者指定位置的元素,弹出的值可以被接收result_end = citys.pop();result_index = citys.pop(3);print(result_end);print(result_index);print(citys);#删除指定值的元素citys.remove(‘小岛‘);print(citys);output[‘北京‘, ‘beijing‘, ‘上海‘, ‘深圳‘, ‘广州‘, ‘武汉‘, ‘杭州‘, ‘成都‘, ‘重庆‘, ‘长沙‘, ‘小岛‘, ‘南京‘][‘北京‘, ‘上海‘, ‘深圳‘, ‘广州‘, ‘武汉‘, ‘杭州‘, ‘成都‘, ‘重庆‘, ‘长沙‘, ‘小岛‘, ‘南京‘]南京广州[‘北京‘, ‘上海‘, ‘深圳‘, ‘武汉‘, ‘杭州‘, ‘成都‘, ‘重庆‘, ‘长沙‘, ‘小岛‘][‘北京‘, ‘上海‘, ‘深圳‘, ‘武汉‘, ‘杭州‘, ‘成都‘, ‘重庆‘, ‘长沙‘]
2.4.4 Reorganization List
lists_1 = [' One ', ' five ', ' Three ', ' wo ', ' xx ', ' hhh '];lists_2 = [' One ', ' five ', ' three ', ' wo ', ' xx ', ' hhh ']; #sort () Permanent sorting by letter lists_1.sort ();p rint (' The result of the list list_1 sorted: ') print (lists_1); #sort (Reverse=true) Permanently sort by letter print (' results after inverse ordering of list list_1: ') lists_1.sort (reverse=true);p rint (lists_1); #sorted () Sort the list alphabetically by letter list2_tmp = Sorted (lists_2); list2_tmp_reverse = sorted (lists_2,reverse=true);p rint (' The result after a temporary sort of list list2_tmp: ') print (list2_tmp); Print (' list list2_tmp_reverse results after temporary inverse order: ') print (list2_tmp_reverse);p rint (' list list_2 after a temporary sort, but the original list does not change: ') print (lists_2 ); Output list list_1 results after sorting: [' Five ', ' hhh ', ' One ', ' three ', ' wo ', ' xx '] list list_1 reverse order after the result: [' xx ', ' wo ', ' three ', ' one ', ' HHH ', The results of the ' five ' list list2_tmp after a temporary sort: [' five ', ' hhh ', ' One ', ' three ', ' wo ', ' xx '] list list2_tmp_reverse The result after a temporary inverse order: [' xx ', ' wo ', ' Three ', ' one ', ' hhh ', ' five '] list list_2 after a temporary sort, but the original list does not change: [' One ', ' five ', ' Three ', ' wo ', ' xx ', ' hhh ']
lists_1 = [‘one‘,‘five‘,‘three‘,‘wo‘,‘xx‘,‘hhh‘];#对列表进行永久反转;lists_1.reverse();print(lists_1);#统计列表的长度result_len = len(lists_1);print(result_len);print(lists_1.__len__());output[‘hhh‘, ‘xx‘, ‘wo‘, ‘three‘, ‘five‘, ‘one‘]66
2.4.5 List Loop operation
citys = [‘北京‘,‘上海‘,‘深圳‘,‘广州‘,‘武汉‘,‘杭州‘,‘成都‘,‘重庆‘,‘长沙‘,‘南京‘];otherCitys = [];for city in citys: print(city+‘ is nice‘); otherCitys.append(city);otherCitys.reverse();print(otherCitys);output北京 is nice上海 is nice深圳 is nice广州 is nice武汉 is nice杭州 is nice成都 is nice重庆 is nice长沙 is nice南京 is nice[‘南京‘, ‘长沙‘, ‘重庆‘, ‘成都‘, ‘杭州‘, ‘武汉‘, ‘广州‘, ‘深圳‘, ‘上海‘, ‘北京‘]
2.4.6 creating a list of values
#创建一个数值列表list_num = list(range(1,10,2));print(list_num);sq = [];for num in list_num: result = num**2; sq.append(result);print(sq);#获取列表中的最小值print(min(sq));#获取列表中的最大值print(max(sq));#获取数值列表的总和print(sum(sq));output[1, 3, 5, 7, 9][1, 9, 25, 49, 81]181165
2.4.7 using a partial slice of a list
num = [‘zero‘,‘one‘,‘two‘,‘three‘,‘four‘,‘five‘,‘six‘,‘seven‘,‘eight‘,‘nine‘,‘ten‘];print(num);print(num[:5]);print(num[5:]);print(num[1:4]);print(num[-3:]);# 切片复制num_part = num[1:5];print(num_part);output:[‘zero‘, ‘one‘, ‘two‘, ‘three‘, ‘four‘, ‘five‘, ‘six‘, ‘seven‘, ‘eight‘, ‘nine‘, ‘ten‘][‘zero‘, ‘one‘, ‘two‘, ‘three‘, ‘four‘][‘five‘, ‘six‘, ‘seven‘, ‘eight‘, ‘nine‘, ‘ten‘][‘one‘, ‘two‘, ‘three‘][‘eight‘, ‘nine‘, ‘ten‘][‘one‘, ‘two‘, ‘three‘, ‘four‘]
2.4.8 tuples
An immutable list of element values is called a tuple
#定义一个元组 使用();coordinate = (39.9,116.3);print(coordinate[0]);print(coordinate[1]);#获取元组的长度print(len(coordinate));#遍历元组for val in coordinate: print(val);#不能修改元组中的单个元素的值,但是可以给存储元组的变量赋值coordinate = (111,222);print(coordinate);output39.9116.3239.9116.3(111, 222)
3. Dictionary 3.1 dictionary base using 3.1.1 to create a dictionary
A dictionary is a series of key-value pairs, each of which is associated with a value, which can be a number, a string, a list, a dictionary, or a Python object
# 创建一个有键值对的字典people_0 = {‘name‘:‘张三‘,‘age‘:99,‘addr‘:‘Beijing‘,‘children‘:{‘son‘:‘张源风‘,‘daughter‘:‘张慕雪‘}}# 创建一个空字典people_1 ={};
3.1.2 Accessing elements in a dictionary
people_0 = {‘name‘:‘张三‘,‘age‘:99,‘addr‘:‘Beijing‘,‘children‘:{‘son‘:‘张源风‘,‘daughter‘:‘张慕雪‘}};#访问字典中的值print(people_0[‘children‘][‘son‘]);people_1 ={};#output张源风
3.1.3 Adding a key-value pair to the dictionary
people_1 ={};#添加键值people_1[‘name‘] = ‘李四‘;people_1[‘age‘] = 80;print(people_1);# output {‘name‘: ‘李四‘, ‘age‘: 80}
3.1.4 modifying key values in a dictionary
people_1 ={};people_1[‘name‘] = ‘李四‘;people_1[‘age‘] = 80;print(people_1[‘age‘]);#将字典中的键age的值修改people_1[‘age‘] = 90;print(people_1[‘age‘]);# output 8090
3.1.5 Delete a key-value pair in a dictionary
people_1 ={};people_1[‘name‘] = ‘李四‘;people_1[‘age‘] = 80;people_1[‘addr‘] = ‘Provence‘;print(people_1);#删除一个键值对del people_1[‘age‘];print(people_1);#output{‘name‘: ‘李四‘, ‘age‘: 80, ‘addr‘: ‘Provence‘}{‘name‘: ‘李四‘, ‘addr‘: ‘Provence‘}
3.2 Traversing the dictionary 3.2.1 all the key-value pairs in the dictionary
Favorite_programming_language = { ‘乔丹‘:‘java‘, ‘约翰逊‘:‘C‘, ‘拉塞尔‘:‘C++‘, ‘邓肯‘:‘python‘, ‘奥尼尔‘:‘C#‘, ‘张伯伦‘: ‘JavaScript‘, ‘科比‘: ‘php‘, ‘加内特‘:‘Go‘,};for name,language in Favorite_programming_language.items(): print(name.title() + "‘s favorite program lnaguage is " + language.title() + ‘.‘);# output乔丹‘s favorite program lnaguage is Java.约翰逊‘s favorite program lnaguage is C.拉塞尔‘s favorite program lnaguage is C++.邓肯‘s favorite program lnaguage is Python.奥尼尔‘s favorite program lnaguage is C#.张伯伦‘s favorite program lnaguage is Javascript.科比‘s favorite program lnaguage is Php.加内特‘s favorite program lnaguage is Go.
3.2.2 traversing a key in a dictionary
Favorite_programming_language = { ‘乔丹‘:‘java‘, ‘约翰逊‘:‘C‘, ‘拉塞尔‘:‘C++‘, ‘邓肯‘:‘python‘, ‘奥尼尔‘:‘C#‘, ‘张伯伦‘: ‘JavaScript‘, ‘科比‘: ‘php‘, ‘加内特‘:‘Go‘,};names = [‘乔丹‘,‘加内特‘];for name in Favorite_programming_language.keys(): print(name.title()); if name in names : print(‘I can see‘ + name.title() +‘ like ‘+ Favorite_programming_language[name].title());#output 乔丹I can see乔丹 like Java约翰逊拉塞尔邓肯奥尼尔张伯伦科比加内特I can see加内特 like Go
3.2.3 traversing a value in a dictionary
Favorite_programming_language = { ‘乔丹‘:‘java‘, ‘约翰逊‘:‘C‘, ‘拉塞尔‘:‘C++‘, ‘邓肯‘:‘python‘, ‘奥尼尔‘:‘C#‘, ‘张伯伦‘: ‘JavaScript‘, ‘科比‘: ‘php‘, ‘加内特‘:‘Go‘,};print(‘this is languages:‘);for language in Favorite_programming_language.values(): print(language.title());# outputthis is languages:JavaCC++PythonC#JavascriptPhpGo
Favorite_programming_language = { ‘乔丹‘:‘java‘, ‘约翰逊‘:‘C‘, ‘拉塞尔‘:‘C++‘, ‘邓肯‘:‘python‘, ‘奥尼尔‘:‘C#‘, ‘张伯伦‘: ‘JavaScript‘, ‘科比‘: ‘php‘, ‘加内特‘:‘Go‘,};print(‘this is languages:‘);#调用sorted函数对值列表排序for language in sorted(Favorite_programming_language.values()): print(language.title());# outputthis is languages:CC#C++GoJavascriptJavaPhpPython
3.3 Dictionary list nested 3.3.1 Nested dictionaries in list
#字典列表嵌套people_1 = {‘name‘:‘张三‘,‘addr‘:‘英国‘};people_2 = {‘name‘:‘李四‘,‘addr‘:‘美国‘};people_3 = {‘name‘:‘王五‘,‘addr‘:‘法国‘};peoples = [people_1,people_2,people_3];for people in peoples : print(people);print(‘=======================‘);botanys = [];for number in range(30): new_botany = {‘colour‘:‘green‘,‘age‘:‘1‘}; botanys.append(new_botany);for botany in botanys[:2]: if botany[‘colour‘] == ‘green‘: botany[‘colour‘] = ‘red‘; botany[‘age‘] = ‘3‘; print(botany);print(‘.....‘);for pl in botanys[0:5]: print(pl);print(‘how much ‘ + str(len(botanys)));#output : {‘name‘: ‘张三‘, ‘addr‘: ‘英国‘}{‘name‘: ‘李四‘, ‘addr‘: ‘美国‘}{‘name‘: ‘王五‘, ‘addr‘: ‘法国‘}======================={‘colour‘: ‘red‘, ‘age‘: ‘3‘}{‘colour‘: ‘red‘, ‘age‘: ‘3‘}.....{‘colour‘: ‘red‘, ‘age‘: ‘3‘}{‘colour‘: ‘red‘, ‘age‘: ‘3‘}{‘colour‘: ‘green‘, ‘age‘: ‘1‘}{‘colour‘: ‘green‘, ‘age‘: ‘1‘}{‘colour‘: ‘green‘, ‘age‘: ‘1‘}how much 30
3.3.2 A nested list in a dictionary
#定义一个字典&包含列表use_language = { ‘name_a‘:[‘java‘,‘php‘], ‘name_b‘:[‘python‘,‘C++‘], ‘name_c‘:[‘Go‘], ‘name_d‘:[‘.net‘], ‘name_e‘:[‘C#‘,‘JavaScript‘],};#循环字典for name,languages in use_language.items(): print("\n" + name.title() + ‘ use this language:‘); #循环列表 for language in languages : print("\t"+language.title());#output : Name_A use this language: Java PhpName_B use this language: Python C++Name_C use this language: GoName_D use this language: .NetName_E use this language: C# Javascript
3.3. Nested dictionaries in 3 words
#字典中嵌套字典person_from ={ ‘战三‘:{‘province‘:‘hubei‘,‘city‘:‘wuhan‘,‘dis‘:1000}, ‘李思‘:{‘province‘:‘jiangsu‘,‘city‘:‘nanjing‘,‘dis‘:1500}, ‘宛舞‘:{‘province‘:‘guangzhou‘,‘city‘:‘shengzhen‘,‘dis‘:2000},};for name,use_info in person_from.items() : print("\n username " + name); form_info = use_info[‘province‘] + ‘_‘ + use_info[‘city‘] ; print("\t from " +form_info);#output : username 战三 from hubei_wuhan username 李思 from jiangsu_nanjing username 宛舞 from guangzhou_shengzhen
4. Process Control 4.1 Simple if statement
score = 60;if score >= 60 : print(‘You passed the exam‘);#output :You passed the exam
4.2 If-else Statements
score = 50;if score >= 60 : print(‘You passed the exam‘);else: print(‘You failed in your grade‘);#output : You failed in your grade
citys = [‘北京‘,‘天津‘,‘上海‘,‘重庆‘];city = ‘深圳‘;if city in citys : print(‘welcome‘);else: print(‘not found‘);#output : not found
4.3 if-elif-else statements
score = 88;if score < 60 : print(‘You failed in your grade‘);elif score >=60 and score <= 80 : print(‘You passed the exam‘);elif score >=80 and score <=90 : print(‘Your grades are good‘);else: print(‘YOU are very good‘);# output : Your grades are good
english = 90;Chinese = 80;if english >= 80 or Chinese >=80 : print("You‘re terrific");else : print(‘You need to work hard‘);#output:Your grades are good
colour_list = [‘red‘,‘green‘,‘blue‘,‘violet‘,‘white‘];my_colour = [‘red‘,‘black‘];for monochromatic in colour_list: if monochromatic in my_colour: print(‘the colour :‘+ monochromatic + ‘ is my like‘); else: print("\n the colour :"+monochromatic + ‘ is not‘);#output :the colour :red is my likethe colour :green is notthe colour :blue is notthe colour :violet is notthe colour :white is not
5.while Loop 5.1 simple while loop
num = 1;while num <=6: print(num); num +=1;#output : 123456
5.2 Exiting while loop with identity
The input () function pauses the program, waits for the user to enter some text, stores it in a variable after the user enters the text, and makes it easy to use later
#等待用户输入文本内容,并且将内容值存储到变量name中name = input(‘please input you name : ‘);print(‘nice to meet you ‘+name);#output:please input you name : zhifnanice to meet you zhifna
flag = True;while flag :messge = input(‘please input :‘);if messge == ‘quit‘:flag = False;else:print(messge);# output :please input :oneoneplease input :twotwoplease input :quit
Process finished with exit code 0
#### 5.3 使用break 退出循环```pythoninfo = "\n please enter the name of city you have visited :";info += "\n(Enter ‘quit‘ when you want to ove)";while True: city = input(info); if city == ‘quit‘: break; else: print(‘I like the city :‘+ city.title());#output :please enter the name of city you have visited :(Enter ‘quit‘ when you want to ove)北京I like the city :北京 please enter the name of city you have visited :(Enter ‘quit‘ when you want to ove)上海I like the city :上海 please enter the name of city you have visited :(Enter ‘quit‘ when you want to ove)quitProcess finished with exit code 0
5.4 Using while working with lists and dictionaries
unauthenticated_user = [' name_a ', ' name_b ', ' name_c ', ' name_e '];allow_user = []; While unauthenticated_user:temp_user = Unauthenticated_user.pop (); Print ("Verifying user" + Temp_user.title ()); Allow_user.append (Temp_user);p rint ("\nshow all allow User:"), for user_name in Allow_user:print (User_name.title ()); #o utput:verifying User name_everifying user name_cverifying user name_bverifying user name_ashow all Allow User:name_enam E_cname_bname_a
user_infos = {};flag = True ;while flag : name = input(‘please enter you name :‘); sport = input("What‘s your favorite sport :"); user_infos[name] = sport; repeat = input(‘Do you want to continue the question and answer (y/n): ‘); if repeat == ‘n‘ : flag = False ;print("\n-------ALL----");for name,sport in user_infos.items(): print(name.title() + ‘ like ‘+sport.title());#output :please enter you name :李思What‘s your favorite sport :舞蹈Do you want to continue the question and answer (y/n): yplease enter you name :王武What‘s your favorite sport :足球Do you want to continue the question and answer (y/n): n-------ALL----李思 like 舞蹈王武 like 足球
Python basic syntax