程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

PythonSummary

編輯:Python

一、注釋

單行注釋 #
多行注釋 """ """

二、運算符
1,算術運算符:

 + 加法運算符
- 減法運算符
* 乘法運算符
/ 除法運算符
% 求模(余)運算符
// 整除運算(地板除法)
** 冪次方

2,關系(比較)運算符

 >
<
>=
<=
==
!=

3,邏輯運算符

 與(並且) and
或(或者) or
非(取反) not

4,所屬運算符

in # 變量 in 容器
not in

5,賦值運算符

=
+= # a += 10 <==> a = a + 10
-=
*=
/=
//=
%=
**=

6,三目運算符:

表達式? 變量1 : 變量2
# Ternary operators in other programming languages
int a = 10 < 8 ? 20 : 40;
# python中
變量1 if 表達式 else 變量2

三、選擇結構

單分支
if 條件:
# 如果條件成立,The indented code is executed 
雙分支
if 條件:
# 如果條件成立,則執行if中的代碼
else:
# 如果條件不成立,execute here(else)的代碼
多(三)分支
if 條件1:
# 如果條件1成立,則執行if中的代碼
elif 條件2:
# 如果條件1成立,則Execute the code here
elif 條件3:
# 如果條件1成立,則Execute the code here
……
[else:
# 剩余情況,Execute the code here

四,循環結構

while循環
while 條件:
# 執行循環體
for循環
python的for循環,本質是一種for in結構的foreach循環,That is, an iterative structure
python提供的for循環,The idea is to iterate over iterable objects(Iterable)traversal of the data.
for 臨時變量 in Iterable:
# The result of each iteration is stored in this temporary variable
print(臨時變量)

五、常見容器

列表(list):
列表的定義:
有兩種方式:This is done through the features of weak data-typed languages
ls = [12,34,45,88,99]
第二種,is to call a global function
list()
list([元素1, 元素2, ……, 元素n])
set:
General collections are usedhash表實現,
無序且不重復!!!!
定義集合
s = {
值1, 值2,…… 值n} # set定義是,不能為空,Empty means an empty dictionary
ssss = set([1,2,3,4,45,5]) # 使用set函數完成list轉換為set
同樣的道理
list({
1,3,2,43,44,4,5}) # 將set轉換為list
元組(tuple)
固定的值,不可變數據類型,類似於java、CThese are enumerated types
字典(dict):
注意,pythonThe fields in are also one{
}形式,Just the elements inside,Not an individual value
Rather, it is a key-value pair
d = {
"name": "張三", "age": 34, "nickname": "法外狂徒"}

六、函數

什麼是函數:
It is a collection of function codes with a name
python如何定義函數:
Naming convention for function names,Follow variable naming conventions!!!!
def 函數名稱([參數列表]): # define function 定義函數
函數體
如果有返回值,則使用returnThe keyword returns the function result
return 返回值
調用函數:
函數名稱([實參列表]
局部變量(本地變量):
定義在函數內部的變量叫做局部變量,作用域是當前函數
全局變量:
Define the module directly(py文件)中的變量,叫做全局變量
return關鍵字:
The value exists inside the function,function if accessedreturn關鍵字,則立刻返回


遞歸(recursion):
Essentially it is a solution to a problem.

七、切片:
切片是python提供,A way to cut strings
Slicing isn't just for strings,有序序列(list、tuple、字符串)

字符串[下標]
字符串[start:end] # 切割字符串,注意:[start, end),默認步長是1
字符串[start:end:step] # 切片操作時,指定步長
注意:注意,Slices do not subscript out of bounds;
默認步長是1,可以指定,If specified as a positive number,It means cutting from left to right
But if specified as a negative number,表示從右向左切
如:s[::-1],Indicates to reverse the order of strings,類似於s.reverse()

八、內置模塊

 - math - random - os
- sys - datetime - date
- calendar - hashlib - hmac
等等

九、對象序列化
對象序列化:
對象:抽象概念
If we want to transfer objects,It is necessary to convert objects from logical concepts to real data(字符串、字節)
對象反序列化:
Convert data in physical state to logical state

pythonTwo modules for object serialization and deserialization are provided
pickle:對象 <> 字節數據
json: 對象 <
> json

pickle:
pickle.dump(obj, file):對象持久化(先序列化,在持久化)
pickle.load(file):反持久化,Reread data from disk as objects

picke.dumps(obj):對象序列化
pickle.loads(bytes):反序列化對象

json模塊:
ison.dump(obj, file):對象持久化(先序列化,在持久化)
ison.load(file):反持久化,Reread data from disk as objects

ison.dumps(obj):對象序列化
ison.loads(bytes):反序列化對象

十、面向對象
類(class):An abstract summary of something with similar properties,抽象概念.
對象(object):A specific case of a class of things,實實在在的案例(實例)
定義類:
python定義類使用,class關鍵定義.

class 類名稱: # The naming convention for class names follows big camelCase
class 類名稱(父類):
class 類名稱(Object):

面向對象的三大特征:
封裝:

在面向對象中:
1、All object-oriented related functions,封裝在一個類裡面
2、在一個類中,將屬性私有化,The outside world is not allowed to access the property,
Generally by providing disclosed methods(getter、setter)來訪問和設置
封裝的本質:It is the protection of the data of the attributes in the class,Illegal access from outside is not allowed
只允許,Access the data through the provided public means!!!
After privatizing the property,How to access this property in the outside world?
1、直接提供get和set方法
2、將get和setPack a handful again,After that use a property-like method for private properties
3、使用@propertyThe decorator completes the encapsulation
class User(object):
def __init__(self):
# python中,Prefix the property name or method name__,Indicates to privatize the property or method
# Outside of the class at this point,There will be no access to private properties and methods
self.__name = "劉建宏"
self.__age = 16
self.__gender = "男"
self.__email = "[email protected]"
self.__tel_phone = "110"
def get_name(self):
return self.__name
def set_name(self, name):
self.__name = name
def get_age(self):
return self.__age
def set_age(self, age):
self.__age = age
def say(self):
print("我叫{},I said something".format(self.__name))
print("這句話,我不愛聽,So I am sad")
self.__cry()
def __cry(self):
"""The method is private,私有的方法,is used inside the class"""
print("我哭了,我很難過")
if __name__ == '__main__':
u1 = User()
# u1.say()
# print(u1.__name)
# u1.name = "劉帥哥"
# print(u1.name)
# 通過getter、setter訪問和設置屬性
print(u1.get_name())
u1.set_name("Zhang Qiusuo")
u1.set_age(19)
print(u1.get_name())
print(u1.get_age())
# PythonThe packaging is not particularly perfect
# print(u1._User__age)

繼承

Offspring inherit the characteristics or traits of the previous generation
Subclasses inherit some methods from the superclass(The parent class allows inherited methods)
class RichMan(object):
def __init__(self):
# 私有屬性無法繼承
self.__name = "阿爸"
self.money = 40000000
self.company = "alibaba"
def say(self):
print("哎,Business is not doing well,我對錢不感興趣,The thing I regret the most,is to create a company")
def __tell(self):
print("These are my whispers,I don't want anyone to know")
# python允許多繼承
class Son(RichMan, object):
pass
if __name__ == '__main__':
s = Son()
print(s.money)
print(s.company)
# print(s.__name)
s.say()
# s.__tell()

多態

面向對象中,多態:父類引用指向子類實例的現象!
ArrayList al = new ArrayList(); // 創建一個ArrayList對象
List list = new ArrayList(); // 父類引用指向子類實例的現象!!!

十一、python高級
生成器(generator):
列表推導式,
優點:through a piece of code,Generate the list data we want,非常強大
缺點:If there is a lot of data,直接生成數據,內存太大
因此pythonProvides a new way of generating lists,This method is the list generator

ls = []
def get_prime():
for i in range(2, 101):
flag = is_prime(i)
if flag:
# ls.append(i)
yield i # yield雖然看起來和return很像,但是注意,不一樣
def is_prime(num):
for j in range(2, num):
if num % j == 0:
# 不可能是質數
return False
return True
# res = get_prime()
# print(ls)
# print(res)
# print(next(res))
# print(next(res))
# for i in res:
# print(i)

Traversal of generators:
使用forA loop can iterate over the generator
for 變量 in generator:
print(This variable is the value of a generator each time it loops)
The second way to write a list generator:
If the list comprehension is too complicated,want to use this way[表達式]非常困難
針對於這種情況,The initialization of the list is generally done using a function

Convert the function to list generation,使用關鍵字yield
注意:When the function is converted to a list builder,函數的執行順序

迭代器(Iterator):
可以通過next函數調用,並且Returns the next value對象
可迭代對象(Iterable):
Can be called cyclically,Returns the next value,可迭代對象
字符串、列表、元組、字典、集合
閉包(closure):
A function capable of variables inside a method function,被稱為閉包

閉包:Causes the function to reside in memory,無法被釋放!!!!
Local variables are globalized:避免了全局污染!!!

裝飾器:
The embodiment of the decorator design pattern,When we are not satisfied with the original function,
We can do this by decorating the original code,to implement code enhancements

 python提供的裝飾器(Decorator),It is to strengthen and decorate the original function,
A syntax that enhances the functionality of a function
python的裝飾器,It runs the process

十二、異常處理
An abnormal software crash phenomenon,稱為異常
異常進行處理,The essence is a kind of software fault tolerance

抓捕異常:

 The judgment code may be abnormal
try:
可能出異常的代碼
except:
可能出現的異常
def main():
y_o_n = input("是否退出程序(y/n)?")
while y_o_n != "y":
print("請輸入一下信息,用空格分開")
input_str = input("性別 體重(kg) 身高(cm) 年齡: ")
str_list = input_str.split(" ")
try:
gender = str_list[0]
weight = float(str_list[1])
height = float(str_list[2])
age = int(str_list[3])
if gender == "男":
bmr = (13.7*weight)+(5.0*height)-(6.8*age)+66
elif gender == "女":
bmr = (9.6*weight)+(1.8*height)-(4.7*age)+655
else:
bmr= -1
if bmr!= -1:
print("你的性別:{},體重:{}公斤,身高:{}厘米,年齡:{}歲".format(gender,weight,height,age))
print("your basal metabolic rate:{}大卡".format(bmr))
else:
print("This gender is not currently supported")
except ValueError:
print("請輸入正確信息")
except IndexError:
print("Too little information entered!")
except:
print("程序異常!")
print()
y_o_n=input("是否退出程序(y/n)?")
if __name__ == '__main__':
main()

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved