View subclass.py
class Shape: | |
pass | |
class Rectangle(Shape): | |
def __init__(self, length, width): | |
self.length = length | |
self.width = width | |
self.area = length * width | |
def get_area(self): |
View fibo.py
def fibonacci(n): | |
assert n >= 0 and int(n) == n, 'Fibonacci number is defined for non-negative indices only!' | |
if n in [0,1]: | |
return n | |
else: | |
a,b = 0,1 | |
for _ in range(1,n): | |
c = a + b | |
a = b | |
b = c |
View fibo-recursion.py
def fibo(n): | |
assert n >= 0 and int(n) == n, 'Fibonacci number is defined for non-negative indices only!' | |
if n in [0,1]: | |
return n | |
else: | |
return fibo(n-1) + fibo(n-2) |
View factorial-recursion.py
def factorial(n): | |
assert n >= 0 and int(n) == n, 'Factorial function is defined for non-negative integers only!' | |
if n in [0,1]: | |
return 1 | |
else: | |
return n * factorial(n-1) |
View docstring.py
def sum_of_squares(nums): | |
""" | |
Compute the sum of squares of a list of numbers. | |
Args: | |
nums (`list` of `int` or `float`): A `list` of numbers. | |
Returns: | |
ans (`int` or `float`): Sum of squares of `nums`. | |
Raises: | |
AssertionError: If `nums` contain elements that are not floats nor ints. |
View for-else.py
def test(nums): | |
for i in nums: | |
if i == 0: # if the condition is satisfied, it hits break and the else block will not run | |
print('There is a 0.') | |
break | |
else: | |
print('There are no 0s.') | |
test([1,2,3,0]) # There is a 0. | |
test([1,2,3]) # There are no 0s. |
View decorator.py
def trace(func): | |
def print_in(*args, **kwargs): | |
print('Executing function', func.__name__) | |
return func(*args, **kwargs) | |
return print_in | |
@trace | |
def calc(a,b): | |
print(f'a+b is {a+b}, a-b is {a-b}.') |
View kwargs.py
def foo2(**kwargs): | |
print(type(kwargs)) | |
for keyword, value in kwargs.items(): | |
print(f'{keyword}={value}') | |
foo2(a=1, b=2, z='end') | |
# <class 'dict'> | |
# a=1 | |
# b=2 |
View args.py
def foo(*args): | |
print(type(args)) | |
for arg in args: | |
print(arg) | |
foo(1, 2, 'end') | |
# <class 'tuple'> | |
# 1 | |
# 2 |
View continue.py
for a in range(5): | |
if a == 2: | |
continue | |
print(a) | |
# 0 | |
# 1 | |
# 3 | |
# 4 |
NewerOlder