With the popularization of ARTIFICIAL intelligence technology, more and more front-end programmers began to pay attention to related technologies. Python, the most commonly used language in the field of artificial intelligence, and JavaScript, the language used daily by front-end programmers, belong to scripting languages. In the development process of the two languages, the community also learned from each other, so there are many similarities. A front-end programmer familiar with the JavaScript language can quickly pick up Python by learning the differences between them.
Here are some of the syntax points I recorded during my learning process that are different from JavaScript for easy reference.
Types and operations
- Boolean keywords are True and False
- The logical operation and, or, non-keyword is and or not
- A null value to None
- Exact division /; Take the exact division //
- Placeholder for formatting string (template like string) ‘%d % F % S %x’ % (1, 1.2, ‘AAA ‘, ‘0x16’)
- Conversions between types and Booleans: as long as
x
Non-zero value, non-empty string, non-empty list, etcTrue
, or forFalse
. - Strongly typed, different types cannot be compared, and an explicit conversion function is required
The code structure
- The colon and indentation represent blocks of code, and the amount of indentation is not specified
- Conditional judgment:
if a > b:
a++
elif:
b++
else:
c++
Copy the code
- The loop traversal number group uses for in
- Temporarily vacant blocks can be placeholder with the keyword pass
- Try block:
try:
print('try... ')
r = 10 / 0
print('result:', r)
except ZeroDivisionError as e:
print('except:', e)
finally:
print('finally... ')
print('END')
Copy the code
- Raise FooError(‘invalid value: %s’ %s)
The list and a tuple
-
Lists are divided into lists and tuples
-
Get list length len()
-
Datas [-1]; datas[-2];
-
List operation method:
Add datas.append(data) to end
Datas. insert(index, data)
Delete end: datas.pop()
Delete location: datas.pop(index)
-
The data types in lists can be different, just like in JavaScript
-
Tuples are immutable lists
-
Tuple definition :(1, 2, 3)
-
Tuple with only one element :(1.2,)
Dict and set
- Map-like types are called dict
- D [‘key’] error if key does not exist
- It can be checked by the ‘key’ in d operation
- D. set (‘key’) returns None if not present
- Dict removes elements with d.pop(‘key’)
- A dict key must be an immutable data type, such as a string or integer
- A set contains only non-repeating keys
- To create a set, supply a list as the input set: s = set(list), which automatically filters the repeating elements
- Set to increase the add (key)
- Set to delete the remove (key)
- The intersection and union operations of set s1 & s2; s1 | s2
Set operations
-
Slice: L[A: B: C] From a to B (left closed and right open, support reciprocal) take one for every C
-
Tuple and STR can also be sliced, resulting in the same type
-
For in Iteration dict is an iteration key by default
-
Iterating dict value: for value in d.values()
-
Dic key, value: for k, v in d.tems ()
-
Index loop: for I, value in enumerate([‘A’, ‘B’, ‘C’]):
-
For x, y in [(1, 1), (2, 4), (3, 9)]:
-
[x * x for x in range(1, 11) if x % 2 == 0], [m + n for m in ‘ABC’ for n in ‘XYZ’]
-
List generator: dynamically generates list elements, saving memory space
-
List generator creation mode
Change the [] outside the list generator to ()
Defining generator functions
-
Variable interchange: A, b = b, a
-
Iterable includes list, tuple, dict, set, and STR
-
The Iterator including the generator
-
Iterator is lazily evaluated
-
Iterable can be converted to Iterator using the iter() function
-
Both Iterable and Iterator can use for, and only Iterator can use next()
-
The return type of map() is Iterator
-
The reduce() callback takes two arguments, similar to the Fibonacci sequence, and returns the type of the list element
-
The sorted() function maps the original elements to sortable as the second named keyword argument
function
- The number and type of function parameters must be the same as defined; otherwise, an error will be reported
- Int () float() STR () bool()
- The function definitions
def abc(x):
return 0
Copy the code
-
The function can return multiple values, essentially forming a tuple
-
Default parameters can be defined in the form of power(x, n=2)
-
Enroll (‘Adam’, ‘M’, city=’Tianjin’) enroll(‘Adam’, ‘M’, city=’Tianjin’)
-
The default argument must point to an immutable object, otherwise there may be problems when the function is called multiple times and parameters are modified
-
Parameter type:
General parameters are called positional parameters, which indicate relationships by their positions in the parameter list.
The mutable argument definition function calc(*numbers) forms a tuple from multiple arguments passed in. When called, calc(*[1,2,3]) means that the list is passed in as a mutable argument.
Def person(name, age, **kw): calls person(‘Adam’, 45, gender=’M’, job=’Engineer’) to pass key/value pairs as dict;
Def person(name, age, *, city, job), must call person(‘Jack’, 24, city=’Beijing’, job=’Engineer’), If the function definition already has a mutable argument, the following named keyword argument does not need a special delimiter: Def person(name, age, *args, city, job): def person(name, age, *, city=’Beijing’, job):
-
The order must be mandatory, default, variable, named keyword, and keyword parameters
-
The anonymous function lambda x: x * x can have only one expression that does not require a return
-
The decorator @ can call higher-order functions to modify the function definition
-
The functools.partial function simply fixes some parameters of a function (that is, defaults) and returns a new function that is easier to call.
object-oriented
- Class Student(object):
- Constructor: def __init__(self):
- Instance variable name if
__
At the beginning, it becomes a private variable, accessible only internally, not externally - View type: type()
- Check inheritance: isinstance()
- Name = name; class attributes are written directly; class attributes are called directly by the instance. The class attributes are shared
- After you bind methods to objects, all instances are available
- The attributes that can be bound to an instance of a class are qualified by __slots__ = (‘name’, ‘age’)
- Accessors can be defined via decorators @property, @xxx.setter
- Class Dog(Mammal, RunnableMixIn, CarnivorousMixIn):
Package and module
- The directory must contain __init__.py, which is the module of the package
- The first string of any module code is treated as a documentation comment for the module;