Welcome to
Magic house !!
Update time 2022.5.13
This article explains the combination of code and results , Be able to get started quickly python Basic usage
0 Point acquisition source code : Portal
The text resource directory is as follows :
Source code :
# python Variables in do not need to be declared But it must be assigned Only after assignment can we create
# So some people call variables names
# python Output code for
print('hello world') # hello world yyds
The magician = 666 # because python Use utf-8 Code, so you can use Chinese
print( The magician ) # Output variables
print("Majician", The magician )# Output both characters and variables
# Advanced knowledge
print("Majiciam", Magician is cool , end='!') # Set ending
print("Majiciam", Magician is cool , sep='-', end='!') # Set up interval
result :
>>>print('hello world') # hello world yyds
hello world
>>> Magician is cool = 666 # because python Use utf-8 Code, so you can use Chinese
>>>print( Magician is cool ) # Output variables
666
>>>print("Majician", Magician is cool ) # Output both characters and variables
Majician 666
>>>print("Majiciam", Magician is cool , end='!')
Majiciam 666!
>>> print("Majiciam", Magician is cool , sep='-',end='!')
Majiciam-666!
# How to use python Data structure in / Data representation and storage
# Standard data type = 【
# ”Number( Numbers ):[’int.float,bool,complex( The plural )'],
# “String( character string )”,
# “list( list )”,
# “Dictionary: Dictionaries ”,
# “Set:( aggregate )”,
# “Tuple:( Tuples )"
# 】
import math
a = -3.5
b = abs(a) # absolute value
print(b)
c = math.sin(b)
print(c)
# list (List)
all_in_list = [
1,
'love',
True,
[1, 2, 3]
]
# Every element of the list is mutable ,
# Each element in the list is ordered ,
# The list can hold Python All objects
print(all_in_list)
index = all_in_list[1]
index = all_in_list[-3]
index = all_in_list[0:2] # Slice of the list , Head and tail , Only 1 To 2, barring 2,
print(index)
# Add, delete, modify and search the list
all_in_list.append("hello world") # Attach the last element
all_in_list.insert(0, "pre_hello") # Insert elements
print(all_in_list)
all_in_list.remove("hello world") # Deletes the specified element
print(all_in_list)
del all_in_list[:2] # Remove elements
print(all_in_list)
all_in_list[0] = 100
print(all_in_list)
#for loop # Low efficiency So use list derivation
x = []
for i in range(10):
x.append(i)
#print(x)
# List derivation
x = [i for i in range(3,10)]
y = [i**2 for i in range(3,10)]
z = [i**2 for i in range(3,10) if i%2==0] # Output even items
print(x)
print(y)
import math
n = 10
x = []
y = []
width = 2 * math.pi / n
# Method 1 :for Loop to establish the core data structure
for i in range(n):
x.append(i * width)
y.append(abs(math.sin(x[i]))) # The absolute value
sums = sum(y) * width # Sum function
# Establish the core data structure by list derivation ( As far as possible need not for loop , High time complexity )
x = [i * width for i in range(n)]
y = [abs(math.sin(i * width)) for i in range(n)]
z = [abs(math.sin(i * width)) * width for i in range(n)]
sums = sum(z)
print(x)
print(y)
print(sums)
# python The operator Mostly with C Language is similar to
# assignment Relationship operation Logic etc. ( It also returns a value )
# Logic
res = 1 < 2 < 3 # At different times, you can continuously compare Guess it's right < > Overload No parameters return Boll Type data , And the parameter return class continues to compare
res = 'M' in 'Magic' # Judge if it's in there
print(res)
# Only if elif else while No, switch 了
# Conditional decision statement if There is no need to add ()
if 1 < 2:
print('hello')
if 1 < 0:
print('hello')
else:
print("world")
if 1 < 0:
print('hello')
elif 1 < -1:
print("world")
else:
print("!")
# bubble sort
x = [1, 2, 3, 4, 123, 1, 64, 1, -2]
n = len(x)
for i in range(n): # More cycles , Higher time complexity
for j in range(i): # Ensure that in the cycle x[i] Value is the largest , Whatever is smaller in front of him , Once there is one x[j]>x[i] j+1 The back is also bigger than x[j] and x[i] Keep changing
if x[j] > x[i]: # Exchange method !!!
x[i], x[j] = x[j], x[i]
print(n)
print(x)
# character string
# Any text in these quotation marks
# Single quotation marks are exactly the same as double quotation marks , However, it is recommended to introduce single quotation marks during development ,
# ''' Three quotation marks are used for long paragraphs or descriptions , As long as the quotation marks don't end , You can wrap any line '''
# String is an immutable data type
string = " character string "
string = '''hello Hey world'''
string = 'my ,name'
print(string)
# Basic usage of string ,
# Splicing char1 + char2 + char3,
# repeat 'word'*3,
# transformation int(string),
# Slicing and indexing :
# str[-3],
# str[1:4],
# str[3:]
res = string[1] # String index
res = string[1:4] # String index
res = string * 3
res = string + ' is '
# The properties of the string itself
# Division
res = string.split(sep=',')
# By default, it is cut according to the space , You can set separate Set separator
# The return value is a list ,
# Be careful !!!!:string Is an immutable data type , Its data cannot be changed , Unless you reassign the name
print(1,string)
string[1] = 'y' # Report errors !!
# Lowercase to uppercase
res = string.upper()
print(res)
Dictionary creation Indexes & Additions and deletions
# Dictionaries Curly braces , list brackets
dictionary = {
'BIDU': 'baidu',
'SINA': 'sina',
'YOKU': 'youku',
}
# key - value Pairs appear ;
# Bonds cannot be repeated ,
# The key cannot be changed , Value can be modified !!!!! So are strings The list can
# Key to index values
dic = {
'h': 'hello', 0.5: [0.3, 0.5], 'w': 'world'}
# dic = {'h': 'hello', 0.5: [0.3, 0.5], 'w': 'world',[2]:2}
# Cannot use list as key !! The premise is that the key cannot become , And the sequence can be changed
print(dic)
demo = dic['h']
demo = dic[0.5] # The elements in the dictionary have no order , Only keys can be used to index
print(demo)
# Look up the dictionary
# modify
dic['h'] = 'hi'
# increase
# Single
dic['new'] = 'new dic' # If there is no such key , A new key value pair will be generated at the end of the dictionary
# Multiple
dic.update({
1: 2, 3: 4})
# Delete
# del dic # Directly delete the whole
del dic['h']
# Dictionary derivation
d = {
i: i ** 2 for i in range(10)}
d = {
i: i ** 2 for i in range(10) if i % 2 == 0}
print(dic)
print(d)
# File operations
# read-only
f = open('beauty_live.text', 'r')
# Read file operation
txt = f.read()
txt = f.read(100) # Set the number of read characters
# Because the file is opened by reading ,
# So after reading the file pointer ,
# The pointer to the file points to the end of the file , You can't continue reading , The pointer needs to be seek Turn into 0
f.seek(0)
# Read only row ( The return value is a list )
txt1 = f.readlines()
# txt1 = f.readline() # Read only one line
f.close()
# print(txt1)
print(txt)
# Count the word frequency of the novel
import re
# View current path
import os
path = os.getcwd() # current word directory Current directory
print(path)
f = open('beauty_live.text', 'r') # Introduce the current project path , If it moves You need an absolute path
txt = f.read() # The data type read in is string
f.close()
txt = txt.lower()
# Remove symbols such as decimal points use ‘’ replace It's empty
re.sub('[,.?!"\'-]', '', txt)
# Because the returned value after using segmentation is a list Can't use re.sub So first deal with segmentation
txt = txt.split()
# Statistics frequency
word = {
}
for i in txt:
if i not in word:
word[i] = 1
else:
word[i] += 1
# Sort the number of times
sor = sorted(word.items(), key=lambda x: x[1], reverse=True)
print(txt)
print(word)
print(sor)
# Function customization
# Simple use lamdba
y = lambda x: x ** 2
y1 = lambda x: x[1]
# Complex use def
def Sum(x=1, y=2): # Set the default value as c++, Ambiguity must be avoided in the front and the back , You can only set the back
return x + y
res = Sum()
demo = y(3)
demo = y1(['hello', 'world'])
print(res)
print(demo)
# Find a given sequence Even numbers
def su(x):
z = 0
for i in x:
if i%2==0:
z +=1
return z
print(su([1,2,34,5,6,2,4,]))
# Object-oriented programming
list = [2.4, 'hello', 'world']
list.append('hehe')
print(list)
string = 'myapp'
string.append('hi') # For string objects No, append Method , Note that it's not a function
list.split() # Similarly, you can't apply to list objects Use split Method Method and object hook
print(string)
# Create your own class
class human: # Methods are functions defined within a class
def __init__(self, ag=None, se=None):
self.age = ag # Attributes of a class
self.sex = se
def square(self, x): # Method
return x ** 2
zhangfei = human(ag=28, se='M') # Class instantiation
demo = zhangfei.square(3)
demo = zhangfei.age
print(demo)
# A module is a file that contains all the variables of the functions you define , Its suffix is .py It's actually a script file
import math # Introduce modules
import def_math
from def_math import Sum
res = math.sin(1) # Call... With a module
res = math.pi
from math import sin, pi # Introduce variables and functions from modules Use it directly In the face of multiple use , This method is recommended !
# Import all variables and functions of the module
from def_math import * # This is not recommended Introduce all into There is no difference between library names Ambiguous with other library function names
res = sin(2) # Direct use in module introduction
res = 2 * pi
res = def_math.Sum(1, 3)
res = Sum(1, 3)
print(res)
modular def_math.py
def Sum(x, y):
return x + y
Download a complete set of resources :
The portal is here !!