This article takes a look at the basic use of PYTHon3, assuming a JS base.
An overview of the
Python and js, is a dynamically typed language, do not need to compile, a semicolon is optional, the overall low entry barriers, the difference is the js grammar reference is Java, and Java from c, so the syntax of this series, and some features in python, such as expressed in the indentation code block, the variable is not need to declare, It’s a little weird.
There are other things to watch out for
- Single-line comments start with a pound sign. Multi-line comments are preceded by “” or “”.
# first comment # second comment # third comment # fourth comment """ "fifth comment # sixth comment """Copy the code
- Code blocks are represented by indentation, which should be consistent within the same code block, rather than curly braces, as is possible in other languages
if True:
print ("True")
else:
print ("False")
Copy the code
- Input, print
The data type
Python uses type(var) to get a data type, and returns
. You can also use isinstance(var,typename) to determine whether a data type is of a particular type, including subclasses.
print(type(1))//<class 'int'>
print(isinstance(True,int))//True
Copy the code
There are six types of data, the first three of which are immutable
Numeric types
By divided into
- int
- bool
- float
- Complex
Bool is a subclass of int, including True and False, 1 and 0, respectively
string
print(type('ee'))//<class 'str'>
Copy the code
tuples
Elements separated by commas in parentheses, an element must be followed by a comma like a string
print(type((2,)))//<class 'tuple'>
Copy the code
There are some other operations
Print (tuple[1:3]) print (tuple[2:]) print (tuple * 2) print (tuple + Tinytuple) # connect tuplesCopy the code
The list of
Similar to an array in JS, elements are separated by commas in brackets, and operate like tuples
print(type([2]))//<class 'list'>
Copy the code
A collection of
Like Set in JS, the elements are not repeated, separated by commas in braces, or you can convert strings to collections using Set (). Empty collections use the latter, because empty braces denote dictionaries
print(type({3}))//<class 'set'>
Copy the code
The following operations can occur between collections
Print (a - b) # a and b difference set print (a | b) # a and b and set the print (a & b) # at the intersection between a and b print (a ^ b) # do not exist at the same time of elements in a and bCopy the code
The dictionary
Similar to objects in JS, where key is immutable and unique
print(type({3:3}))//<class 'dict'>
Copy the code
The operator
Here is only the ones that need JS or others that need attention
Arithmetic operator
- // Take the exact division, the product is rounded down
Comparison operator
There is no === correlation
The assignment operator
No additional attention
An operator
No additional attention
Logical operator
And or not subtables are expressed as
- and
- or
- not
Member operator
Whether operand 1 is in operand 2 (string, list, or tuple)
- in
- not in
Identity operator
The address can be obtained by id(). This address is read-only
- is
- is not
statements
Conditional statements
No switch syntax
if condition_1:
statement_block_1
elif condition_2:
statement_block_2
else:
statement_block_3
Copy the code
Looping statements
Continue and break can be used in loop statements, similar to js
- while
While judge the condition: execute the statement......Copy the code
While with the else
while <expr>:
<statement(s)>
else:
<additional_statement(s)>
Copy the code
- For statement
for <variable> in <sequence>:
<statements>
else:
<statements>
Copy the code
You can use range() to traverse a sequence of numbers
Range (5)//0 to 4 range(5,9) //5 to 8 range(0, 10, 3) //0 to 9, step 3Copy the code
Iterators and generators
The iterator
Iterators are js iterators. You can use iter() to turn strings, lists, or tuples into iterators. You can use next for iteration or polling
List =[1,2,3,4] it = iter(list) print(next(it))//1 for I in it: print(I)//1 2 3 4Copy the code
The generator
A generator is a generator in JS, a function that returns an iterator, using yield
function
Functions start with def, the js equivalent of function, followed by the function name and argument.
Def function name (argument list) : function bodyCopy the code
Such as
Def printme(STR): # printme(STR): # printme(STR): # printme(STR) ) printme(" Call the same function again ")Copy the code
They can also be anonymous functions, lambda functions
lambda [arg1 [,arg2,.....argn]]:expression
Copy the code
Such as
Sum = lambda arg1, arg2: arg1 + arg2 ", sum( 20, 20 ))Copy the code
You can use default parameters, variable length parameters, etc
The module
You can use import Module1 [, module2[,… moduleN] to import the entire module or use from modname import name1[, name2[,… nameN]] to import a portion of the module
>>> fib(500) 1 1 23 5 8 13 21 34 55 89 144 233 377Copy the code
Or import all
The from... import *Copy the code
Namespaces and scopes
The namespace
There are three types of namespaces
- Local as in a function or class
- In the global module
- Built-in built-in contains language built-in names
scope
Scopes correspond to namespaces, where parts can be nested and divided into Local and Enclosing
- The local the innermost
- Enclosing local and global
- global
- build-in
Additional keywords are needed when modifying variables in an internal scope. Use the nonlocal keyword if the external scope is global, or if the external scope is enclosing the scope. If you don’t do this, you will create a new variable in the internal scope
o=2 print(o) # 2 def outer(): num = 10 print(num) # 10 def inner(): Num = 100 inner() global o o=3 print(num)# 100 outer() #3 print(o)Copy the code
class
Object orientation in python is class-based, similar to c++, which can contain properties or methods that are called directly when instantiated, not with new. The first argument in the method is self, representing the instance, and the constructor is __init__(). Private methods and properties begin with two underscores __
class ClassName:
<statement-1>
.
.
.
<statement-N>
Copy the code
Such as
Class MyClass: """ I = 12345 def f(self): Return 'hello world' # instantiate class x = MyClass() # instantiate class x = MyClass() # instantiate class x = MyClass() ", x.f())Copy the code
inheritance
Support multiple inheritance, you can inherit the method to rewrite
class DerivedClassName(Base1, Base2, Base3):
<statement-1>
.
.
.
<statement-N>
Copy the code
The end