变量作用域
只有模块(module),类(class)和函数(def、lambda)才会引入新的作用域,if/elif/else/、try/except、for/while 等语句则不会引入新的作用域,即外部可以访问在这些语句内定义的变量。
x = 3
for i in range(5):
x = 1
print(x) # 1
x = 7
def f():
global x
y = x
print(y) # 7
x = 2
f()
Operator
//
print(5//0.5) # 10.0
valid ways to declar complex numbers
z = 5 * 1j
print(type(z)) # <class 'complex'>
a = 1 + 5j
print(type(a)) # <class 'complex'>
b = complex(3)
print(type(b)) # <class 'complex'>
2 == 2.0 is True
is关键字
The is keyword is used to test if two variables refer to the same object.
The test returns True if the two objects are the same object.
The test returns False if they are not the same object, even if the two objects are 100% equal.
Use the == operator to test if two variables are equal.
x = ["apple", "banana", "cherry"]
y = ["apple", "banana", "cherry"]
print(x is y) # False
print(x == y) # True
y = x
print(x is y) # True
print(x == y) # True
Lambda
A lambda function is a small anonymous function.
A lambda function can take any number of arguments, but can only have one expression.
lambda arguments : expression
A = {
1,2,3,5,3,2,1}
print(type(A)) # <class 'set'>
print(A) # {1, 2, 3, 5}
print(list(filter(lambda x : x % 2 == 0, A))) # [2]
print(sum(list(filter(lambda x: x%2 == 0, A)))) # 2
Built in Functions
zip() Function
The zip() function returns a zip object, which is an iterator of tuples where the first item in each passed iterator is paired together, and then the second item in each passed iterator are paired together etc.
If the passed iterators have different lengths, the iterator with the least items decides the length of the new iterator.
filter() Function
The filter() function returns an iterator were the items are filtered through a function to test if the item is accepted or not.
ages = [5, 12, 18, 18, 24, 32]
def myFunc(x):
if x < 18:
return False
else:
return True
adults = filter(myFunc, ages)
print(list(adults))
int() Function
print(int('3')) # 3
print(type(int('3'))) # <class 'int'>
print(int(0.5)) # 0
print(int('4.0')) # ValueError: invalid literal for int() with base 10: '4.0'
print() Function
print(object(s), sep=separator, end=end, file=file, flush=flush)
Parameter | Description |
---|---|
object(s) | Any object, and as many as you like. Will be converted to string before printed |
sep=‘separator’ | Optional. Specify how to separate the objects, if there is more than one. Default is ’ ’ |
end=‘end’ | Optional. Specify what to print at the end. Default is ‘\n’ (line feed) |
file | Optional. An object with a write method. Default is sys.stdout |
flush | Optional. A Boolean, specifying if the output is flushed (True) or buffered (False). Default is False |
a = [0]
print(a) # [0]
b = [a]
print(b) # [[0]]
c = b[0]
print(c) # [0]
print(a, b, c) # [0] [[0]] [0]
round() Function
print(round(1234.5)) # 1234