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

Python basic syntax

編輯:Python

List of articles

  • One 、python Basic grammar of
      • 1. Variables and variable types
        • 1.1 Composition of variables
        • 1.2 Memory model
        • 1.3 The type of variable
      • 2. identifier
      • 3. keyword
      • 4. Data type conversion
  • Two 、python Operator
      • 1. Arithmetic operator
      • 2. Assignment operator
      • 3. Comparison operator
      • 4. Logical operators
      • 5. member operator
      • 6. An operator
      • 7. Operator priority

One 、python Basic grammar of

1. Variables and variable types

1.1 Composition of variables

  • Variable name : Easy to find
  • A variable's value : What you actually want to store
  • Variable type : Limit what you can store

1.2 Memory model

  • Heap memory : Actual storage area
  • Stack memory : Storage area ( Limited information , Easy to find )

1.3 The type of variable

 Numerical type :
plastic ——》int
floating-point ——》float
The plural ——》complex
Non integer type :
String type ——》str
Boolean type ——》bool(Ture、False)
Complex type :
list ——》list
Tuples ——》turple
Dictionaries ——》dict

Demonstrate the definition and use of variables

# Demonstrate the definition and use of variables 
''' Three single quotes or triple double quotes can also be comments '''
a=1
print(type(a))
a="abc"
print(type(a))
a=1.7
print(type(a))
b=1+2j
print(type(b))
b=False
print(type(b))
c='dfsahaca:ajdsc'
print(type(c))
d='''sdcjs sdvj;s sdvj '''
print(type(d))
#print Result 
<class 'int'>
<class 'str'>
<class 'float'>
<class 'complex'>
<class 'bool'>
<class 'str'>
<class 'str'>

Demonstrate complex data types

arr=[1,2,3,4,5] #List The elements in can be changed 
print(type(arr))
print(arr[0]) #arr[0] On behalf of the first 
print(arr[2])
tpl=(1,"abc",1.56)
print(type(tpl)) #tuple The characteristic of tuples is that they can only be seen but not changed , Velocity ratio arr fast 
# Dictionary types usually use braces 
dic={
"name":"wangwu","age":18,"gender":' male '}
print(type(dic))
print(dic)
#print Result 
<class 'list'>
1
3
<class 'tuple'>
<class 'dict'>
{
'name': 'wangwu', 'age': 18, 'gender': ' male '}

2. identifier

If you want to represent something in a program , Developers need to customize some symbols and names , These symbols and names are called identifiers

  • The naming rules are as follows :
    ① Identifiers are made up of letters 、 Underline and numbers make up , And the number can't start , The first character must be a letter or underscore in the alphabet _
    ② Identifiers are case sensitive
    ③ Identifiers cannot use keywords

Example

name="zhangsan"
print(name)
aliyun=" Alibaba cloud "
print(aliyun)
a=0x1ab # Hexadecimal 
print(a)
_abab="123abc" # In large programs, underscores represent source programs , You can't change 
print(_abab)
zhangsan
Alibaba cloud
427
123abc

3. keyword

Keywords are identifiers with special functions

>>> help() # Enter the help system 
help> keywords # See all the keywords 
help> return # see return Description of this keyword 
help> quit # Exit the help system 

4. Data type conversion

The following built-in functions can perform conversion between data types , These functions return a new object , Represents the value of the transformation .

function describe int(x [,base]) take x Convert to an integer float(x) take x Converts to a floating point number complex(real [,imag]) Create a complex number str(x) Put the object x Convert to string repr(x) Put the object x Converts to an expression string eval(str) Used to calculate the validity in a string Python expression , And returns an object tuple(s) The sequence of s Converts to a tuple list(s) The sequence of s Convert to a list set(s) Convert to variable set dict(d) Create a dictionary ,d Must be a (key, value) Tuple sequence .frozenset(s) Convert to immutable set chr(x) Converts an integer to a character ord(x) Converts a character to its integer value hex(x) Convert an integer to a hexadecimal string oct(x) Converts an integer to an octal string

Example

result1=int(1.8) # This conversion takes only the integer part , The decimal part is discarded directly , No rounding 
print(result1)
result2=float(2)
print(result2)
#print give the result as follows 
1
2.0

Two 、python Operator

1. Arithmetic operator

