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

3.1python fundamentals 01

編輯:Python

One 、python introduction

1.1Python Environment building

1.2 notes

  • Python Single-line comments
    Python Use the well number # As a symbol for a single line comment
  • Python Multiline comment
    Python Use three consecutive single quotes ’'' Or three consecutive double quotes """ Annotate multiple lines of content

1.3 python Identifier naming specification

Simply understand , An identifier is a name , It's like each of us has his own name , Its main function is as a variable 、 function 、 class 、 Names of modules and other objects .

  • Order rules

    • An identifier is made up of characters (A~Z and a~z)、 Underline and numbers make up , But the first character cannot be a number .
    • Identifiers cannot be with Python The reserved words in are the same
    • Python In the identifier in , Cannot contain spaces 、@、% as well as $ Equal special character
    • Unless a particular scenario requires , You should avoid using identifiers that start with underscores .
      • An identifier that starts with a single underline ( Such as _width), Represents a class property that cannot be accessed directly , It cannot pass from…import* How to import ;
      • Identifiers starting with double underscores ( Such as __add) Represents a private member of a class ;
      • Identifiers that start and end with double underscores ( Such as __ini__), Is a private identifier
    • Try to avoid using Chinese characters as identifiers
  • Name of identifier , In addition to following these rules , Identifiers in different scenarios , Its name also has certain norms to follow

    • When the identifier is used as the module name , It should be as short as possible , And use all lowercase letters , You can use underscores to divide multiple letters , for example game_mian、game_register etc. .
    • When the identifier is used as the name of the package , It should be as short as possible , It's all in lowercase , Underline is not recommended , for example com.mr、com.mr.book etc. .
    • When the identifier is used as the class name , It should be capitalized with the first letter of the word . for example , Define a Book Class , You can call it Book.
    • The class name inside the module , May adopt “ Underline + title case ” In the form of , Such as _Book;
    • Function name 、 Property and method names in the class , All lower case letters should be used , Multiple words can be separated by underscores ;
    • Constants should be named in all uppercase letters , Words can be separated by underscores ;

1.4 Python keyword ( Reserved words )

Reserved word is Python Some words in a language that have been given a specific meaning , This requires developers to develop programs , You can't use these reserved words as identifiers for variables 、 function 、 class 、 Templates and other object naming .

>>> import keyword
>>> keyword.kwlist
['False', 'None', 'True', 'and', 'as', 'assert', 'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 'except', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'nonlocal', 'not', 'or', 'pass', 'raise', 'return', 'try', 'while', 'with', 'yield']

1.5 Python Built in functions

Python The functions that come with the interpreter are called built-in functions , These functions can be used directly , There is no need to import a module .

>>> dir(__builtins__)

Two 、python Variable types and operators

2.1 Definition and use of variables

a,b=1,2

2.1.1 Python It's a weak type of language

There are two characteristics of weakly typed languages :

  • Variables can be assigned directly without declaration , Assigning a value to a nonexistent variable is equivalent to defining a new variable .
  • The data type of the variable can be changed at any time , such as , The same variable can be assigned to an integer in a moment , Later it's assigned a string .

2.2 value type

Python There are four types of values for median numbers : Integers 、 long integer 、 Floating point and complex number .

  • integer , Such as 1, -1, 0

  • Long integer , It's a big integer , Such as 234234243324

  • floating-point , Such as 1.23、3E-2

  • The plural , Such as 1 + 2j、 1.1 + 2.2j

stay Python View types in , Use type() Built in functions .

>>> type(2)
int
>>> type("2")
str

2.2.1 Hexadecimal 、 Octal and binary

  • Hexadecimal : stay Pthon Use in 0x At the beginning “ Numbers ” Represents a number in hexadecimal . about 9 Later numbers , There is no corresponding Arabic numeral . Then use a Express 10 , b Express 11 , By analogy , Last f Express 15. Do not distinguish in hexadecimal expression “ Letter ” The case of

  • octal : stay Python Use in 0o The first number represents octal , Be careful 0 Followed by English letters o

  • Binary system :0b The switch expression represents binary . In binary expressions , Only numbers... Can be used 0 And 1

hex1 = 0x45
hex2 = 0x4Af
print("hex1Value: ", hex1)
print("hex2Value: ", hex2)
hex1Value: 69
hex2Value: 1199

2.2.2Python Numeric type conversion

  • int(x) take x Convert to an integer .

  • float(x) take x Converts to a floating point number .

  • complex(x) take x To a complex number , The real part is x , The imaginary part is 0 .

>>> a = 3.1415926
>>> int(a)
3
## Convert to a complex expression .
>>> complex(a)
(3.1415926+0j)

2.2.3 Values and expressions

‘/’ The result of division is a decimal , Floating point numbers

# Whether the operand is an integer or a floating point number , The result is always floating point numbers 
>>> 4.0 / 2
2.0
>>> 1 / 1
1.0

If you want to discard the decimal part , That is, perform an integer division operation , Double slashes can be used // .

# Whether the operand is an integer or a floating point number , The quotient obtained does not retain the mantissa of the floating-point number 
>>>4//2
2
>>>5.0//2
2.0

Seeking remainder ( modulus ) Operator ,x % y As the result of the x Divide y The remainder of

>>> 10 % 3
1
>>> 2.75 % 0.5
0.25
>>> 10 % -3
-2
>>> 10 // -3
-4

chengfang ( Exponentiation ) Operator . Please note that , The priority of the power operator is negative ( Monocular subtraction ) high , therefore -32 Equivalent to -(32) . If you want to calculate (-3)**2 , Must be specified in parentheses .

>>> -3 ** 2
-9
>>> (-3) ** 2
9

2.3Python character string

2.3.1 String linking and copying


# In operation two Integer or floating-point values , + Is the addition operator . however , When used with two strings , It will string Connect , Become “ String connection ” The operator .
>>> 'Alice' + 'Bob'
'AliceBob'
# If you use the plus operator on a string and an integer value ,Python I don't know how to deal with 
>>> 'Alice' + 42
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-5-4e9a9e71481a> in <module>
----> 1 'Alice' + 42
TypeError: can only concatenate str (not "int") to str
## When used with two integer or floating-point values ,* The operator represents multiplication . but * The operator is used for a string Value and an integer value , It became “ String copy ” The operator .
>>> 'Alice' * 5
'AliceAliceAliceAliceAlice'

2.3.2Python Access the value in the string

>>> var2 = "Runoob"
>>> print ("var2[1:5]: ", var2[1:5])
var2[1:5]: unoo
#in The usage of the keyword is similar to that of the operating system , Used to determine whether an element is in a list or string .
>>> if( "H" in a) :
>>> print("H In variables a in ")
>>> else :
>>> print("H Not in variable a in ")
H In variables a in
#not Keyword is used to negate 
>>> if( "M" not in a) :
>>> print("M Not in variable a in ")
>>> else :
>>> print("M In variables a in ")
M Not in variable a in

2.3.3Python String formatting

The usage is to insert a value into a string format character %s In the string of .

>>> " My name is %s, This year, %d year !" % (' Xiao Ming ', 10)
' My name is Xiao Ming , This year, 10 year !'

Python String formatting symbols :

  • %s : Formatted string ;

  • %d : Formatted integer ;

  • %f : Formatted floating point number , Precision after the decimal point can be specified ;

 Specify decimal precision
%m.nf
%.nf
m Represents the minimum width ,n Indicates output accuracy ,. Must exist .
f = 3.141592653
# Minimum width is 8, After the decimal point 3 position 
print("%8.3f" % f)
# Minimum width is 8, After the decimal point 3 position , Left complement 0
print("%08.3f" % f)
# Minimum width is 8, After the decimal point 3 position , Left complement 0, Signed 
print("%+08.3f" % f)

2.3.4 Single quote strings and escaping Quotes

Single and double quotes , Most of the cases are exactly the same

'Let's go!'
Report errors
# The backslash ( \ ) Escape Quotes 
'Let\'s go!'

2.3.5 Python Original string

Escaping characters can sometimes cause problems , For example, I would like to express an inclusion Windows route D:\Program Files\Python 3.8\python.exe Such a string , stay Python It must not be possible to write this directly in the program , Whether it's a normal string or a long string . because \ The particularity of , We need to look at each of the strings \ All of them are escaped , It's written as D:\Program Files\Python 3.8\python.exe This is the form .

Add... At the beginning of a normal or long string r Prefix , It becomes the original string , The specific format is :

str1 = r' Original string content '
str2 = r""" Original string content ""
rstr = r'D:\Program Files\Python 3.8\python.exe'
print(rstr)

2.3.6 Unicode character string

https://www.liaoxuefeng.com/wiki/1016959663602400/1017075323632896

Python There may be identifiers and strings in several languages in the program code to display 、 Output or comment . To store and display these different languages , Different countries and organizations have developed several character set standards . Common character sets are ASCII Character set 、 Simplified Chinese GB2312 Character set 、 Traditional Chinese Big5 Character set 、 Simplified Chinese GB18030 Character set 、Unicode Character set, etc. .

  • ASCII(American Standard Code for Information Interchange, American standard code for information exchange ) American National Standards Institute (American National Standard Institute,ANSI) A computer coding system based on the Latin alphabet ,ASCII Character set is the most common single byte encoding system nowadays , Equivalent to international standards ISO/IEC 646.
  • GB2312 and GB18030 The character set is a Chinese character coded character set formulated by China
  • Big5 Character set is the most commonly used computer Chinese character set standard in the traditional Chinese community
  • Unicode It's an industry standard in the field of computer science , Include character set 、 Coding scheme, etc .Unicode It is to solve the limitation of traditional character coding scheme , It sets a unified and unique binary code for each character in each language , To meet cross language needs 、 Cross platform text conversion 、 Handling requirements .

stay Python3 in , All strings are Unicode character string , stay Unicode There are many ways to put numbers 23383 Expressed as data in the program , Include UTF-8、UTF-16、UTF-32

