6 - 10 Python
6 - 10 Python
Link: https://towardsdatascience.com/100-helpful-python-tips-you-can-learn-before-finishing-your-morning-coffee-eb9c39e68958
Do you want to learn Python, SQL, Django, Machine Learning, Deep Learning, and Statistics in one-on-one
classes 🤔
Drop me a message on LinkedIn to discuss your requirements
[1, 4, 9, 16]
[1, 2, 3, 4]
2. range() includes a step parameter that may not be known that much
In [4]: for number in range(1, 10, 3):
print(number, end=" ")
# 1 4 7
1 4 7
def range_with_no_zero(number):
for i in range(number):
print(i, end=' ')
range_with_zero(3) # 0 1 2
range_with_no_zero(3) # 0 1 2
0 1 2 0 1 2
def get_first_element(my_list):
if len(my_list):
return my_list[0]
elements = [1, 2, 3, 4]
first_result = get_element_with_comparison(elements)
second_result = get_element_with_comparison(elements)
True
5. You can define the same method multiple times inside the same scope
However, only the last one is called, since it overrides previous ones.##
def get_address():
return "Third address"
Third address
6. You can access private properties even outside their intended scope
In [9]: class Engineer:
def __init__(self, name):
self.name = name
self.__starting_salary = 62000
dain = Engineer('Dain')
print(dain._Engineer__starting_salary) # 62000
62000
print(sys.getsizeof("bitcoin")) # 56
56
8. You can define a method that can be called with as many parameters as you
want
In [11]: def get_sum(*arguments):
result = 0
for i in arguments:
result += i
return result
print(get_sum(1, 2, 3)) # 6
print(get_sum(1, 2, 3, 4, 5)) # 15
print(get_sum(1, 2, 3, 4, 5, 6, 7)) # 28
6
15
28
9. You can call the parent class’s initializer using super() or parent class’s name
Calling the parent’s class initializer using super():
class Child(Parent):
def __init__(self, city, address, university):
super().__init__(city, address)
self.university = university
ETH Zürich
class Child(Parent):
def __init__(self, city, address, university):
Parent.__init__(self, city, address)
self.university = university
child = Child('Zürich', 'Rämistrasse 101', 'ETH Zürich')
print(child.university) # ETH Zürich
ETH Zürich
Note that calls to parent initializers using init() and super() can only be used inside the child class’s initializer.
10. You can redefine the “+” operator inside your own classes
Whenever you use the + operator between two int data types, then you are going to find their sum.
However, when you use it between two string data types, you are going to merge them:
11
firstsecond
2000
500
In [ ]: