Home>Article>Backend Development> Super detailed compilation and sharing of the basics of getting started with Python

Super detailed compilation and sharing of the basics of getting started with Python

WBOY
WBOY forward
2022-11-15 17:56:54 2507browse

This article brings you relevant knowledge aboutPython, which mainly organizes relevant content related to the basics of getting started with Python, including identifiers, variables, conditional statements, etc. Let’s take a look. Take a look, hope it helps everyone.

Super detailed compilation and sharing of the basics of getting started with Python

【Related recommendations:Python3 video tutorial

Identifiers

In Python, all identifiers can includeEnglish (case-sensitive), numbers, and underscores (_), but cannot begin with Start with numbers.

Begins with asingle underscorerepresents _foocannot directly access the class attributes of. It needs to be accessed through the interface provided by the class. It cannot be imported using from xxx import * .

__foo starting withdouble underscorerepresents theprivate memberof the class,

starting withdouble underscore and ending with__foo__ represents the special identifier for special methods in Python, such as __init__(), which represents the constructor of a class.

StatementsPython code blocks must use the same number of

number of indented spaces at the beginning of the line

in python

Single-line comments

Start with #.Multi-line comments in python

Use three single quotes (''') or three double quotes (""").

# Python语句中一般以新行作为语句的结束符。但是我们可以使用【斜杠( \)】将一行的语句分为多行显示, # 语句中包含 [], {} 或 () 括号就不需要使用多行连接符。 # Python可以在同一行中使用多条语句,语句之间使用【分号(;)】分割 total = item_one + \ item_two + \ item_three days = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday'] # Python可以在同一行中使用多条语句,语句之间使用【分号(;)】分割。 import sys; x = 'runoob'; sys.stdout.write(x + '\n') # Python 可以使用【引号( ' )、双引号( " )、三引号( ''' 或 """ ) 】来表示字符串 word = 'word' sentence = "这是一个句子。" paragraph = """这是一个段落。 包含了多个语句""" # print 默认输出是换行的,如果要实现【不换行需要在变量末尾加上逗号】 。 print x,y
Variables

There are six standard data types in Python3:

Number (number)
  • String (string )
  • List (list)
  • Tuple (tuple)
  • Set (set)
  • Dictionary
  • Among the six standard data types of Python3:
Immutable data (3) : Number (number), String (string), Tuple (tuple);

Variable data (3): List (list), Dictionary (dictionary), Set (set).

Number (number)

int, float, bool, complex (plural number)

In internal functions,

strings, tuples, and numbers

is an unchangeable object, and global variables must be init variables or defined with self in the function;

list, dict, etc. are objects that can be modified, and internal functions can directly use local variables in the function.

counter = 100 # 赋值整型变量 miles = 1000.0 # 浮点型 name = "John" # 字符串 二进制转换: int('10',2) > 2 bin(10) > '0b1010' bin(10)[2:] ord(c) # c为字符 # 返回值:对应的十进制整数(ASCll数值) int(c) # c为字符,转化为对应的数字 float('-inf') # 最小值 -inf a = b = c = 1 a, b, c = 1, 2, "john" all() # 函数用于判断给定的可迭代参数 iterable 中的所有元素是否都为 TRUE,如果是返回 True,否则返回 False。 # 从左到右索引默认【0开始的】,最大范围是字符串【长度少1】 # 从右到左索引默认【-1开始的】,最大范围是【字符串开头】 # 第三个参数,参数作用是【截取的步长】 s = "a1a2···an" # n>=0 向上取整:math.ceil() 向下取整:math.floor()、整除"//" 四舍五入:round()——奇数向远离0取整,偶数去尾取整;或言之:奇数进位,偶数去尾 向0取整:int()
List(List)

tinylist = [123, 'john'] print list[0] # 输出列表的第一个元素 print list[1:3] # 输出第二个至第三个元素 print list[2:] # 输出从第三个开始至列表末尾的所有元素 # 二维数组 num_list = [ [0] * 5 for i in range(2)] dp = [[1]*n] + [[1]+[0] * (n-1) for _ in range(m-1)] clone_node.neighbors = [self.cloneGraph(n) for n in node.neighbors] # 加号 + 是列表连接运算符,星号 * 是重复操作 print tinylist * 2 # 输出列表两次 print list + tinylist # 打印组合的列表 list.append('Google') # 使用 append() 添加元素 del list[2] # 可以使用 del 语句来删除列表的元素 list.pop(3) # 指定pop参数,将会删除该位置的元素;无参数时默认删除最后一个元素 list.append(sublist) # 引用传递 list.append([]+sublist) # 值传递 list.append(list(path)) len([1, 2, 3]) 3 #长度 [1, 2, 3] + [4, 5, 6] [1, 2, 3, 4, 5, 6] #组合 ['Hi!'] * 4 ['Hi!', 'Hi!', 'Hi!', 'Hi!'] #重复 3 in [1, 2, 3] True #元素是否存在于列表中 for x in [1, 2, 3]: print x, 1 2 3 #迭代 [::-1] # 数组反转 max(list) # 求list的最大值 sum(sp[i] for i in range(n)) #求和 sum(s in jewelsSet for s in stones) nums.sort() # 排序 score.sort(reverse=True) list有一个sort方法,list.sort()将list进行排序,返回None sort(*,key = None,reverse = False) key是一个函数,这个函数的作用是从list的每个元素中提取用于当作排序依据的属性 默认是从小到大,即reserve为False的时候,如果reserve为True,排列顺序就是从大到小 def f(item): return item[1] list.sort(key = f) list.sort(key = lambda item:item[0]) sorted(iterable,*,key=None,reverse=False) # 默认正序排列 sorted(dict.items(),key=lambda item:item[0]) res = sorted(hash,key = lambda word:(-hash[word],word)) # 第一个参数 -hash[word] 即单词出现次数的相反数 # 当词频相同时,用第二个参数 word 进行排序,即字母正序排列 列表解析 List Comprehensions 表达式:[expression for iter_val in iterable if cond_expr] [expression]:最后执行的结果 [for iter_val in iterable]:这个可以是一个多层循环 [if cond_expr]:两个for间是不能有判断语句的,判断语句只能在最后;顺序不定,默认是左到右。 print[(x,y)for x in [1,2]for y in [3,4]] for (k1, v1), (k2, v2) in zip(dict_one, dict_two): # 遍历两个list或者dict for item in product([1,2],[10,20]): # 对矩阵做笛卡尔积 print(item) for i, j in product(range(m), range(n)): neighbors = [(1,0), (1,-1), (0,-1), (-1,-1), (-1,0), (-1,1), (0,1), (1,1)] for neighbor in neighbors: r = (row + neighbor[0]) c = (col + neighbor[1]) for u,v in neighbors: s = [1, 2, 3, 4, 5] # 从指定索引1开始 for index, value in enumerate(s, 1): list(str(n)) # int转化为字符串,转化为list next(word for word,f in freq.items() if f==maxFreq) # next()取list第一个值 map(max, grid) # 求每行的最大值 map(max, zip(*grid)) # 求每列的最大值 strs = map(str,nums) # 转换为list(str) r1,m1 = map(int, num1[:-1].split('+')) # list(str)转化为list(int) list(map(list,numSet)) >>> a = [1,2,3] >>> b = [4,5,6] >>> c = [4,5,6,7,8] >>> zipped = zip(a,b) # 返回一个对象 >>> zipped  >>> list(zipped) # list() 转换为列表 [(1, 4), (2, 5), (3, 6)] >>> list(zip(a,c)) # 元素个数与最短的列表一致 [(1, 4), (2, 5), (3, 6)] >>> a1, a2 = zip(*zip(a,b)) # 与 zip 相反,zip(*) 可理解为解压,返回二维矩阵式 >>> list(a1) [1, 2, 3] >>> list(a2) [4, 5, 6]

tuple(Tuple)

# 元组用 () 标识。内部元素用逗号隔开。但是元组不能二次赋值,相当于只读列表。 tinytuple = (123, 'john')

Dict( Dictionary)

# 字典用"{ }"标识。字典由索引(key)和它对应的值value组成。 dict = {} dict['one'] = "This is one" dict[2] = "This is two" # 值可以取任何数据类型,但键必须是不可变的,如字符串,数字或 元组 。 用列表就不行 dict[tuple(count)] # 以列表返回字典中的所有值 dict.values() list(dict.values()) for key in dict: print (key) tinydict = {'name': 'runoob','code':6734, 'dept': 'sales'} print dict['one'] # 输出键为'one' 的值 print dict[2] # 输出键为 2 的值 print tinydict # 输出完整的字典 print tinydict.keys() # 输出所有键 print tinydict.values() # 输出所有值 maxFreq = max(freq.values()) # 求value的最大值 tinydict['Age'] = 8 # 更新 tinydict['School'] = "RUNOOB" # 添加 del tinydict['Name'] # 删除键是'Name'的条目 tinydict.clear() # 清空字典所有条目 del tinydict # 删除字典 defaultdict(list) defaultdict(int) # defaultdict类的初始化函数接受一个类型作为参数,当所访问的键不存在的时候,可以实例化一个值作为默认值: count.get(c, 0) # 默认值为0 items():返回所有(key,value)元组的数组,类似于‘列表’ [s for s, c in cnt.items() if c == maxCnt] # 遍历dict dict排序 sorted(dict.items(),key=lambda item:item[0]) items = [(-val, key) for key, val in count.items()] # 变更为tuple for val, key in sorted(items): # 遍历排序后的tuple

set(set)

parame = {value01,value02,...} 或者 set(value) s.add( x ) s.update( x ) # 参数可以是列表,元组,字典等 s.remove( x ) s.discard( x ) len(s) s.clear() x in s for key in set: print (key)

Operator

/

Division - x Divide by y

%Modulo - Returns the remainder of the division
**Power - Returns x raised to the yth power
//Divide by integers - returns the integer part of the quotient (rounded down)
and

x and y Boolean AND - if x is False, x and y returns False, otherwise it returns y The calculated value of x.

orx or y Boolean "or" - if x is non-zero, it returns the calculated value of x, otherwise it returns the calculated value of y.
notnot x Boolean "not" - If x is True, returns False.
is

is is used to determine whether two identifiers refer to an object.

is notis not is used to determine whether two identifiers refer to different objects.
is is different from ==.:
is is used to determine whether the objects referenced by two variables are the same ( same memory space), == is used to determine whether the values of reference variables are equal.

Conditional statement

if num == 3: # 判断num的值 print 'boss' elif num == 2: print 'user'elif num == 1: print 'worker'elif num < 0: # 值小于零时输出 print 'error'else: print 'roadman' # 条件均不成立时输出

Loop statement

i = 1 while i < 10: i += 1 if i%2 > 0: # 非双数时跳过输出 continue print i # 输出双数2、4、6、8、10 i = 1 while 1: # 循环条件为1必定成立 print i # 输出1~10 i += 1 if i > 10: # 当i大于10时跳出循环 break flag = 1 while (flag): print 'Given flag is really true!' fruits = ['banana', 'apple', 'mango'] for fruit in fruits: # 第二个实例 print ('当前水果: %s'% fruit) fruits = ['banana', 'apple', 'mango'] for index in range(len(fruits)): print ('当前水果 : %s' % fruits[index]) for i in reversed(range(length - 1)): # 逆序 for letter in 'Python': # 第一个实例 if letter == 'h': break print '当前字母 :', letter for i, ch in enumerate(s): if frequency[ch] == 1: return i diff = [(a,b) for a,b in zip(s,goal) if a!=b]
String

+ 字符串连接 >>>a + b 'HelloPython' * 重复输出字符串 >>>a * 2 'HelloHello' [] 通过索引获取字符串中字符 >>>a[1] 'e' [ : ] 截取字符串中的一部分 >>>a[1:4] 'ell' in 成员运算符 - 如果字符串中包含给定的字符返回 True >>>"H" in a True not in 成员运算符 - 如果字符串中不包含给定的字符返回 True >>>"M" not in a True r/R 原始字符串 - 原始字符串:所有的字符串都是直接按照字面的意思来使用,没有转义特殊或不能打印的字符。 原始字符串除在字符串的第一个引号前加上字母"r"(可以大小写)以外,与普通字符串有着几乎完全相同的语法。 >>>print r'\n' \n >>> print R'\n' \n strs = 'abcd' for ch in strs: print(ch) strs = 'abcd' for index in range(len(strs)): print(strs[index], end=' ') res += 'a'*3 # 'aaa' s.split(" ") # 将字符串分割成单词列表 " ".join(list) # 将单词列表转换为字符串,以空格分隔 f'{bulls}A{cows}B' # {}计算格式化 a = list(str(n)) # int转成list a[i-1] = str(int(a[i-1]) - 1) # 操作字符 int("".join(a)) # list转化为int isdigit # 函数判断是否数字 isalpha # 判断是否字母

String formatting

print "My name is %s and weight is %d kg!" % ('Zara', 21) %s 格式化字符串 %d 格式化整数 %f 格式化浮点数字,可指定小数点后的精度

Triple quotes

允许一个字符串跨多行,字符串中可以包含换行符、制表符以及其他特殊字符 >>> hi = '''hi there''' >>> hi # repr() 'hi\nthere' >>> print hi # str() hi there

Function

string.count(str, beg=0, end=len(string)) # 返回 str 在 string 里面出现的次数,如果 beg 或者 end 指定则返回指定范围内 str 出现的次数 string.endswith(obj, beg=0, end=len(string)) # 检查字符串是否以 obj 结束,如果beg 或者 end 指定则检查指定的范围内是否以 obj 结束,如果是,返回 True,否则返回 False. string.find(str, beg=0, end=len(string)) # 检测 str 是否包含在 string 中,如果 beg 和 end 指定范围,则检查是否包含在指定范围内,如果是返回开始的索引值,否则返回-1 string.format() # 格式化字符串 string.index(str, beg=0, end=len(string)) # 跟find()方法一样,只不过如果str不在 string中会报一个异常. string.join(seq) # 以 string 作为分隔符,将 seq 中所有的元素(的字符串表示)合并为一个新的字符串 string.replace(str1, str2, num=string.count(str1)) # 把 string 中的 str1 替换成 str2,如果 num 指定,则替换不超过 num 次. string.split(str="", num=string.count(str)) # 以 str 为分隔符切片 string,如果 num 有指定值,则仅分隔 num+1 个子字符串

Function

In python,strings, tuples, and numbers

are unchangeable objects, while

list, dict, etc. are objects that can be modified.Immutable type: After assigning a=5 to the variable, assign a=10. Here, a new int value object 10 is actually generated, and then a is pointed to it, and 5 is discarded. It does not change the value of a. It is equivalent to newly generating a.Variable type: variable assignment la=[1,2,3,4] and then assignment la[2]=5 changes the value of the third element of list la. la itself is not moved, only its internal Some of the values have been modified.

In Python,
immutable objects such as numbers, characters or tuples

types belong to

value transfer, while dicts or lists, etc.are mutable Object typebelongs topass-by-reference.If you want to modify the new assignment and the original object remains unchanged, you need to use python's copy module, that is, object copy.copy.copy is a shallow copy and copies the first-level list, while copy.deepcopy is a deep copy and deep copies all sub-elements of the list.

#可写函数说明 def printinfo( name, age = 35 ): "打印任何传入的字符串" print "Name: ", name print "Age ", age return #调用printinfo函数 printinfo( age=50, name="miki" ) printinfo( name="miki" ) # 可写函数说明 def printinfo( arg1, *vartuple ): "打印任何传入的参数" print "输出: " print arg1 for var in vartuple: print var return # 调用printinfo 函数 printinfo( 10 ) printinfo( 70, 60, 50 ) import copy l1 = [[1, 2], 3] l2 = copy.copy(l1) l3 = copy.deepcopy(l1) l2.append(4) l2[0].append(5) l3[0].append(6) l1 = [[1, 2, 5], 3] l2 = [[1, 2, 5], 3, 4] l3 = [[1, 2, 6], 3]


Anonymous function

# 可写函数说明 sum = lambda arg1, arg2: arg1 + arg2 # 调用sum函数 print "相加后的值为 : ", sum( 10, 20 ) print "相加后的值为 : ", sum( 20, 20 )

Module

import support from fib import fibonacci from math import *
Search path

1. Current Directory2. If it is not in the current directory, Python searches every directory under the shell variable PYTHONPATH.3. If neither is found, Python will check the default path. Under UNIX, the default path is generally /usr/local/lib/python/.
The module search path is stored in the sys.path variable of the system module. The variables contain the current directory, PYTHONPATH and the default directory determined by the installation process.

Python中的包
包是一个分层次的文件目录结构,它定义了一个由模块及子包,和子包下的子包等组成的 Python 的应用环境。

简单来说,包就是文件夹,但该文件夹下必须存在 __init__.py 文件, 该文件的内容可以为空。 __init__.py 用于标识当前文件夹是一个包。

考虑一个在 package_runoob 目录下的 runoob1.py、runoob2.py、 __init__.py 文件,test.py 为测试调用包的代码,目录结构如下:
test.py
package_runoob
|-- __init__.py
|-- runoob1.py
|-- runoob2.py

# 导入 Phone 包from package_runoob.runoob1 import runoob1from package_runoob.runoob2 import runoob2 runoob1()runoob2()

文件

str = input("请输入:") print "你输入的内容是: ", str fo = open("foo.txt", "w") print "文件名: ", fo.name print "是否已关闭 : ", fo.closed print "访问模式 : ", fo.mode print "末尾是否强制加空格 : ", fo.softspace # 打开一个文件 fo = open("foo.txt", "w") str = fo.read(10) fo.write( "www.runoob.com!\nVery good site!\n") # 关闭打开的文件 fo.close()

文件和文件夹

import os os.rename( "test1.txt", "test2.txt" ) os.remove("test2.txt") os.mkdir("test") # 将当前目录改为"/home/newdir" os.chdir("/home/newdir") # 给出当前的目录 print os.getcwd() # 删除”/tmp/test”目录 os.rmdir( "/tmp/test" )

异常

try: 正常的操作 ...................... except: 发生异常,执行这块代码 ...................... else: 如果没有异常执行这块代码 try: fh = open("testfile", "w") fh.write("这是一个测试文件,用于测试异常!!") except IOError: print "Error: 没有找到文件或读取文件失败" else: print "内容写入文件成功" fh.close() try-finally 语句无论是否发生异常都将执行最后的代码。 try: <语句> finally: <语句> #退出try时总会执行 raise try: fh = open("testfile", "w") try: fh.write("这是一个测试文件,用于测试异常!!") finally: print "关闭文件" fh.close() except IOError: print "Error: 没有找到文件或读取文件失败"

面向对象

class Employee: '所有员工的基类' empCount = 0 def __init__(self, name, salary): self.name = name self.salary = salary Employee.empCount += 1 def displayCount(self): print "Total Employee %d" % Employee.empCount def displayEmployee(self): print "Name : ", self.name, ", Salary: ", self.salary "创建 Employee 类的第一个对象" emp1 = Employee("Zara", 2000) "创建 Employee 类的第二个对象" emp2 = Employee("Manni", 5000) emp1.displayEmployee() emp2.displayEmployee() print "Total Employee %d" % Employee.empCount

empCount 变量是一个类变量,它的值将在这个类的所有实例之间共享。你可以在内部类或外部类使用 Employee.empCount 访问。

第一种方法__init__()方法是一种特殊的方法,被称为类的构造函数或初始化方法,当创建了这个类的实例时就会调用该方法

self 代表类的实例,self 在定义类的方法时是必须有的,虽然在调用时不必传入相应的参数。

继承

class A: # 定义类 A ..... class B: # 定义类 B ..... class C(A, B): # 继承类 A 和 B .....

重写

class Parent: # 定义父类 def myMethod(self): print '调用父类方法' class Child(Parent): # 定义子类 def myMethod(self): print '调用子类方法'

运算符重载

class Parent: # 定义父类 def myMethod(self): print '调用父类方法' class Child(Parent): # 定义子类 def myMethod(self): print '调用子类方法'

类属性和方法

类的私有属性
__private_attrs:两个下划线开头,声明该属性为私有,不能在类的外部被使用或直接访问。在类内部的方法中使用时 self.__private_attrs。

类的方法
在类的内部,使用 def 关键字可以为类定义一个方法,与一般函数定义不同,类方法必须包含参数 self,且为第一个参数

类的私有方法
__private_method:两个下划线开头,声明该方法为私有方法,不能在类的外部调用。在类的内部调用 self.__private_methods

单下划线、双下划线、头尾双下划线说明:
__foo__: 定义的是特殊方法,一般是系统定义名字 ,类似 __init__() 之类的。

_foo: 以单下划线开头的表示的是protected 类型的变量,即保护类型只能允许其本身与子类进行访问,不能用于 from module import *

__foo: 双下划线的表示的是私有类型(private)的变量, 只能是允许这个类本身进行访问了。

【相关推荐:Python3视频教程

The above is the detailed content of Super detailed compilation and sharing of the basics of getting started with Python. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:csdn.net. If there is any infringement, please contact admin@php.cn delete