程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
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)

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