One day quick start to Python

Young and frivolous 2021-02-22 15:30:03
day quick start python


Python By Guido Van Rossum stay 90 Early design , Now it's one of the most common programming languages . Especially the popularity of artificial intelligence , In addition, its grammar is simple and beautiful , It's a beginner's Guide AI Essential programming language .

Python Basic grammar

identifier

The first character must be an English letter or an underline _ . The rest of the identifier consists of the letters 、 Numbers and underscores . Identifiers are case sensitive .

Reserved words

Reserved words are keywords , Cannot be used as any identifier name . keyword The module can output all keywords of the current version :
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']

notes

Single line notes using #, Notes are for people to see , Can be anything , The interpreter ignores comments .

Multiline comments use ''' or """.
# print(" I am a comment , Not execute ")
print(" Normal code execution ")

'''
This is a multiline comment , Use three single quotes
This is a multiline comment , Use three single quotes
'''
print("Hello, World!")

"""
This is a multiline comment , Use three double quotes
This is a multiline comment , Use three double quotes
"""
print("Hello, World!")

Lines and indents

Python Use indentation to represent code blocks instead of braces {}. The number of indented spaces is variable , But statements in the same code block must have the same number of indented spaces . Suggest four spaces .

Be careful Tab Mixed with four spaces will report an error , This mistake is not easy to detect .

Input and output

It's usually one line per statement , If the statement is long , We can use backslash (\) To implement multiline statements . stay , {}, or Multiple lines in , You don't need a backslash .
sentence1 = "I love " + \
"python"

sentence2 = ["I", "love",
"python"]

Basic data type

Computer programs deal with different kinds of data , Different data types need to be defined .Python Variables in do not need to be declared , Each variable must be assigned a value before use , The variable will not be created until it is assigned a value .

Python Variables are variables , There is no type , said " type " Is the type of object in memory that the variable refers to . Equal sign (=) Used to assign values to variables . Equal sign (=) To the left of the operator is a variable name , Equal sign (=) To the right of the operator is the value stored in the variable .

Numeric type (Number)

Number types are immutable data .Python3 Support int( Integers )、float( Floating point numbers )、bool( Boolean )、complex( The plural ), The assignment and calculation of numeric types are very intuitive .
# int( Integers )
a = 3
# float( Floating point numbers )
b = 3.5
#bool( Boolean )
c = True
#complex( The plural )
d = 4+3j
print(a, b, c, d)

# Built in type Function can be used to query the object type of variable
print(type(a), type(b), type(c), type(d))

# You can also use isinstance To judge
#isinstance and type The difference is that :type A subclass is not considered a superclass type ,isinstance Think of a subclass as a superclass type
print(isinstance(a, int))
print(isinstance(a, float))

About numerical operations , Multiple variables can be assigned at the same time , Such as a, b = 1, 2. A variable can be assigned to different types of objects .

Division contains two operators :/ Returns a floating point number ,// Returns an integer . In mixed computing ,Python Will convert integer to floating point .
# Add 
print("Add operation: 5 + 4 = ",5 + 4)
# reduce
print("Sub operation: 5 - 4 = ",5 - 4)
# ride
print("Mul operation: 5 * 4 = ",5 * 4)
# except , Get a floating point number
print("Div operation: 5 / 4 = ",5 / 4)
# except , Get an integer
print("Div operation: 5 // 4 = ",5 // 4)
# Remainder
print("Mod operation: 5 % 4 = ",5 % 4)
# chengfang
print("Pow operation: 5 ** 4 = ",5 ** 4)

String type (String)

Python No separate character type , One character is the length of 1 String . String in single quotes ' Or double quotes " Cover up .
s1 = "I love python"
s2 = 'I love python'
print(s1)
print(s2)

# Index value to 0 For starting value ,-1 To start at the end
print("s1 Initials :", s1[0])
print("s1 The last letter character :", s1[-1])
print(" Output characters from the third to the fifth :", s1[2:5])

# plus + Is the concatenator of a string
# asterisk * Means to copy the current string , The number that follows is the number of copies
str = "I love python "
print(" Connection string :", str + "!!!")
print(" Output string twice :", str * 2)

# The backslash \ Escapes special characters
# If you don't want the backslash to escape , You can add a... Before the string r
print('I\nlove\npython')
print(" Backslash escape is invalid :",r'I\nlove\npython')

List the type (List)

A list type is an ordered collection . The types of elements in a list can vary , It supports Numbers , Strings can even contain lists ( The so-called nested ). The list is written in square brackets Between 、 Comma separated list of elements .
list_a = [1, 2, 3, 4, 5, 6]
list_b = [7, 8, 9]
print(list_a)
print(list_b)

# Lists can be indexed and intercepted , After the list is truncated, a new list containing the required elements is returned
print (" Output complete list : ", list_a)
print (" The first element of the output list :", list_a[0])
print (" Output from the second to the third element :", list_a[1:3])
print (" Output all elements starting with the third element :", list_a[2:])
print (" Connect the list twice :", list_a * 2)
print (" Connection list :", list_a + list_b)

# The elements in the list can be changed
list_a = [1, 2, 3, 4, 5, 6]
print(" Before the change :", list_a)
list_a[0] = 0
list_a[2:5] = [7, 8, 9]
print(" After change :", list_a)

#append Method : Add a new object at the end of the list
list_a = [1, 2, 3, 4, 5, 6]
print(" Before adding :", list_a)
list_a.append(7)
list_a.append(8)
print(" After adding :", list_a)

#del sentence : Delete list elements
list_a = [1, 2, 3, 4, 5, 6]
print(" Before deleting :", list_a)
del list_a[0]
print(" After deleting :", list_a)

#len Method : Calculate the length of the list
list_a = [1, 2, 3, 4, 5, 6]
print(" List length :", len(list_a))

#max Method : Returns the maximum value of a list element .min Method : Returns the minimum value of a list element
list_a = [1, 2, 3, 4, 5, 6]
print(" List minimum :", min(list_a))
print(" List maximum :", max(list_a))

#list Method : Convert string to list
str = '123456'
print(" After the transformation :", list(str))

#count Method : Count the number of times an element appears in a list
list_a = [1, 1, 2, 3, 4, 5, 6]
print("1 stay list_a Is the number of times :", list_a.count(1))

#index Method : Find the index position of the first occurrence of a value from the list
list_a = [1, 2, 3, 4, 5, 6]
print("3 First occurrence :", list_a.index(3))

#insert Method : Insert the object into the list at the specified location
list_a = [1, 2, 3, 4, 5, 6]
print(" Before insertion :", list_a)
list_a.insert(0 ,7)
print(" After inserting :", list_a)

#pop Method : Removes an element from the list ( Default last element ), And returns the value of that element
list_a = [1, 2, 3, 4, 5, 6]
print(" The last element is removed by default :", list_a.pop)
print(" Specifies to remove the first element :", list_a.pop(0))

#reverse Method : Flip the elements in the list
list_a = [1, 2, 3, 4, 5, 6]
print(" Before turning over :", list_a)
list_a.reverse
print(" After flipping :", list_a)

#sort Method : The method does not return a value , But sort the original list
list_a = [1, 3, 2, 5, 4, 6]
print(" Before ordering :", list_a)
list_a.sort
print(" Ascending sort :", list_a)
list_a.sort(reverse = True)
print(" null :", list_a)

A tuple type (Tuple)

Tuple types are immutable types , Tuples use braces .
tup1 = (1, 2, 3, 4, 5 )
# When a tuple contains only one element , You need to add a comma after the element , Otherwise parentheses will be used as operators
tup2 = (50,)
tup3 = (50)
print(type(tup2))
print(type(tup3))

# Access tuples : Use subscript indexes to access values in tuples
tup1 = (1, 2, 3, 4, 5 )
print ("tup1[0]: ", tup1[0])
print ("tup1[1:3]: ", tup1[1:3])

# Modify tuple : Element values in tuples are not allowed to be modified , But you can join and combine tuples
tup1 = (1, 2)
tup2 = ('a', 'b')
# Create a new tuple
tup3 = tup1 + tup2
print(tup3)

# Delete tuples : Element values are not allowed to be deleted , But you can use del Statement to delete the entire tuple
tup1 = (1, 2, 3, 4, 5 )
print(tup1)
del tup1
print(" Deleted tuple tup1: ")
print(tup1)

# Tuple operators : Such as + Number and * Number
tup1 = (1, 2)
tup2 = ('a', 'b')
print(" Connect :", tup1 + tup2)
print(" Copy 3 Time :", tup1 * 3)

#len: Count tuple elements
tup1 = (1, 2)
print(" Tuple length :", len(tup1))

#max Method : Returns the maximum value of an element in a tuple .min Method : Returns the minimum value of an element in a tuple
tup1 = (1, 2)
print(" Tuple maximum :", min(tup1))
print(" Tuple maximum :", max(tup1))

#tuple Method : Convert list to tuple
list1= ['1', '2']
print(" Before conversion :", list1)
tup1 = tuple(list1)
print(" After the transformation :", tup1)

Collection types (Set)

A set type is an unordered sequence of non repeating elements . Use braces {} perhaps set Function to create a collection .

Be careful : To create an empty collection, you must use the set instead of {}, because {} Is used to create an empty dictionary .
a={'a','b','c'}
b=set('abc')
c=set
d={}
print(a)
print(b)
print(type(a), type(b), type(c), type(d))

# Disorder
a = set('python')
print(a)

# The opposite sex
a = set('good')
print(a)

#add Method : Add an element to the collection
a = set('good')
a.add('p')
print(a)

#update Method : Add elements to the collection
a = set('good')
a.update('p')
print(" Add an element ", a)
a.update(['a', 'b', 'c'])
print(" Add multiple elements ", a)
a.update(['H', 'e'], {'l', 'l', 'o'})
print(' Add lists and collections ', a)

#remove Method : Removes the specified element
s = {'P', 'y', 't', 'h', 'o', 'n'}
s.remove('t')
print(" Get rid of t", s)

#pop Method : Remove elements at random
s = {'P', 'y', 't', 'h', 'o', 'n'}
print(" Delete elements randomly :", s.pop)

#clear Method : Remove all elements from the collection
s = {'P', 'y', 't', 'h', 'o', 'n'}
s.clear
print(" Empty the set :", s, len(s))

#issubset Method : Determine whether the specified set is a subset of the method parameter set
A = set('abcd')
B = set('cdef')
C = set('ab')
print("C whether A A subset of :", C.issubset(A))

#union Method : Returns the union of two sets , It can also be used. |
print("A and B Combine :", A|B)
print("A and B Combine :",A.union(B))

#intersection Method : Returns the intersection of sets , It can also be used. &
print("A and B intersection :", A&B)
print("A and B intersection :",A.intersection(B))

#difference Method : Difference set , It can also be used. -
print("A and B Difference set :", A-B)
print("A and B Difference set :",A.difference(B))

Dictionary type (Dictionary)

Dictionary types are variable types . In the same dictionary , key (key) Must be unique .

Each key value of the dictionary (key=>value) Yes, with a colon (:) Division , Use commas... Between each pair (,) Division , The whole dictionary is enclosed in curly brackets ({}) in .
# use {} Create a dictionary 
dict1 = {"a":"1", "b":"2"}
print(dict1)
# With built-in functions dict
dict2 = dict(a="1", b="2")
print(dict2)

# Visit the values in the dictionary
dict1 = {"a":"1", "b":"2"}
print ("dict1['a']: ", dict1['a']) # If there's no mistake
print ("dict1.get('a'): ", dict1.get('a')) # If there is no return None
print(" Get all key value :", dict1.keys)
print(" Get all value value :", dict1.values)

# Add a new key / It's worth it
dict1 = {"a":"1", "b":"2"}
print (" Before adding :", dict1)
dict1['c'] = 3
print (" After adding :", dict1)

# Delete dictionary specified elements
dict1 = {"a":"1", "b":"2"}
print (" Before deleting :", dict1)
del dict1['a']
print (" After deleting :", dict1)

# Empty dictionary
dict1 = {"a":"1", "b":"2"}
print (" Before emptying :", dict1)
dict1.clear
print (" After emptying :", dict1)

#dir Method : see dict All the methods
print(dir(dict))

Condition judgment and cycle

Under controlled conditions : Through the execution of one or more statements (True perhaps False) To determine the code block to execute .

Use a colon after each condition :, Indicates the statement block to be executed after the condition is met . Use indentation to divide statement blocks , Statements with the same indentation number form a statement block together . stay Python There is no switch–case sentence .
#if operation 
x = 5
if x > 3:
print("yes")

#if nesting :if...elif...else
# Also can put the if...elif...else The structure is placed in another if...elif...else In structure
x = 99
if x<60:
print(" fail, ")
elif x<80:
print(" good ")
else:
print(" good ")

#while loop
sum = 0
counter = 1
while counter <= 10:
sum = sum + counter
counter += 1
print("1 To 10 The sum is : %d" % sum)

#while Recycling else sentence
count = 0
while count < 5:
print (count, " Less than 5")
count = count + 1
else:
print (count, " Greater than or equal to 5")

#for sentence :for A loop can traverse any sequence ( list 、 String, etc. )
str = 'python'
list1 = ['I', 'love', 'python']
print(" Traversal string ")
for i in str:
print(i)
print(" Traverse the list ")
for i in list1:
print(i)

#range function : Traversing a sequence of numbers , You can use built-in range Functions generate sequences
for i in range(5):
print(i)

# You can also use range Specify the value of the interval
for i in range(2,6):
print(i)

# You can also make range Start with a specified number and specify a different increment ( step ), It could be negative
for i in range(0, 10, 3):
print(i)

for i in range(-10, -100, -30):
print(i)

# Can combine range and len Function to traverse the index of a sequence
list1 = ['I', 'love', 'Python']
for i in range(len(list1)):
print(list1[i])

#break sentence : Jump out of for and while Circulatory body of
list1 = ['I', 'love', 'Python']
for i in list1:
if i == 'love':
break
print(' At present, it is :', i)

#continue sentence : Skip the remaining statements in the current loop block , Then proceed to the next cycle
var = 10
while var > 0:
var = var -1
# Variable is 5 Skip output
if var == 5:
continue
print (' Current value :', var)
print ("hello world!")

#pass sentence :pass It's an empty statement , To maintain the integrity of the program structure ,pass Not doing anything , Generally used as occupation statement
while True:
pass # Wait for the keyboard to interrupt (Ctrl+C)

function

Functions are organized , Reusable , To achieve oneness , Or code snippets associated with functions . Function can improve the modularity of application , And code reuse .

Python Many built-in functions are provided , such as “print”, You can also create your own functions , This is called a user-defined function .
# 1. Nonparametric functions 
# use def Define new functions
def my_func:
print("test...")
return 1
# Call function
my_func

# 2. There are parametric functions
# Key parameters 、 Default parameters 、 Variable parameters .

# Key parameters : Specifies the name of the parameter when called , And it is consistent with the parameter name when the function is declared . Using keyword parameters allows the order of parameters when a function is called to be different from when it is declared .
def my_func1(x, y):
print(x)
print(y)

# Standard call
my_func1(1, 2)
# Key word call
def my_func1(y = 1, x = 2)

# Default parameters : When a function is declared , Specifies the default value of the formal parameter , Call without passing in parameters ( Use the default value ).
def my_func2(x, y=1):
print(x+y)

my_func2(2)

# Variable parameters : Variable parameter means that the number of parameters passed in is variable , It can be 1 individual 、2 From one to any one .
# Add a... Before the parameter * Number . Inside the function , Parameters numbers What was received was a tuple.

def my_func3(*numbers):
sum = 0
for n in numbers:
sum = sum + n * n
return sum

# Function call
my_func3 # Return results 0
my_func3(1,2) # Return results 5

# Key parameters : Variable parameters allow you to pass in 0 Or any number of parameters , These variable parameters are automatically assembled into a tuple. The keyword parameter allows you to pass in 0 Or any number of parameters with parameter names , These key parameters are automatically assembled into a function dict.

def my_func4(x, **kw):
print ('x:', x, 'other:', kw)

# Except for the required parameters x Outside , Also accepts keyword parameters kw. When the function is called , Only the required parameters can be passed in .
my_func4(8)

# You can also pass in any number of keyword parameters
my_func4(8, z="66")

class

class (Class): A collection of objects with the same properties and methods . It defines the properties and methods that are common to each object in the collection . Object is an instance of a class .

Class variables : Class variables are common to the entire instantiated object . Class variables are defined in the class and outside the function body . Class variables are usually not used as instance variables .

Data member : Class variable or instance variable , Used to process data related to classes and their instance objects .
# Create a class Student
class Student(object):
" Student achievement "
def __init__(self, name, score):
self.name = name
self.score = score

def print_score(self):
print('%s: %s' % (self.name, self.score))

# establish Student Class object bart
jack = Student('Bart Simpson', 59)
# establish Student Class object lisa
bob = Student('Lisa Simpson', 87)
# Access the properties of a class
jack.print_score
bob.print_score
# Add one 'age' attribute
jack.age = 7
print(" Add one 'age' attribute :",hasattr(jack, 'age'))
# modify 'age' attribute
jack.age = 8
print(" modify 'age' attribute :",getattr(jack, 'age'))
# Delete 'age' attribute
del jack.age
print(" Delete 'age' attribute :",hasattr(jack, 'age'))


Class inheritance


One of the main benefits of object-oriented programming is code reuse , One way to achieve this reuse is through the inheritance mechanism .

A new class created by inheritance is called a subclass or derived class , The inherited class is called the base class 、 Parent or superclass .
# Write a project called Fruit Of class, perform run Method can be printed directly 
# To write Apple and Orange Class time , You can directly from Fruit Class inheritance
class Fruit(object):
' Parent class Animal'
def run_father(self):
print(' Call the superclass method ...')

class Apple(Fruit):
' Subclass 1 Apple'
def run_son(self):
print(' Call subclass method ...')

class Orange(Fruit):
' Subclass 2 Orange'
def run_son(self):
print(' Call subclass method ...')
# Instantiate subclasses
apple = Apple
orange = Orange
# Call the superclass method
apple.run_father
orange.run_father
# Call subclass method
apple.run_son
orange.run_son


Method rewriting


If the function of the parent method doesn't meet your needs , You can override your parent's methods in a subclass
class Fruit(object):
' Parent class Animal'
def run(self):
print(' Call the superclass method ...')

class Apple(Fruit):
' Subclass 1 Apple'
def run(self):
print(' Subclass 1 Apple Override parent method ...')

class Orange(Fruit):
' Subclass 2 Orange'
def run(self):
print(' Subclass 2 Orange Override parent method ...')
# Instantiate subclasses
apple = Apple
orange = Orange
# Call the superclass method
apple.run
orange.run

modular

Python modular (Module), It's a Python file , With .py ending , Contains Python Object definition and Python sentence . Modules allow you to organize your Python Code segment .

Assign the relevant code to a module to make your code better , Easier to understand . Modules can define functions , Classes and variables , Modules can also contain executable code .
# The import module 
import math
# Now you can call the functions contained in the module
print(" seek e Of n The next power :",math.exp(1))

# from…import sentence : Import a specified part from the module into the current namespace
# Import specific functions in the module
from math import exp
# Now you can use this function directly
print(" seek e Of n The next power :",exp(1))

# from…import* sentence : Import all the items in a module . However, such a declaration should not be used too much
from math import *

Long press QR code to focus on

AI Introduction to Xiaobai

ID:StudyForAI

Study AI Study ai( Love )

Looking forward to meeting you ~

Recommended reading

《Python Web crawler from entry to practice

author : Tang Song Chen Zhiquan

 One day quick start python


This book will show you how to use Python Write a web crawler program to get big data on the Internet . Whether or not there is a programming foundation , As long as you're interested in crawler technology , This book can lead readers from the beginning to the advanced , Then to the actual battle , Learn about reptiles step by step , Finally write your own crawler program .

 One day quick start python


National drinking guide

What is Hengduanshan ?

One starts to go uphill 3 Signs

Great river 40 year : Seven opportunities to change fate

In a bad mood , Look at this. 3 Pictures , Suddenly the light came out
版权声明
本文为[Young and frivolous]所创,转载请带上原文链接,感谢
https://pythonmana.com/2021/02/20210221071855625m.html

  1. Python中的解决中文字符编码的问题
  2. Solving the problem of Chinese character coding in Python
  3. Translation: practical Python Programming 02_ 01_ Datatypes
  4. Installation and use of Python and tensorflow in win10 environment (Python version 3.6, tensorflow version 1.6)
  5. Python series 46
  6. Linux安装Python3
  7. 【python接口自动化】- 正则用例参数化
  8. Python RestFul Api 设计
  9. filecmp --- 文件及目录的比较│Python标准库
  10. Installing python3 on Linux
  11. [Python] Matplotlib 圖表的繪製和美化技巧
  12. (資料科學學習手札108)Python+Dash快速web應用開發——靜態部件篇(上)
  13. 翻譯:《實用的Python程式設計》02_01_Datatypes
  14. 【python接口自动化】- 正则用例参数化
  15. 翻译:《实用的Python编程》02_02_Containers
  16. 两年Java,去字节跳动写Python和Go
  17. [Python interface automation] - regular use case parameterization
  18. Python restful API design
  19. 翻译:《实用的Python编程》02_02_Containers
  20. 两年Java,去字节跳动写Python和Go
  21. 翻译:《实用的Python编程》02_02_Containers
  22. Python基于粒子群优化的投资组合优化研究
  23. ubuntu部署django项目
  24. 兩年Java,去位元組跳動寫Python和Go
  25. 翻譯:《實用的Python程式設計》02_02_Containers
  26. 这样学习Python,爷爷都学会了!超简单Python入门
  27. [Python] 基于 jieba 的中文分词总结
  28. 【python】递归听了N次也没印象,读完这篇你就懂了
  29. [Python] 基于 jieba 的中文分词总结
  30. 人理解迭代,神则体会递归,从电影艺术到Python代码实现神的逆向思维模式
  31. [Python] 基於 jieba 的中文分詞總結
  32. Python属于后端开发还是前端开发?Python入门!
  33. 【python】递归听了N次也没印象,读完这篇你就懂了
  34. 一天快速入门python
  35. 学习Python对年龄有没有要求?30岁可以吗?
  36. 清华教授!12小时整理的最全Python教程(文末无偿分享)
  37. 使用Python开发DeFi项目
  38. python 函数详解
  39. Python工程师是做什么的?前景如何?
  40. Filecmp -- comparison of files and directories
  41. Python - zip() 函数
  42. 30 周年生日,Python 先驱是怎么评价这门语言的?
  43. Drawing and beautifying skills of [Python] Matplotlib chart
  44. Python + dash rapid web application development static components
  45. Translation: practical Python Programming 02_ 01_ Datatypes
  46. python将excel自适应导入数据库
  47. 从小白到大师,这里有一份Pandas入门指南
  48. [Python] 茎叶图和复合饼图的画法
  49. [Python interface automation] - regular use case parameterization
  50. Translation: practical Python Programming 02_ 02_ Containers
  51. Two years of Java, to write Python and go
  52. Translation: practical Python Programming 02_ 02_ Containers
  53. Two years of Java, to write Python and go
  54. Python-geoplot 空间核密度估计图绘制
  55. Python-seaborn 经济学人经典图表仿制
  56. python空间绘图- regionmask掩膜操作示例
  57. Python 空间绘图 - Cartopy 经纬度添加
  58. Python-pykrige包-克里金(Kriging)插值计算及可视化绘制
  59. Python 批量重采样、掩膜、坡度提取
  60. python - 多种交通方式可达圈分析