In computer memory , Unified use Unicode code , When you need to save to a hard disk or need to transfer , Just switch to UTF-8 code .

[ 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-D05wg0Cx-1656062146825)(https://boostnote.io/api/teams/dlm1ZMj21/files/0971c779c2cf97bc40e136e29a66b04b029eb5ef84f40cae80904530464c4d1c-image.png)]

2.3.7 Python Three quotes

Python Three quotes allow a string to span multiple lines , String can contain line breaks 、 Tabs and other special characters

>>> para_str = """ This is an example of a multiline string >>> Multi line strings can use tabs >>> TAB ( \t ). >>> You can also use line breaks [ \n ]. >>> """
>>> print (para_str)

2.4 Python bytes Type and usage

bytes yes Python 3.x New type , stay Python 2.x There is no such thing as .

If you use the appropriate character set , A string can be converted to a byte string ; In turn, , The byte string can also be restored to the corresponding string .

# Using the string of encode() Method code into bytes, By default utf-8 Character set 
a= “ Study ”.encode(‘utf-8’)
# call bytes Object's decode() Method to decode it into a string 
st= a.decode(‘utf-8’)

2.5 Python bool Boolean type

  • True and False yes Python Keywords in , As Python Code input , Be sure to pay attention to the case of letters , Otherwise, the interpreter will report an error .
  • bool A type is used to represent the truth of something ( Yes ) Or false ( wrong ), If this thing is right , use True( or 1) representative ; If this thing is wrong , use False( or 0) representative .

2.6 Operator

2.6.1 Python Assignment operator

# Continuous assignment 
A=B=C=100
# The extended assignment operator 
x += y # Be similar to x = x + y
x -= y # Be similar to x = x - y

= and == Are two different operators ,= Used to assign , and == Used to judge whether the values on both sides are equal

2.6.2 Python Ternary operator ( Ternary operator )

exp1 if contion else exp2

condition It's the judgment condition ,exp1 and exp2 It's two expressions . If condition establish ( The result is true ), Is executed exp1, And put exp1 As the result of the entire expression ; If condition Don't set up ( The result is false ), Is executed exp2, And put exp2 As the result of the entire expression .

2.6.3Python Operator priority

Operator description Python Operator priority associativity parentheses ( )19 nothing index operator x[i] or x[i1: i2 [:i3]]18 Left Attribute access x.attribute17 Left chengfang **16 Right According to the not ~15 Right Symbolic operators +( Plus sign )、-( Minus sign )14 Right Multiplication and division *、/、//、%13 Left Addition and subtraction +、-12 Left Displacement >>、<<11 Left Bitwise AND &10 Right Bitwise XOR ^9 Left Press bit or |8 Left Comparison operator ==、!=、>、>=、<、<=7 Left is Operator is、is not6 Left in Operator in、not in5 Left Logic is not not4 Right Logic and and3 Left Logic or or2 Left The comma operator exp1, exp21 Left
4+4<<2
# Be similar to (4+4) << 2
  • Python Operator associativity

100 / 25 * 16,/ and * Same priority for , Which one should be executed first ?

The so-called Associativity , That is, when multiple operators with the same priority appear in an expression , Which operator to execute first : First execute the left one, which is called left associativity , First execute the on the right, which is called right associativity .


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