Basic Python
WIP (Work in Progress) In this post, I will share some of the Python programming
The Zen of Python
by Tim Peters
import this
- 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!
__main__
__init__
decorators
Decorators is a function where we want to decorate a function without changing the original function
def dev(a,b):
return a/b
dev(2,4)
Result
0.5
Let say we want to execute above function and want to alter the function or add another into the original function, we use decorator
def smart_dev(func):
def inner_function(a,b):
if a<b:
a,b = b,a
return func(a,b)
return inner_function
@smart_dev
def dev(a,b):
return a/b
dev(2,4)
Result
2
https://www.youtube.com/watch?v=FsAPt_9Bf3U
Class and object
Why Class in Python?
To group the data and function for easy to use and build upon
Object is the subset of the class. The object is created by the defined object Class Example:
class Class_Name:
def __init__(self, att_1, att_2, att_3):
self.att_1 = att_1
self.att_2 = att_2
self.att_3 = att_3
def function_class(self):
print(self.att_1)
Method
Method is the function associated with the class
Add self
to each of the method of the class Class_Name
def function_class(self):
Constructor
The custome constructor like example below is how to define the attributes in more efficient way
def __init__(self, att_1, att_2, att_3):
Therefore to run the example of the Class
above
variable1 = Class_Name(att_1, att_2, att_3)
String formatting
There are multiple ways on how you can do string-formatting Let say we have an output like this
My name is Ahmad and I am 20 years old.
Example
person = {'name': 'Ahmad', 'age': 20}
sentence = 'My name is ' + person['name'] + ' and I am ' + str(person['age']) + ' years old.'
On the example above, you need to convert the integer to string due to error TypeError: can only concatenate str (not "int") to str
You could refer to the date time format based on official documentation of Python datetime library
import datetime
my_date = datetime.datetime(2016, 9, 24, 12, 30, 45)
sentence = '{0:%B %d, %Y} fell on a {2:%d} and was the {1:%y} day of the year'.format(my_date, my_date, my_date)
On the example above you can either add 0
at the beginning of the :%B %d, %Y
or you put the 3 placeholders but provide only a value to the format
.
Therefore you can either put 3 values in the format
or assign only one value to the format
and add 0:
.
str() and repr()
str should be readable repr should be unambigious
Namedtuple
To increase the readability of the tuple
from collections import namedtuple
argparse
Argparse is used to parse python scripts parameters
import argparse
if __name__ = '__main__':
# Initialize parser
parser = argparse.ArgumentParser()
parser.add_argument('')
# Add the additional parameter and add the parser
args = parser.parse_args()