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

Python learning notes_ Day01

編輯:Python

Environmental preparation

The official site :http://www.python.org

IDE: Integrated development environment

pycharm Configuration of

  1. If it's the first time , After opening , The following appears , Choose... Below “ Do not import configuration ”

Insert picture description here

  1. If it's professional , Need to buy

Insert picture description here

  1. Choose the interface style

Insert picture description here

  1. Create a new project , A software project is a project , Corresponding to a folder

[ Failed to transfer the external chain picture , The origin station may have anti-theft chain mechanism , It is suggested to save the pictures and upload them directly (img-qA8upgBq-1584409255959)(C:\Users\daiyajie\AppData\Roaming\Typora\typora-user-images\1584352090231.png)]

  1. Creating a virtual environment

Location: Project directory , That is, the path where the code file is stored

Project Interpreter: The interpreter uses a virtual environment , It is equivalent to putting the python The program is copied to a folder , Install later

python The software is installed in this folder . Future projects completed , This environment is no longer needed , Just delete the virtual environment directory .

[ Failed to transfer the external chain picture , The origin station may have anti-theft chain mechanism , It is suggested to save the pictures and upload them directly (img-ISIULfav-1584409255960)(C:\Users\daiyajie\AppData\Roaming\Typora\typora-user-images\1584352199928.png)]

  1. If the previous step , Automatic creation of virtual environment failed , You can create virtual environments manually
# Creating a virtual environment
[[email protected] ]# python3 -m venv ~/nsd1903
# When using virtual environments , It needs to be activated
[[email protected] ]# source ~/nsd1903/bin/activate (nsd1903)
[[email protected] ]# python --version
Python 3.6.7
  1. modify pycharm The virtual environment of the project

File -> Settings -> Project: Day01 -> Project Interpreter -> Point the gear in the upper right corner -> Add Local -> Existing Enviroment -> spot blow … -> Input /root/nsd1903/bin/python

[ Failed to transfer the external chain picture , The origin station may have anti-theft chain mechanism , It is suggested to save the pictures and upload them directly (img-nJUsyKBR-1584409255962)(C:\Users\daiyajie\AppData\Roaming\Typora\typora-user-images\1584352291851.png)]

[ Failed to transfer the external chain picture , The origin station may have anti-theft chain mechanism , It is suggested to save the pictures and upload them directly (img-MFEefgEZ-1584409255965)(C:\Users\daiyajie\AppData\Roaming\Typora\typora-user-images\1584352302945.png)]

  1. Modify edit text size

File -> Settings -> Editor -> font -> size Change the size

python Operation mode

  • Interactive interpreter
[[email protected] devops0101]# source ~/nsd1903/bin/activate
(nsd1903) [[email protected] devops0101]# python
>>> print("hello world!")
>>> exit
Use exit() or Ctrl-D (i.e. EOF) to exit
  • File form stay pycharm Right click on the item name to select the fourth item , You can copy to the absolute path of the project
# vim hi.py
print("Hello World!")
(nsd1903) [[email protected] day01]# python hi.py
Hello World!

python grammar

  • python Use indentation to express code logic , Recommended indents 4 A space
  • Code with sub statements , There are colons behind them
  • Annotation use # Number , stay pycharm You can press ctrl + / Comment or uncomment
  • Multiple statements on the same line , Semicolons are required to separate , But still not recommended .

I / O statement

# The string must be written in quotation marks , There is no difference between single and double quotation marks
>>> print('hello world!')
# One print In the sentence , Can print multiple items ,123 No quotes , Representation number . By default, items are separated by spaces
>>> print('hao', 123, 'world')
hao 123 world
# When the output , You can also specify the separator between items
>>> print('hao', 123, 'world', sep='_')
hao_123_world
>>> print('hao', 123, 'world', sep='***')
hao***123***world
# Strings can be used + Splicing
>>> print('hello' + 'world')
helloworld
# adopt input Get keyboard input ,input The string in parentheses is the screen prompt , Save the results entered by the user in a variable num in ,num It's a variable. , send Don't use it like shell Add like that $ Prefix .
>>> num = input("number: ")
number: 100
>>> num
'100'
# As long as through the input Read , All character types , Characters cannot perform four operations with numbers
>>> num + 10
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: must be str, not int
# Can pass int Function num Convert to integer , And then calculate with numbers
>>> int(num) + 10
110

Variable

The amount that will change . Constants do not change , The quantity that represents the literal meaning does not change .100,'abc' Such a quantity is literal , Indicates the literal meaning of what you see .

Why use variables : convenient , Variables can have meaningful names .

Naming convention for variables :
  • The first character can only be a letter or an underline
  • Other characters can be letters or underscores or numbers
  • Case sensitive
>>> 2a = 10 # Error
>>> _a = 5 # OK, Not commonly used
>>> abc-1 = 10 # Error
# The following two variables are different
>>> a = 10
>>> A = 100
Recommended naming method :
  • Variable and function names are in lowercase letters , Such as pythonstring
  • brief , Such as pystr
  • meaningful
  • Multiple words are separated by underscores , Such as py_str
  • Variables are nouns , Functions use predicates ( Verb + Noun ), Such as phone Said variable , use update_phone According to the function
  • The class name is in the form of hump , Such as MyClass

Using variables

# Variables must be assigned before they are used
>>> print(a) # a No definition , So the name is wrong
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'a' is not defined
>>> counter = 0
# Assignment operation from right to left . The following code means to counter Take the value of and add 1, And then assign it to the variable counter
>>> counter = counter + 1
# The above code can be abbreviated as
>>> counter += 1
# python zen
>>> import this Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
……
Beauty is better than ugliness , The light is better than the dark , Simplicity is better than complexity

Operator

Arithmetic operations : Four mathematical operations
>>> 5 / 3
1.6666666666666667
>>> 5 // 3 # Keep only the quotient
1
>>> 5 % 3 # Keep only the remainder
2
>>> divmod(5, 3) # divmod Function can return both quotient and remainder
(1, 2)
>>> a, b = divmod(5, 3) # The quotient and remainder are stored in a and b in
>>> a
1
>>> b
2
>>> 2 ** 3 # 2 Of 3 Power
8
Comparison operations
# The result of the comparison operation is True or False
# String comparison , Compare character by character , Once the result appears, it will not continue . Letter press ASCII Value comparison .
>>> 'x' > 'abc'
True
# stay python in , Support continuous comparison
>>> 20 > 15 > 10
True
>>> 20 > 10 < 15 # amount to 20 > 10 and 10 < 15
True
Logical operators
# and Both expressions are true , The result is true
>>> 10 > 5 and 10 < 20
True
# or Expressions on both sides as long as one side is true , The result is true
>>> 10 > 5 or 10 < 3
True
# not Reverse true and false
>>> 10 > 5
True
>>> not 10 > 5
False
>>> 10 < 5
False
>>> not 10 < 5
rue

data type

Numbers

  • int Integers , No decimal point
  • bool, Boolean number ,True The value of is 1,False The value is 0
  • Floating point numbers , There's a decimal point
  • The plural . In order to solve whose square is -1, Mathematicians invented the plural number

The representation of integers

# python Default to 10 Binary output , Numbers without any prefix are considered to be 10 Hexadecimal number
>>> 23 # 10 Base number
23
>>> 0o23 # 0o It begins with 8 Hexadecimal number
19
>>> 0O23
19
>>> 0x23 # 0x It begins with 16 Base number
35
>>> 0X23
35
>>> 0b11 # 0b It begins with 2 Base number
3
>>> 0B11
3
>>> 0x234
564
>>> 2 * 16 * 16 + 3 * 16 + 4
564
# application
>>> import os
>>> os.chmod('login.py', 755)
(nsd1903) [[email protected] day01]# ll login.py
--wxrw--wt. 1 root root 87 7 month 31 11:45 login.py
>>> os.chmod('login.py', 0o755) # linux The system permissions are 8 Hexadecimal number , No 10 Base number
(nsd1903) [[email protected] day01]# ll login.py
-rwxr-xr-x. 1 root root 87 7 month 31 11:45 login.py

character string

  • A string is a set of characters enclosed in quotation marks , There is no difference between single and double quotation marks .
# s1 and s2 Single and double quotation marks are used respectively , They mean exactly the same thing
>>> s1 = 'hello world'
>>> s2 = "hello world"
# The string tom Assign a value to a variable name
>>> name = 'tom'
# s3 Medium name It means literally name
>>> s3 = "hello name"
>>> s3
'hello name'
# s4 Medium %s Use the following variables name The value of
>>> s4 = "hello %s" % name
>>> s4
'hello tom'
>>> "%s is %s years old" % ('tom', 22)
'tom is 22 years old'
  • python Three quotation marks are allowed ( Three consecutive single or double quotes ) Save the style of the string
