In except blocks, the raise statement can be used without arguments to re-raise whatever exception occurred.
try:
num = 5 / 0
except:
print('An error occurred')
raise
The assert can take a second argument that is passed to the AssertionError raised if the assertion fails.
temp = -10
assert (temp >= 0), 'Colder than absolute zero!'
Test if writing to file was successfull:
file = open('filename.txt', 'w')
msg = 'My message!'
if file.write(msg) == len(msg):
print('File changed successfully.')
else:
print("file didn't change successfully.")
The file is automatically closed at the end of the with statement, even if exceptions occur within it.
with open('filename.txt') as f:
print(f.read())
If a negative value is used for the step, the slice is done backwards.
Using [::-1] as a slice is a common and idiomatic way to reverse a list.
lst = [1, 2, 3, 4, 5]
lst[::-1] # [5, 4, 3, 2, 1]
A list comprehension can also contain an if statement to enforce a condition on values in the list.
lst = [i for i in range(0, 10) if i % 2 == 0]
# [0, 2, 4, 6, 8]
String join:
"".join(['Hello ', 'world', '!'])
# 'Hello world!'
String join with function arguments instead of a list:
class String(str):
def my_join(self, *args):
return self.join(args)
s = String('')
# Python style:
s.join(['Hello ', 'world', '!'])
# My style:
s.my_join('Hello ', 'World', '!')
# both return: 'Hello world!'
# What if we have a list of strings and we want to join them using my style:
l = ['Hello ', 'world', '!']
s.my_join(*l)
# returns: 'Hello world!'
Often used in conditional statements, all and any take a list as an argument, and return True if all or any (respectively) of their arguments evaluate to True (and False otherwise).
The function enumerate can be used to iterate through the values and indices of a list simultaneously.
nums = [55, 44, 33, 22, 11]
if all([i > 5 for i in nums]):
print("All larger than 5")
if any([i % 2 == 0 for i in nums]):
print("At least one is even")
for v in enumerate(nums):
print(v)
# Output:
# (0, 55)
# (1, 44)
# (2, 33)
# (3, 22)
# (4, 11)
To find the maximum or minimum of some numbers or a list, you can use max or min.
To find the distance of a number from zero (its absolute value), use abs.
To round a number to a certain number of decimal places, use round.
To find the total of a list, use sum.
max([1, 4, 9, 2, 5, 6, 8]) # 9
min(1, 2, 3, 4, 0, 2, 1) # 0
abs(-99) # 99
round(1.6734, 2) # 1.67
sum([1, 2, 3, 4, 5]) # 15
Run a function n-times with an input
def run_n_times(func, times, inp):
if times == 0:
return None
for i in range(times):
inp = func(inp)
return inp
run_n_times(lambda x: x * x, 2, 2) # 16
Fibonachi numbers generator using dynamic programming approach
def fib_n(n=None):
'''
If no n is given, generates fibonachi numbers forever!
'''
nums = []
i = 0
while not n or i < n:
if i in {0, 1}:
nums.append(1)
else:
nums.append(nums[i - 1] + nums[i - 2])
yield nums[i]
i += 1
for n in fib_n(5):
print(n)
# 1
# 1
# 2
# 3
# 5
list(fib_n(5))
# [1, 1, 2, 3, 5]
Different models of creating class properties
class Animal:
def __init__(self, name):
self.name = name
name = property()
@name.getter
def name(self):
"""I'm the 'name' property."""
return self.__name
@name.setter
def name(self, value):
self.__name = value
@name.deleter
def name(self):
del self.__name
class Animal:
def __init__(self, name):
self.name = name
def __name_setter(self, value):
self.__name = value
def __name_getter(self):
return self.__name
name = property(__name_getter, __name_setter, doc="Animal's name proprty")
class Animal:
def __init__(self, name):
self.name = name
def __name():
doc = "Animal's name proprty"
def fget(self):
return self.__name
def fset(self, value):
self.__name = value
return locals()
name = property(**__name())
The Zen of Python
>>> import this
The Zen of Python, by Tim Peters
Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!
PEP 8 -- Style Guide for Python Code
Ternary Operator
status = 1
msg = "Logout" if status == 1 else "Login"
The else statement is most commonly used along with the if statement, but it can also follow a for or while loop, which gives it a different meaning. With the for or while loop, the code within it is called if the loop finishes normally (when a break statement does not cause an exit from the loop).
for i in range(10):
if i == 999:
break
else:
print("Unbroken 1")
for i in range(10):
if i == 5:
break
else:
print("Unbroken 2")
# Output:
#
# Unbroken 1
The else statement can also be used with try/except statements. In this case, the code within it is only executed if no error occurs in the try statement.
try:
print(1)
except ZeroDivisionError:
print(2)
else:
print(3)
try:
print(1/0)
except ZeroDivisionError:
print(4)
else:
print(5)
# Output:
#
# 1
# 3
# 4