1. Type conversion
(1) Conversion between integer and floating point types:
Integer -> Float: use float()
For example, the result of float(3) is 3.0, and the result of float('3.14') is 3.14;
Float -> integer: use int()
For example, the result of running int(3.14) is 3, and the result of int('3') is 3;
Note: float() can also convert a string whose content is a number into a floating-point type, while int() can only convert a string whose content is an integer into an integer, and use int() to convert it to an integer. The integer part of the floating-point type.
(2) When there is a mixed operation of integer and floating point, the operation result is floating point. Such as 3+6.0=9.0
(3) Rounding decimals
Use round() to achieve rounding, such as round(3.14) results in 3, round(3.95) results in 4.
2. Enhanced assignment operator
The explanations of operators such as +=, -=, *=, /= are as follows:
operator | example | equivalence |
+= | a+=1 | a=a+1 |
-= | a-=1 | a=a-1 |
*= | a*=2 | a=a*2 |
/= | a/=2 | a=a/2 |
//= | a//=2 | a=a//2 |
**= | a**=2 | a=a**2 |
%= | a%=2 | a=a%2 |
3. Boolean and related operations
There is no boolean value in python2, directly use the number 0 to represent False, and use the number 1 to represent True.
True and False are defined as keywords in python3, but their essence is still 1 and 0, and even digital operations can be performed.
(1) Comparison operators
Comparison operators return True and False for true and false
The following variables a=15, b=20:
operator | illustrate | example |
== | Compares the values of two objects for equality | (a==b) returns False |
!= | Compares whether the values of two objects are not equal | (a!=b) returns True |
> | Returns whether a is greater than b | (a>b) returns False |
< | returns whether a is less than b | (a<b) returns True |
>= | Returns whether a is greater than or equal to b | (a>=b) returns False |
<= | Returns whether a is less than or equal to b | (a<=b) returns True |
(2) Logical operators
operator | Format | illustrate |
or logical or |
x or y | Returns True if at least one of x or y is True Returns False if both x and y are False |
and logic and |
x and y | Returns True if both x and y are True Returns False if either x or y contains False |
not logical NOT |
not x | x is True, return False x is False, return True |