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

Python quick start notes

編輯:Python

List of articles

    • python Quick start
      • Development environment configuration
      • elements of grammar
        • Novice questions
        • Input and output
        • Strings and variables
            • assignment
            • Common string processing
          • Boolean expression
          • Conditional statements
          • Loop statement
          • list
          • Tuples
          • aggregate
          • Dictionaries
          • function
          • modular
          • file
          • exception handling
          • Classes and objects
          • Multithreading
          • visualization gui Interface

python Quick start

Development environment configuration

python You only need to go to the official website to download the latest version , The main syntax of a mature language is that it will not change greatly with the update of the version , So the choice of version is not really a problem

Recommended anaconda3 Version control , The most convenient way to use is to control every python And the required libraries , In the process of development , It is always the time to install and configure what library files are needed for development , Different development requires different library file environments , When the later projects are packaged , No need to package unused libraries , Improve packaging efficiency

  • anaconda It comes with a large number of commonly used data science packages that do not need to be downloaded
  • Self contained conda The management pack and environment can reduce the problems of various libraries and versions in the process of processing data

Download environment configuration
Download link on official website
Configure the environment variables in the user environment variables set in the system advanced settings

Basic usage
After the environment configuration is completed, you can directly go to cmd Window use conda command

# Set the mirror image
conda config --add channels https://mirrors.tuna.tsinghua.edu.cn/anaconda/pkgs/free/
conda config --add channels https://mirrors.tuna.tsinghua.edu.cn/anaconda/pkgs/main/
conda config --add channels https://mirrors.tuna.tsinghua.edu.cn/anaconda/cloud/conda-forge/
conda config --add channels https://mirrors.tuna.tsinghua.edu.cn/anaconda/cloud/bioconda/
# Set up bioconda
conda config --add channels bioconda
conda config --add channels conda-forge
# Set the channel address when searching
conda config --set show_channel_urls yes
# View virtual environment
conda env list
# Activate the virtual environment
conda activate The name of the virtual environment
# Exit virtual environment
conda deactivate
# Creating a virtual environment
conda install -n Virtual environment name python= Version number
# Delete virtual environment
conda remove Virtual environment name
# View the installed packages
conda list
# Get all the configurations in the environment
conda env export --name myenv > myenv.yml
# Restore the environment again
conda env create -f myenv.yml

elements of grammar

Novice questions

  1. Are all punctuation marks in English
  2. Whether the indentation is correct
  3. Whether the function is spelled correctly

Input and output

# Input 
a=input(" Please enter :")
# Output 
print(a)
# Line break 
print("\n")

Strings and variables

stay cmd Window type jupyter notebook You can enter the interactive interface , It is equivalent to the one you brought with you shell, But compared to it ,notebook The interface is more beautiful and the functions are more comprehensive

assignment
# Variables need not be declared , You can assign values directly 
# Naming rules , Except for keywords , Using letters , Underline , Digital composition , But you can't start with a number , Name normalization 
a=1
b='ct'
# The string can be assigned with single quotation marks or double quotation marks , But when there is a single quotation mark in the string , Use double quotation marks on the outside , On the contrary, there are double quotation marks inside and single quotation marks outside 
Common string processing
# This method is usually used to deal with regular expressions when writing crawlers , Can not be used in the code , Generally speaking, the code 
# Inside / To escape, add a backslash to the front or , Add... Before the string r, Of the current string Escape character \ It will fail. 
#windows The path of is separated by a backslash , stay python Inside , Will treat the backslash as an escape , It can cause conflict 
url = "https://translate.google.cn/?sl=auto&" \
"tl=zh-CN&text=hello&op=translate"
headers = {
'user-agent': "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:88.0) Gecko/20100101 Firefox/88.0"}
html = requests.get(url, headers=headers)
result = re.match(r"^<span.*?>(.*?)</span>", html)
print(result)
print(r'ct\n')
# Strings can be merged by a plus sign , You can also operate with the multiplication sign , You can't -/*

Common string handling functions

a="https://www.baidu.com"
#find() Find a substring in a long string , The index of the leftmost position of the substring is returned , If not, return to -1.
print(a.find("t")
#replace() Replace the matching old character in the string with the following new string 
print(a.replace("h","wa"))
#split() Slice the string with the specified delimiter , If parameters num If it's worth it , It is divided into num Characters 
print(a.split("w"))
# format() Very convenient string splicing function , Very often , Add curly braces to the string {}, Use... After the end of the quotation marks , Method to replace the parentheses in the string 
b="aaa"
c="t{},h{}".format(b,"cc")
Boolean expression
#bool() Function can evaluate any value , The result is Ture perhaps False, Null value such as ([],{}'',"")
# The sum is 0 Or is it None The result is False, Everything else is True, And circulation , Use with conditional statements 
# The operator has and or Literally ,

This is used for discrete school assignments , Very convenient

Conditional statements

Follow c The conditional sentence judgment of language is basically the same , Just pay attention to the correctness of the format .

# Indentation is four spaces , Direct tapping tab Key will do 
a=1
if a:
print("hello")
else:
pass
Loop statement

for loop

# It can be a numerical cycle , There's only one number , The default is from zero to the first digit of this number , This figure is not included 
for i in range(10):
print(i)
# It can be range() Multiple parameters , The starting point , End , step 
for i in range(1,10,3)
# It could be a list 
for i in [" Xiao Ming "," Xiaohong "," Small ."]:
print(i)
# It can also be a string 
for i in "range":
print(i)

while loop
continue,pass and break Use

a=10
while a<20:
a=a+1
if a%2==0:
continue
elif a==15:
pass
else:
print('1')
list

Used to store different data types , Enclosed in parentheses , String to be quoted , No numbers

service=[3,'ht','ssh']
print(service[1]) ## Output second element 
print(service[-1]) ## Output the last element 
# section 
print(service[1:]) ## Print the contents after the first element 
print(service[:-1]) ## Print the contents before the last element 
print(service[::-1]) ## Output in reverse order 
# List manipulation functions 
service.pop() ## The last element pops up 
a = service.pop(0) ## Pop up the second 1 Elements ### It can be assigned 
service.remove('ssh') ## Specify the name of the deleted object ## Delete directly , It cannot be assigned ## Sequence number cannot be specified , Only the... Of the object to be deleted can be specified 
del service ## Delete list 
del service ## Directly delete the entire list 
print(service)
names = ['alice','Bob','coco','Harry']
names.sort()
names ### according to ASCLL Sort ### First sort the first letter of uppercase , The first letter of reorder is lowercase 
names.sort(key=str.lower) ### Sorting strings is not case sensitive , Equivalent to converting all elements to lowercase , Reordering 
names.sort(key=str.upper) ### Equivalent to converting all elements to uppercase , Reordering 
Tuples

Once the tuple is created , Its elements cannot be changed , So tuples are immutable lists , The sign is in parentheses () wrap up

aggregate

Use curly braces to enclose , Different from list, etc , You cannot use subscripts to access the elements inside , You can use a loop to get elements , Elements in a collection cannot be repeated , You can use... For a list set() Method into a collection , Indirectly realize the de duplication operation

Dictionaries

A dictionary is a variable container model , You can store any object , Store in key value pairs , Use colons to separate , Use commas between each pair of key value pairs , Division , The whole dictionary uses curly braces {} Cover up

# Dictionary format 
dict={
"name":" Xiao Ming ","age":12,"like":['ball','book']}
# Dictionary access 
print(dict["name"])
print(dict["like"][0])
  1. This can be used to solve a very large task of discrete mathematics
  2. Global variables are stored in two files through dictionaries for use
function

Pay attention to local variables and global variables in the function

def Function name ( Parameters ):
pass
modular
# Use import Import the written file 
# from Module name import Method / class /*
file

Use the built-in open Function to read
After reading, use close() Close file

#mode Means open mode ,w It's writing ,r Means read ,r+ It can be read or written , The return value is a file object 
f = open(" File path ","mode")
f.write(" Text ")
f.flush() # Write the memory contents to the hard disk immediately 
f.close()
# Commonly used 
with open(filename, 'wb') as f: # Open the file in binary form 
f.write(" Image resources ")
exception handling

try It works by , When you start a try After the statement ,python Mark in the context of the current program , So you can go back here when the exception occurs ,try Clauses are executed first , What happens next depends on whether an exception occurs during execution .

  • If so try An exception occurred during the execution of the following statement ,python Just jump back to try And execute the first... That matches the exception except Clause , Exception handling completed , Control flow through the whole try sentence ( Unless a new exception is thrown when handling the exception ).
  • If in try An exception occurred in the following statement , There is no match except Clause , Exceptions will be delivered to the upper level try, Or to the top of the program ( This will end the program , And print the default error message ).
  • If in try No exception occurred while clause was executing ,python Will perform else Statement after statement ( If there is else Words ), And then control the flow through the whole try sentence .
try:
< sentence > # Run other code 
except < name >:
< sentence > # If in try Part of it triggered 'name' abnormal 
except < name >,< data >:
< sentence > # If triggered 'name' abnormal , Get additional data 
else:
< sentence > # If no exceptions occur 
#try-finally Statement will execute the last code whether or not an exception occurs .
try:
< sentence >
finally:
< sentence > # sign out try Always carry out 
Classes and objects
# The basic format 
class Persion:
name=" Xiao Ming "
age=12
def fun(self):
print(age)
p=Persion()
print(p.name)
# Every time you create an object , Will automatically call __init__() Method , Be similar to java Construction method of 
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
p1 = Person("Bill", 63)
print(p1.name)
print(p1.age)
Multithreading
import threading
import time
def run(n):
print("task", n)
time.sleep(1)
print('2s')
time.sleep(1)
print('1s')
time.sleep(1)
print('0s')
time.sleep(1)
if __name__ == '__main__':
t1 = threading.Thread(target=run, args=("t1",))
t2 = threading.Thread(target=run, args=("t2",))
t1.start()
t2.start()
# Inherit threading.Thread From defining thread classes , Its essence is reconstruction Thread Class run Method 
import threading
import time
class MyThread(threading.Thread):
def __init__(self, n):
super(MyThread, self).__init__() # restructure run Function must write 
self.n = n
def run(self):
print("task", self.n)
time.sleep(1)
print('2s')
time.sleep(1)
print('1s')
time.sleep(1)
print('0s')
time.sleep(1)
if __name__ == "__main__":
t1 = MyThread("t1")
t2 = MyThread("t2")
t1.start()
t2.start()
visualization gui Interface

pyqt5 Library gui Programming , You can add window components in the visualization , Definition UI


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