Python uses tabs or spaces to organize code structure instead of parentheses like R, C++, and Java.
It is recommended to use four spaces as the default indentation, and set the tab key to four spaces
In addition, multiple statements can be separated by semicolons:
a =5; b =6; c =7
In python, number, string, data structure, function, class, and module all have their own "box", which can be understood as Python object (object). All the following objects are directly referred to by object.
Use parentheses
result =f(x,y,z)
Unlike languages such as C++ and Java, object reference in Python does not have its own types. But you can check the type by type:
a =5type(a)
int
The type information is stored in the object itself.
Python can be regarded as a strong type, that is, every object has a clear type. So the following calculation will not hold. But Visual Basic will turn '5' into an integer (int), and JavaScript will turn 5 into a string (string)
'5'+5
TypeError Traceback (most recent call last)
in ()
----> 1 '5' + 5
TypeError: Can't convert 'int' object to str implicitly
However, there is an implicit conversion between int and float:
a =4.5
b =2print('a is {0}, b is {1}'.format(type(a),type(b)))
a is <class 'float'>, b is <class 'int'>
a / b
2.25
Because knowing the type of each Object is very important, we can use the isinstance
function to view the type of object
a =5isinstance(a, int)
True
Check whether a and b are int or float type
a=5;b=4.5
isinstance(a,(int, float))
True
isinstance(a,(int, float))
True
Attributes refer to some other python objects in the current object. Method refers to some functions of the current object that can access internal data in the object.
Through obj.attribute_name
you can view:
a='foo'
a.<Press Tab>
You can access attributes and methods through the getattr function:
getattr(a,'split')
In programming, duck typing (English: duck typing) is a style of dynamic typing. In this style, the effective semantics of an object is not determined by inheriting from a specific class or implementing a specific interface, but by the "collection of current methods and properties". The name of this concept comes from the duck test proposed by James Whitcomb Riley (see the "History" section below). The "duck test" can be expressed as follows:
"When you see a bird that walks like a duck, swims like a duck, and calls like a duck, then this bird can be called a duck."
In the duck type, the concern is not the type of the object itself, but how it is used.
For example, if an object can implement the iterative principle, then the object is iterable. We can see if this object has the magic method __iter__
. Or write an iter function yourself to detect:
def isiterable(obj):try:iter(obj)return True
except TypeError: # not iterable
return False
isiterable('a string')
True
isiterable([1,2,3])
True
isiterable(5)
False
This function is mostly used to write functions that can accept multiple types. For example, we write a function to receive any sequence (list, tuple, ndarray) or even an iterator. If the received is not a list, then we will artificially transform it into a list:
if not isinstance(x, list) and isiterable(x): #If x is not a list, and x is iterable
x =list(x) #Convert x to list
For example, I created a some_module.py file, which says:
# some_module.py PI =3.14159
def f(x):return x +2
def g(a, b):return a + b
Then in other files, there are multiple import methods:
# 1 import some_module
result = some_module.f(5)
pi = some_module.PI
# 2 from some_module import f, g, PI
result =g(5, PI)
# 3 import some_module as sm
from some_module import PI as pi, g as gf
r1 = sm.f(pi)
r2 =gf(6, pi)
Use is, and is not to check whether two references refer to the same object,
a =[1,2,3]
b = a
c =list(a)
a is b
True
a is not c
True
Because the list function in c = list(a)
creates a new list, c is a new list and does not point to the original a.
Another common method of is to check whether an instance is none:
a = None
a is None
True
In addition, like, +, -, ==, <=, &, |, etc. are also regarded as operators, this will not be discussed in detail, you can directly look at this link
In the python object, lists, dicts, NumPy arrays, and user-defined types (classes) can all be changed.
The string and tuple cannot be changed:
This type refers to None, str, bytes, float, bool, int
ival =123554
ival **6
3557466836753811461234217695296
fval =7.234
fval2 =5.43e-5
5 /2
2.5
# Take quotient
5 //2
2
# Take the remainder
5 %2
1
a ='one way of writing a string'
b ="another way"
c ="""
This is a longer string that
spans multiple lines
"""
c.count('\n') #There are three carriage returns
3
The string type is immutable:
a[10]='f'
TypeError Traceback (most recent call last)
in ()
1 a[10] = 'f'
TypeError: 'str' object does not support item assignment
Convert other types to strings:
a =5.6
s =str(a)
s
'5.6'
Because a string is a series of Unicode characters, it can be treated as a sequence, like lists and tuples:
s ='python'list(s)
[' p', 'y', 't', 'h', 'o', 'n']
s[:3]
' pyt'
Backslashes are used to specify special characters, such as carriage return\n
s ='12\\34'print(s)
12\34
You can use the prefix r to write the desired string format directly without having to enter a lot of backslashes:
s = r'this\has\no\special\characters'
# Actual s
s
' this\has\no\special\characters'
# Addition is used to concatenate two strings
s + s
' this\has\no\special\charactersthis\has\no\special\characters'
String template, or formatting, is a very important topic. String ojecjt has a format method:
template ='{0:.2f} {1:s} are worth US${2:d}'
template
'{0:.2 f} {1:s} are worth US${2:d}'
In this string:
{0:.2 f}
: The first parameter is of type float, with two decimal places
{1: s)
: change the second parameter to string type
{2: d)
: change the third parameter to an exact integer
template.format(4.5560,'Argentine Pesos',1)
'4.56 Argentine Pesos are worth US$1'
Recommended Posts