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

Python basic knowledge collection

編輯:Python

1. list

Lists are the most commonly used Python data type , It can appear as a comma separated value in square brackets .

The data items of a list do not need to have the same type

Create a list , Just enclose the different data items separated by commas in square brackets

Code understanding : Index of the list , Addition, deletion and modification of list data , And the use of list derivation

# list 
all_in_list=[0.3,'hello','True']
print(' The list data is :',end='')
print(all_in_list) # The forward index starts from
res=all_in_list[0]
print('all_in_list[0] The value of is :',end='')
print(res)
# Reverse all slave -1 Start
res=all_in_list[-2]
print('all_in_list[-2] The value of is :',end='')
print(res)
# Slice of the list , Left closed right away
res=all_in_list[0:2]
print('all_in_list[0:2] The slice value of is :',end='')
print(res) # The new element in the end
all_in_list.append('hello world')
# Insert the element before the specified position , Become an element in the specified position
all_in_list.insert(0,'pre-hello')
print(' Add the new element as :',end='')
print(all_in_list) # Remove elements
all_in_list.remove('hello world')
# Delete the first two elements
del all_in_list[:2]
print(' After deleting the element, it is :',end='')
print(all_in_list) # Modify element values
all_in_list[0]=100
print(' Modify the element to :',end='')
print(all_in_list) # for loop
x=[]
for i in range(10):
x.append(i) print('for After adding the element in a loop, it is :',end='')
print(x) # List derivation
b=[i for i in range(1,11)]
c=[i**2 for i in range(1,11)]
d=[i**2 for i in range(1,11) if i%2==0]
print(' The value of each list derivation is :',end='')
print(b)
print(c)
print(d) # practice 1: Find the area of curved trapezoid
import math
n=10000
width=2*math.pi/n
# Method 1 : utilize for Loop through the core data structure
x=[]
y=[]
for i in range(n):
x.append(i*width)
for i in x:
y.append(abs(math.sin(i)))
S=sum(y)*width
print(' Method the area of a curved trapezoid is :',end='')
print(S)
# Method 2 : Use list derivation to build the core data structure
s=[abs(math.sin(i*width))*width for i in range(n)]
print(' Methods the area of the trapezoid with two curved edges is :',end='')
print(sum(s))

Code run results

2. The operator

Python Languages often use the following types of operators : Arithmetic operator 、 Compare relational operators 、 Assignment operator 、 Logical operators

Code understanding : Logical controller 、 Inclusion of strings in、 Conditional statements 、 Exchange value operation of bubble sort