>>> words = "hello\nwelcome\ngreet" >
>> print(words) # When printing ,\n Escape to carriage return
hello
welcome
greet
>>> words # Internal storage , Press enter to save as \n
'hello\nwelcome\ngreet'
# The three quotation marks can only be used to retain the style of carriage return when entering , But internal storage is nothing special
>>> wordlist = """hello
... welcome
... greet"""
>>> print(wordlist)
hello
welcome
greet
>>> wordlist
'hello\nwelcome\ngreet'
  • String related operations
>>> py_str = 'python'
>>> len(py_str) # Calculate the length of the string
6
>>> py_str[0] # Take out the first character , Subscript to be 0
'p'
>>> py_str[5]
'n'
>>> py_str[6] # If the subscript is out of range , There will be mistakes
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: string index out of range
# Subscript is negative , It means taking... From right to left
>>> py_str[-1]
'n'
>>> py_str[-6]
'p'
# section , Cut the segment
>>> py_str[2:4] # Contains the characters corresponding to the starting subscript , Does not contain the character corresponding to the ending subscript
'th'
>>> py_str[2:6] # When taking slices , No error will be reported if the subscript exceeds the range
'thon'
>>> py_str[2:6000]
'thon'
>>> py_str[2:] # End subscript does not write , It means to get to the end
'thon'
>>> py_str[:2] # The starting subscript does not write , Means to take... From the beginning
'py'
>>> py_str[0:2]
'py'
>>> py_str[:] # From beginning to end
'python'
>>> py_str[::2] # The step value is 2
'pto'
>>> py_str[1::2]
'yhn'
>>> py_str[::-1] # If the step size is negative, it means taking... From right to left
'nohtyp'
# Membership is broken
>>> 't' in py_str # t In a string ?
True
>>> 'th' in py_str
True
>>> 'to' in py_str # to Although in the string , But it's not continuous , return False
False
>>> 'to' not in py_str # to Not in the string ?
True
# Strings are passed through + Realize splicing
>>> 'hao' + '123'
'hao123'
>>> str(123) # Built-in functions str You can turn numbers into strings
'123'
>> 'hao' + str(123)
'hao123'
# Duplicate string
>>> '*' * 30
'******************************'
>>> '#' * 30
'##############################'
>>> 'ab' * 30
'abababababababababababababababababababababababababababababab'

list

Use [] Represents a list . The list is container type , It can store all kinds of data .

>>> alist = [10, 20, 30, 'tom', 'jerry']
>>> len(alist)
5
>>> alist[0]
10
>>> alist[-1]
'jerry'
>>> 30 in alist
True
>>> alist[3:]
['tom', 'jerry']
# The list supports modifying contents
>>> alist[2] = 300
>>> alist
[10, 20, 300, 'tom', 'jerry']
# adopt append Method , You can append data to the list
>>> alist.append('bob')
>>> alist
[10, 20, 300, 'tom', 'jerry', 'bob']
>>> alist * 2
[10, 20, 300, 'tom', 'jerry', 'bob', 10, 20, 300, 'tom', 'jerry', 'bob']
>>> alist + 100 # Report errors , Lists cannot be spliced with numbers
>>> alist + [100] # List splicing

Tuples

Tuples can be considered immutable lists , The rest are exactly the same .

>>> atuple = (10, 20, 300, 'tom', 'jerry', 'bob')
>>> len(atuple)
6
>>> atuple[0]
10
>>> atuple[2:4]
(300, 'tom')
>> atuple[0] = 100 # Report errors , Do not modify
# Single element tuples , Must have comma , Otherwise it's not tuples .
>>> a = (10)
>>> a # a It's not a tuple , It's numbers
10
>>> b = (10,)
>>> b
(10,)
>>> len(b)
1

Dictionaries

The dictionary is out of order , So you can't take subscripts and slices like strings .

>>> adict = {'name': 'tom', 'age': 22}
>>> len(adict)
2
>>> 'tom' in adict # 'tom' It's a dictionary key Do you ?
False
>>> 'name' in adict
True
>>> adict['name'] # The dictionary passed key Take out value
'tom'
# Dictionary key Can't repeat , assignment ,key Modification of existence val,key If it doesn't exist, add
>>> adict['age'] = 25
>>> adict
{'name': 'tom', 'age': 25}
>>> adict['email'] = '[email protected]'
>>> adict
{'name': 'tom', 'age': 25, 'email': '[email protected]'}

Data type classification

  • By storage model
  • Scalar : character string 、 Numbers
  • Containers : list 、 Yuan Zu 、 Dictionaries
  • Press to update the model
  • variable : list 、 Dictionaries
  • immutable : character string 、 Tuples 、 Numbers
  • By access model
  • direct : Numbers
  • The order : character string 、 list 、 Tuples

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