Python Summary-1 general usage
2017-09-21
Common functions in Python
原创文章,转载请注明:转自Luozm's BlogThe Python summary series include common operations, functions and libraries related to Algorithm Design and Data Science.
1. Basic Syntax
- File type: Command line or scripts (.py), notebooks (.ipynb)
- Comment:
Comments are indicated by #
- E.g. # this line is a comment
- end of line:
The end of line is end of statement no ‘;’ needed
- E.g. x=5
- Semicolon:
Semicolon (;) can be used to separate statements on the same line
- E.g. x=5; y=8
- Printing:
Built-in print function
- print(x)
- print(“The value of x is equal to”, x)
- Variables & Objects:
Variables has no attached type information, everything is treated as an object
Objects has attributes and methods accessed by dot operator
- List.append(4)
- x.real()
1.1 Indentation
- Whitespace at the beginning is meaningful
- Code block: statements that should be treated as a unit
- Code blocks are preceded by a colon “:”
- Amount of indenting must be consistent in the code (typically 4 spaces)
if statement:
#code block, code without indentation will not be part of
while condition:
#code block
2. Operations
2.1 Arithmetic operations
Operator | Name | Description |
---|---|---|
a + b | Addition | Sum of a & b |
a - b | Subtraction | Difference of a & b |
a * b | Multiplication | Product of a & b |
a / b | True Division | Quotient of a & b |
a // b | Floor Division | Quotient of a & b, removing fractional parts |
a % b | Modulus | Reminder after division of a by b |
a ** b | Exponentiation | a raised to the power of b |
-a | Negation | The negative of a |
2.2 Comparison operations (return True or False)
Operator | Description |
---|---|
a == b | a equal to b |
a != b | a not equal to b |
a < b | a less than b |
a > b | a greater than b |
a <= b | a less than or equal to b |
a >= b | a greater than or equal to b |