# Python Logical controller 
res=1<2
print('1<2 The correctness of the :',end='')
print(res)
res=1<2<3
print('1<2<3 The correctness of the :',end='')
print(res)
res='Name'=='name'
print("'Name'=='name' The correctness of the :",end='')
print(res)
res='M' in 'magic'
print("'M' stay 'magic' Correctness in :",end='')
print(res) # Conditional decision statement
if 1<2:
print(' If 1<2 correct , The output :', end='')
print('1.hello') if 1<0:
print(' If 1<0 correct , The output :', end='')
print('2.hello')
else:
print(' If 1<0 Incorrect , The output :', end='')
print('2.world') if 1<0:
print(' If 1<0 correct , The output :', end='')
print('3.hello')
elif 2<1:
print(' If 1<0 Incorrect , but 2<1 correct , The output :', end='')
print('3.world')
else:
print(' If 1<0 Incorrect , And 2<1 It's not true either , The output :', end='')
print('3.hehe') # Bubble sort
x=[1,2,6,0.3,2,0.5,-1,2.4]
print(' The value before bubble sorting is :', end='')
print(x)
n=len(x)
for i in range(n):
for j in range(i):
if x[j]>x[i]:
# Exchange value
x[i],x[j]=x[j],x[i] print(' The value after bubble sorting is :', end='')
print(x)

Code run results

3. Dictionaries

Dictionary is another variable container model , And can store any type of object .

Each key value of the dictionary key:value Yes, with a colon : Division , Comma between each key value pair , Division , The whole dictionary is enclosed in curly brackets {} in , The format is as follows :d = {key1 : value1, key2 : value2 }

Code understanding : According to the dictionary index value , Modified value , add value , Delete value , And dictionary derivation to generate dictionary

# Dictionaries 
dic={'h':'hello',0.5:[0.2,0.3],'w':'world'}
print(' The dictionary data is :',end='')
print(dic) # According to the key index value
res=dic['h']
print("dic['h'] The corresponding value is :",end='')
print(res)
# Modify an element according to the key
dic['h']=100
print(" The revised dictionary is :",end='')
print(dic)
# Add an element
dic['hw']='hello world'
print(" The dictionary after adding a key value is :",end='')
print(dic)
# Add multiple elements at the same time
dic.update({1:2,3:4})
print(" The dictionary after adding multiple key values is :",end='')
print(dic)
# Delete an element according to the key
del dic['h']
print(" The dictionary after deleting the key value is :",end='')
print(dic) # Dictionary derivation
a={i:i**2 for i in range(10)}
print(" The dictionary generated by dictionary derivation is :",end='')
print(a)

Code run results

4. character string

The string is Python The most commonly used data type in . We can use quotation marks ( ' or " ) To create a string .

Creating a string is simple , Just assign a value to the variable .

Code understanding : There are two ways to generate strings with and without line breaks 、 Index of a string , Basic operation of splicing 、 String segmentation 、 All strings are lowercase

# character string , There is no difference between a double quoted string and a single quoted string 
string="My name"
print(' The generated string is :'+string)
# Three quotation marks can be used for line breaking
string='''My name
'''
print(' The generated string with newline is :'+string)
string='My name'
print(' Single quotation marks and double quotation marks generate the same string , It's for :'+string)
print(string)
# The first element of the index string
print(' The first element of the string is :'+string[0])
# The first two elements of the index string
print(' The first two elements of the string are :'+string[:2])
# Repeat the string twice
print(' Repeat the string twice as :'+string*2)
# String concatenation
print(' The splicing string is :',end='')
print(string+' is xxx') # Split string , Divide by commas , The return result is a list
res=string.split(sep=',')
print(' The string is divided according to the comma and then is :',end='')
print(1,string)
# Change all string letters to lowercase
res=string.lower()
print(' Change all string letters to lowercase :',end='')
print(res)

Code run results

5. file

Code understanding

# File operations 
f=open("Walden.txt","r")
# Read file contents
txt=f.read()
print(txt)
# Before reading the contents of the file 100 That's ok
txt=f.read(100)
print(txt)
f.close()
# Read the file line by line , And return to the list
f=open("Walden.txt","r")
txt_lines=f.readlines()
print(txt_lines)
f.close() # practice 3: Read the words in the novel
import re
f=open("Walden.txt","r")
# The data type read in is string
txt=f.read()
f.close()
# Change the characters in the string to lowercase
txt=txt.lower()
# Remove the punctuation marks from the novel
txt=re.sub('[,.?:“\’!-]','',txt)
# Word segmentation
words=txt.split()
word_sq={}
for i in words:
if i not in word_sq.keys():
word_sq[i]=1
else:
word_sq[i]+=1
# Sort
res=sorted(word_sq.items(),key=lambda x:x[1],reverse=True)
print(res)

6. function

You can define a function that you want to function , Here are the simple rules :

  • Function code block to def Key words start with , Followed by function identifier name and parentheses ().
  • Any arguments and arguments passed in must be placed between parentheses . Parentheses can be used to define parameters .
  • The first line of the function optionally uses the document string — Used to store function descriptions .
  • Function contents start with a colon , And indent .
  • return [ expression ] End function , Optionally return a value to the caller . Without expression return It's equivalent to returning to None.

Code understanding

# Function customization 
# The first way
def Sum(x,y):
return x+y # The second way , Simple customization of functions
# return x The square of
y=lambda x:x**2
# return x The first element of
y1=lambda x:x[1] res=Sum(1,2)
print(res)
res=y(10)
print(res)
res=y1(['hello',0])
print(res) # practice 4: User defined function for finding the even number of sequences
def su(x):
z=0
for i in x:
if i%2==0:
z+=1
return z
res=su([1,2,3,4,5,6])
print(res)

7. object-oriented

Some basic features of object orientation :

  • 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 .
  • Method rewriting : If the method inherited from the parent class does not meet the needs of the child class , It can be rewritten , This process is called method coverage (override), Also known as method rewriting .
  • local variable : Variables defined in methods , Class that only works on the current instance .
  • Instance variables : In the declaration of a class , Properties are represented by variables . This variable is called instance variable , It is declared inside the class declaration but outside the other member methods of the class .
  • Inherit : That is, a derived class (derived class) Inherited base class (base class) Fields and methods for . Inheritance also allows the object of a derived class to be treated as a base class object . for example , There is such a design : One Dog Object of type derived from Animal class , This is a simulation " It's a (is-a)" Relationship ( Case diagram ,Dog It's a Animal).
  • Instantiation : Create an instance of a class , Class specific objects .
  • Method : Functions defined in class .
  • object : Data structure instance defined by class . Object contains two data members ( Class variables and instance variables ) And methods .

Code understanding

# The difference between method and function 
all_in_list=[2.5,'hello','world',3]
string='My name'
all_in_list.append('hehe')
# For string objects , It's not append Methodical
#string.append('Y’) res=string.split()
# split It's a method , Is a method only available for string objects
#all_in_list.split()
print(all_in_list)
print(res) # object-oriented
class Human:
def __init__(self,ag=None,se=None):
# Attributes of a class
self.age=ag
self.sex=se
# Class method
def square(self,x):
return x**2 zhangfei=Human(ag=23,se=' male ')
res=zhangfei.square(10)
print(res)
res=zhangfei.age
print(res)
res=zhangfei.sex
print(res)

Python- More relevant articles on the collection of basic knowledge

  1. Python Development 【 Second articles 】:Python Basic knowledge of

    Python Basic knowledge of One . First knowledge of basic data types type : int( integer ) stay 32 On the bit machine , The number of digits of an integer is 32 position , The value range is -2**31-2**31-1, namely -2147483648-2147483647 stay 64 position ...

  2. python Basic knowledge of ( Two )

    The following content , As python Supplement of basic knowledge , It mainly involves the creation and characteristics of basic data types , And new data types Bytes Introduction of type

  3. python Basic knowledge of ( One )

    python Basic knowledge of ( One ) One .python Introduction to development Python Was founded by Guido van Rossum.1989 During Christmas , In Amsterdam ,Guido In order to kill the boredom of Christmas , Determined to develop a new script ...

  4. python Basic knowledge explanation ——@classmethod and @staticmethod The role of

    python Basic knowledge explanation ——@classmethod and @staticmethod The role of In a member function of a class , You can add @classmethod and @staticmethod Modifier , There is a certain difference between the two , Simple ...

  5. python There are five modules in crawler : The crawler starts the entry module ,URL The manager stores the crawler's URL And reptiles URL list ,html Downloader ,html Parser ,html Output device At the same time, we can master urllib2 Use 、bs4(BeautifulSoup) Page parser 、re Regular expressions 、urlparse、python Basic knowledge review (set Set operations ) And so on .

    This time python A hundred steps Encyclopedia of reptiles , There is a detailed analysis of the steps of the crawler , There are detailed comments on each step of the code , It can be grasped through this case python The characteristics of reptiles : 1. Crawler dispatch entry (crawler_main.py) # coding: ...

  6. python Crawlers and data visualization --python Basic knowledge of

    Abstract : Come into contact with by chance python voice , I think the grammar is simple . Powerful , Just a friend shared an online class <python Crawlers and data visualization >, So in work and leisure time to learn , And do the following course notes , The whole is roughly divided into 4 individual ...

  7. python Summary of basic knowledge - Operation and Maintenance Notes

    Contact python It's been a while , The following for python The use of basic knowledge to do a complete comb :1) avoid ‘\n’ And so on : a) Using escape character ‘\’ b) Using the original characters ‘r’ print r'c:\now' ...

  8. Python Basic knowledge of ( 5、 ... and )

    # -*- coding: utf-8 -*-# @Time : 2018-12-25 19:31# @Author : Three Jin aphrodisiac # @Email : [email protected]# @Fi ...

  9. Python Basic knowledge of (Basic knowledge)

    Python Basic knowledge of (Basic knowledge) 1. know Python& Basic environment construction 2.Python Basics ( On ) 3.Python Basics ( in ) 4.Python Basics ( Next ) 5.Python ...

  10. Python Basic knowledge of ( One )

    1.Python brief introduction 1.1.Python Introduce python Founded by Guido · Van rosum (Guido van Rossum).1989 Christmas period of , Guido · Van rosum ( Chinese name : Uncle GUI ) To spend time in Amsterdam ...

Random recommendation

  1. 1089 Longest text substring V2(Manacher Algorithm )

    1089  Longest text substring  V2(Manacher Algorithm ) Base time limit :1  second Space restriction :131072 KB The score is : 0  difficulty : Basic questions   Collection   Focus on Palindrome string refers to aba.abba.cccbccc.aaaa ...

  2. c# XML And entity classes ( Serialization and deserialization )[ Brick ]

    link: http://blog.okbase.net/haobao/archive/62.html by:  I'm so full We need to be in XML And entity classes ,DataTable,List Switch between , Here is XmlU ...

  3. hdoj 2066 A solo trip

    Problem Description Although cao'er is a road maniac ( I have been in Hangdian for more than a year , Even people who get lost on campus , Khan, ~), But cao'er still likes traveling very much , Because on the journey I'll meet a lot of people ( Prince charming ,^0^), A lot of things , It's also abundant ...

  4. WPF4.5 Information about new and enhanced features in

    This topic contains information about Windows Presentation Foundation (WPF) edition 4.5 Information about new and enhanced features in . This topic contains the following sections : Ribbon controls improve performance , Set the grouping when the display is large ...

  5. spring-data-mongodb A system xml Two data sources are configured in the file

    spring-data-mongodb A system xml Two data sources are configured in the file The reference documents are as follows : http://www.iteye.com/problems/92789 http://stackoverfl ...

  6. stay VB6/VBA Using regular expressions

    One . About the cause Recently Office Of QQ The group asked how to extract values from a string and add them up . If you use regular expressions, you can solve this problem very quickly . So today I'm going to talk about VB6/VBA Method and code for using regular expressions in , another ...

  7. python Basic modules

    time & datetime modular import timeimport datetime# ## # print("ss")# #time.sleep(5)# # prin ...

  8. spring boot A simple user management DEMO

    summary The Demo Designed to deploy a simple spring boot engineering , Including data editing and viewing functions POM To configure <?xml version="1.0" encoding="UTF- ...

  9. [LeetCode] Array Partition I One of the array splits

    Given an array of 2n integers, your task is to group these integers into n pairs of integer, say (a1 ...

  10. Brief introduction Excel The implementation principle of cell row and column indication ( It is commonly known as spotlight function )

    Original source :www.cnblogs.com/Charltsing/p/CellLight.html QQ:564955427 Excel The implementation principle of cell row and column indication ( It is commonly known as spotlight function ) Cell row and column indication function is in recording ...


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