Arithmetic operators
- + Addition
- - Subtraction
- * Multiplication
- / Division
- % Mod (the remainder after dividing)
- ** Exponentiation (note that ^ does not do this operation, as you might have seen in other languages)
- // Divides and rounds down to the nearest integer
Variables
Assign value
the following two are equivalent in terms of assignment
x = 3
y = 4
z = 5
and
x, y, z = 3, 4, 5
Reserved world in python
Pythonic way to name variables
YES
my_height = 58
my_lat = 40
my_long = 105
NO
my height = 58
MYLONG = 40
MyLat = 105
Varaibles and Assignment operator
a = 10
a = a + 10 -6
or
a += 10 - 6
Scientific notation
4.445e8 is equal to 4.445 * 10 ** 8 which is equal to 444500000.0.
Integers and Floats
浮点数创建直接在后面加上一个点就行
>>> print(10.)
10.0
或者
x = int(4.7) # x is now an integer 4
y = float(4) # y is now a float of 4.0
type function
查看是什么类型的
>>> print(type(10))
<class 'int'>
>>> print(type(10.0))
<class 'float'>
>>> print(type(int(10.0)))
<class 'int'>
>>> print(type(float(10)))
<class 'float'>
Floating Issues
>>> 0.1+0.1+0.1
0.30000000000000004
>>> print(.1 + .1 + .1 == .3)
False
Floating Point Arithmetic: Issues and Limitations小数部分不能完全表示为二进制分数
Boolean Comparison and Logical Operators
Strings
Strings in Python are shown as the variable type str. You can define a string with either double quotes " or single quotes '
>>> my_string = 'this is a string!'
>>> my_string2 = "this is also a string!!!"
operators of strings
len() function
len() is a built-in Python function that returns the length of an object, like a string. The length of a string is the number of characters in the string. This will always be an integer.
change type
such as
>>> age="22"
>>> print(int(age))
22
>>> print(type(int(age)))
<class 'int'>
String Methods
No professional has all the methods memorized, which is why understanding how to use documentation and find answers is so important. Gaining a strong grasp of the foundations of programming will allow you to use those foundations to use documentation to build so much more than someone who tries to memorize all the built-in methods in Python. (学会使用文档,而不是记住所有的这些方法)
You will find that the string method documentation is one of the most valuable resources for writing code, and not only when it comes to strings or writing code in Python!
Important string method
format()
》maria_string = "Maria loves {} and {}"
》print(maria_string.format("math","statistics"))
》Maria loves math and statistics
split()
string split document
This function or method returns a data container called a list that contains the words from the input string.
>>> '1,2,3'.split(',')
['1', '2', '3']
python code Style
PEP 8 -- Style Guide for Python Code
Whitespace
合理利用空格来编写清晰可读的代码