Operator Related instructions + Add : Add two objects - reduce : A negative number or one number minus another * ride : Multiply two numbers or return a string that is repeated several times / except :a Divide b% Remainder : Returns the remainder of the Division ** power : return a Of b The next power // Divide and conquer : Returns the integer part of the quotient
# Show me arithmetic operators 
import math
a=7
b=2
print(a+b)
print(a-b)
print(a*b)
print(a/b)
print(a//b) #5/2...1
print(a%b)
print(a**b) #5 Of 2 Power 
print(b**a) #2 Of 5 Power 
print(math.sqrt(b)) # prescribing 
#print give the result as follows 
9
5
14
3.5
3
1
49
128
1.4142135623730951

2. Assignment operator

There is only one assignment operator , namely = , Its function is to assign the value to the right of the equal sign to the left , for example ,num=1+2

  • Assign the same value to multiple variables :x=y=z=1
  • Assign multiple values to multiple variables :a, b = 1,2
    ps: From right to left
Operator explain example = Simple assignment operators c = a + b take a + b The operation result of is assigned as c+= Addition assignment operator c += a Equivalent to c = c + a-= Subtraction assignment operator c -= a Equivalent to c = c - a*= Multiplication assignment operator c *= a Equivalent to c = c * a/= Division assignment operator c /= a Equivalent to c = c / a%= Modulo assignment operator c %= a Equivalent to c = c % a**= Power assignment operator c**= a Equivalent to c = c ** a//= Integer division assignment operator c //= a Equivalent to c = c // a

Example

a=5
b=2
c=3
a+=b
print(a)
a-=b
print(a)
c*=b
print(c)
c/=a
print(c)
c%=a
print(c)
a//=b
print(a)
a**=c
print(a)
#print result 
7
5
6
1.2
1.2
2
2.2973967099940698

3. Comparison operator

Operator explain == Check that the values of the two operands are equal != Check that the values of the two operands are not equal > Check whether the value of the left operand is greater than the value of the right operand < Check whether the value of the left operand is less than the value of the right operand >= Check whether the value of the left operand is greater than or equal to the value of the right operand <= Check whether the value of the left operand is less than or equal to the value of the right operand

Example

# Demonstrate the comparison operator 
a=5
b=6
print(a==b)
print(a!=b)
print(a<b)
print(a>b)
print(a>=b)
print(a<=b)
#print result 
False
True
True
False
False
True

4. Logical operators

Operator Logical expression describe andx and y Boolean " And " , If x by False,x and y return False, Otherwise it returns y Calculated value orx or y Boolean " or " , If x Right and wrong 0, It returns x Calculated value , Otherwise it returns y Calculated value notnot x Boolean " Not " , If x by True, return False . If x by False, It returns True
a=5
b=6
result1=a<=b
result2=a!=b
print(result1 and result2) # All two are true, So back true
print(result1 or result2) # If one of the two is right, it will return trun
print(not result1) #result1 That's right. , So back false
#print The results are as follows 
True
True
False

5. member operator

Operator describe example in Returns if a value is found in the specified sequence True, Otherwise return to Falsex stay y In sequence , If x stay y Return in sequence Truenot in If no value is found in the specified sequence, return True, Otherwise return to Falsex be not in y In sequence , If x be not in y Return in sequence True

Example

arr=[1,2,3,4,5,6]
print(1 in arr)
print(8 in arr)
#print result 
True
False
---------------------------------------------------------------------------------------------
arr=[1,2,3,4,5,6]
print(8 not in arr)
True

6. An operator

Bitwise operators calculate numbers as binary

Python The bitwise algorithm in is as follows :

# Variable a by 60,b by 13
a = 0011 1100
b = 0000 1101
a&b = 0000 1100
a|b = 0011 1101
a^b = 0011 0001
~a = 1100 0011
Operator describe example & Bitwise and operator : Two values involved in the operation , If both corresponding bits are 1, The result of this bit is 1, Otherwise 0(a & b) Output results 12 , Binary interpretation : 0000 1100| bitwise or operator : As long as one of the two corresponding binary bits is 1 when , The result bit is 1(a |b) Output results 61 , Binary interpretation : 0011 1101^ bitwise exclusive or operator : When two corresponding bits are different , The result is 1(a ^ b) Output results 49 , Binary interpretation : 0011 0001~ Bitwise negation operator : Invert each binary bit of data , Namely the 1 Turn into 0, hold 0 Turn into 1 .~x Be similar to -x-1(~a ) Output results -61 , Binary interpretation : 1100 0011, In the complement form of a signed binary number << Left move operator : All the binary bits of the operand are shifted to the left by several bits , from << The number on the right specifies the number of digits to move , High level discard , Low complement 0.a << 2 Output results 240 , Binary interpretation : 1111 0000>> Move right operator : hold ">>" Each binary of the left operand is shifted several bits to the right ,>> The number on the right specifies the number of digits to move a >> 2 Output results 15 , Binary interpretation : 0000 1111

Example

# Demo bit operation 
a=60
b=13
c=0
c=a&b
print(c)
c=a|b
print(c)
c=a^b
print(c)
c=~a
print(c)
c=a<<2 print(c) c=b>>2 print(c) #print result 12 61 49 -61 240
3
  • summary :

Move left : Equivalent to times 2
Move right : Equivalent to divided by 2
Bitwise AND : Binary bitwise judgment of two integers , All are 1 The result is 1
Press bit or : Binary bitwise judgment of two integers , All are 0 The result is 0
Bitwise XOR : Binary bitwise judgment of two integers , Different for 1, Same as 0( Same as false , Different is true )
According to the not : The binary bit negation of an integer , The sign bit will change . So the result is the inverse value minus the maximum value +1. You can use the original number directly +1, Change sign

7. Operator priority

All operators from highest to lowest priority are listed below :

Operator describe ** Index ( Highest priority )~ + - Flip by bit , One yuan plus sign and minus sign ( The last two methods are called [email protected] and [email protected])* / % // ride , except , Find the remainder and take the integral division + - addition and subtraction >> << Move right , Shift left operator & position ‘AND’^ | An operator <= < > >= Comparison operator == != Equals operator = %= /= //= -= += *= **= Assignment operator is is not Identity operator in not in member operator not and or Logical operators

Example

a=20
b=10
c=15
d=5
e=0
e = (a+b)*c/d #( 30 * 15 ) / 5
print("(a+b)*c/d The result of operation is :",e)
e = ((a+b)*c)/d #( 30 * 15 ) / 5
print("((a+b)*c)/d The result of operation is :",e)
e=(a+b)*(c/d) #(30)*(15/5)
print("(a+b)*(c/d) The result of operation is :",e)
e=a+(b*c)/d #(20)+(150/5)
print("a+(b*c)/d The result of operation is :",e)
# The result is as follows 
(a+b)*c/d The result of operation is : 90.0
((a+b)*c)/d The result of operation is : 90.0
(a+b)*(c/d) The result of operation is : 90.0
a+(b*c)/d The result of operation is : 50.0

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