519722, 225 PM Essential Pytion Concepts & Structures Any Serious Programmer Needs to Know, Explained | by Andre Ye | Towards Data Science
Open in app
You have 2 free member-only stories left this month. Sign up for Medium and get an extra one
é Andre Ye
J
Apr 30, 2020 - 6 minread * - Qtisten
[save
‘Source: Pixabay
Essential Python Concepts & Structures Any
Caviane Dranrammar Mande ta Kuna
.
hitps:/towardsdatascience.com/essential-pythor-concepts-any-serous-programmer-nesds-1o-know-sxplained-420aad86692¢ ne519722, 225 PM Essential Pytion Concepts & Structures Any Serious Programmer Needs to Know, Explained | by Andre Ye | Towards Data Science
Open in app te
ing Medium,
VSHTAWID, VUJSLE jpojucin)
More
ium log user data, By
Fy WEUUIAWID, &
This article will outline some essential Python concepts that any serious programmer
should know and understand to implement. These concepts form a framework of
advanced Python programming to approach and implement problems intelligently.
Generators
Building an iterator, an object that can be iterated upon, in Python is a lot of work. A
class (object-oriented programming) must be built with
an _iter_() and _next__«) methods, internal states must be stored and updated,
and a stoptteration error must be raised when there is no value to be returned.
For item
Do something
Iterations in Python. Image created by author,
To avoid this lengthy process, Python generates can automatically create iterators. All
the processes described above to create an iterator are automatically done by Python
with generators. A generator is a function that returns an object (iterator) which can
be iterated (covered one value at a time).
A generator function is defined as a function, but uses the yicid keyword instead of
the traditional return . If the body of a function contains yieid , then itis
i Q
hitpsiltowardsdatascience.com/essential-pythor-concepts-any-serous-programmer-nesds-o-know-sxplained-420aad80b978 ana519722, 225 PM Essential Pytion Concepts & Structures Any Serious Programmer Needs to Know, Explained | by Andre Ye | Towards Daa Science
Open in app
yield 2
yield 3
for value in simple generator ():
print (value)
The first four lines of code define the generator, which will iteratively return 1, 2,
and 3, The last two lines demonstrate the iteration by iteratively printing out values,
outputting:
A generator object would still require a function to outline the object, but needs to be
set equal to a variable, in this case x.
x = simple_generator ()
print (next (x) )
print (next (x))
print (next (x)
For example, the following code creates a Fibonacci sequence generator, where each
term is the sum of the two preceding terms (0, 1, 1, 2, 3, 5, 8,13, «).
def fibonacei (1i
a, b= 0, 1
it)
while a < limit:
yield a
a, b= b, atb
tl Q
hitpsiltowardsdatascience.com/essential-pythor-concepts-any-serous-programmer-nesds-t-know-explained-420aad80b978 ana519722, 225 PM Essential Pytion Concepts & Structures Any Serious Programmer Needs to Know, Explained | by Andre Ye | Towards Data Science
Open in app te
parameter in the funct ae
Then, » and » are updated simultaneously, where « is set to » and » is set to itself
log user data, By
ing Medium, » our Privacy Poll
ue of a.
plus a. This shifts the sequence one to the right while keeping relevant information
for generating the next sequence value (the previous two numbers).
initialization
repeat per
iteration
Fibonacci sequence generator logic. Image created by author.
‘The generator can then be iterated over, in this case with a for-loop:
for i in fibonacci (8):
print (i)
The output will hence iterate across all elements of the Fibonacci sequence under the
value of 8:
i Q
hitpsiltowardsdatascience.com/essential-pythor-concepts-any-serous-programmer-nesds-to-know-explained-420aad80b978 ana519722, 225 PM Essential Pytion Concepts & Structures Any Serious Programmer Needs to Know, Explained | by Andre Ye | Towards Data Science
Open in app
Object-Oriented Programming
Object-Oriented Programming is a feature of Python that allows for clean and
organized storage of methods and variables. Object-Oriented Programming (OOP) in
Python consists of ciass objects, which contain information about that object.
For example, say we want to create a virtual dog in Python. A class’ personal attributes
are stored ina _init__ function. The ses parameter must be included, and any
other attributes of that object that need to be defined upon creation, such as the
dog’s species and age.
class do:
def in
The object's variables and functions can be called inside the <1as> object with . , with
the preceding element referencing the object and the item after the period referencing
the object being called, se1s.species = species sets the internal variable to whatever
the input parameter species is.
We can also create functions in the class:
class dog:
def
hitpsiltowardsdatascience.com/essential-pythor-concepts-any-serous-programmer-nesds-o-know-sxplained-420aad80b978 ez519722, 225 PM Essential Pytion Concepts & Structures Any Serious Programmer Needs to Know, Explained | by Andre Ye | Towards Data Science
.dium work, we log user data, By
Open inane (cetsians Pe voain vor wolog sr a
These two internal functions, »ark and reveal information , are methods performed
and attached by the class. We can then set a variable, pepper , to the dog class. We
must specify initialization parameters, species and ase.
pepper = dog(species='German Shepard",
Then, we can call sepper’s attributes:
pepper. reveal_information()
This will output:
I am a German Shepard
I am 3 years old
hitpsitowardsdatascience.com/essential-pythor-concepts-any-serous-programmer-nesds-o-know-sxplained-420aad80b978 en2519722, 225 PM Essential Pytion Concepts & Structures Any Serious Programmer Needs to Know, Explained | by Andre Ye | Towards Data Science
pen in app C aig TO make Medlum work, we log user data, By
ng Medium, you agree to our Privacy Pol
Object-Oriented Progr incising cookie policy urposes. Even though it
may take some more typing to set up, it allows for much more readable code.
Closure
Closures can avoid the use of global values and provides a form of data hiding,
providing an object-oriented solution to the problem. When there are few methods to
be implemented in a class, closures can provide an alternate and more elegant
solution. When the number of attributes and methods grow larger, a class is more
fitting. The following criteria demonstrate closure in Python when a nested function
references a value in its enclosing scope:
There exists a nested function (a function inside a function)
The nested function refers to a value declared in the enclosing function
* The enclosing function returns the nested function
ate function f with n
Return function f
create function creator instance
Closure diagram. Image created by author.
Tat’c demanctrata elacnra with an evamnle fimotian asia mteinriae whieh take ina
tl Q
hitpsiltowardsdatascience.com/essential-pythor-concepts-any-serous-programmer-nesds-o-know-sxplained-420aad80b978 m2519722, 225 PM Essential Pytion Concepts & Structures Any Serious Programmer Needs to Know, Explained | by Andre Ye | Towards Data Science
Open in app
return x
return mult
Creating a function that multiplies something by 3 would be done like this:
times3 = make_multiplier (3)
Because the function maxe_muitip: returns a function, times3 is a function.
pri mes3 (9) )
-.returms...
..because 3 times 9 is 27. Closure is probably the best way to accomplish this task in
Python.
Built-In Enumeration
Python’s built-in enumeration is awesome. Perhaps the most often task a developer
faces is iterating through an item in a list while keeping track of an index. In many
other languages without enumeration, the programmer would need to do this
manually, for example in Python here:
hitpsiltowardsdatascience.com/essential-pythor-concepts-any-serous-programmer-nesds-t-know-explained-420aad80b978 ana519722, 225 PM Essential Pytion Concepts & Structures Any Serious Programmer Needs to Know, Explained | by Andre Ye | Towards Daa Science
Open in app
However, Python’s enunezate() function automatically keeps track of the counter with
each iteration by returning an unpackable tuple:
for index, item in enumer
do_something_with (item)
do_ something with (index)
(a_list):
As a demonstration, the following code...
for index, item in enumer:
print (index, item)
(tat, tbt,tet}):
...would output...
Decorators
Decorators take in a function, adds some functionality to the function, and returns it.
‘This is very helpful in cases where small variations of a parent function are needed
because the function can be varied and changed with a decorator instead of being
rewritten for each variation of the function that is needed.
Say we have a function oreinary«) whose sole purpose is to print out a string *: an
ordinary function.”
hitpsiltowardsdatascience.com/essential-pythor-concepts-any-serous-programmer-nesds-t-know-explained-420aad80b978 ona519722, 225 PM Essential Pytion Concepts & Structures Any Serious Programmer Needs to Know, Explained | by Andre Ye | Towards Data Science
Open in app
Say we would also like to add another message, ~: » We may create a
function decorate() that takes in a function, print the addition message, and then call
the original function, whose object is inputted as a parameter in
thefunction cecorate() . The process of adding an additional string and calling the
original function can be stored in an inner function, whose object is returned
with decorate () .
def decorate (function) :
inner_function ()
print ("I was decorated!
function ()
rn inner_function
‘To decorate the original function orainary() , we would call the
function cecoratet) on the original function. The variable we store the output
a in the function decorate.) ).
of decorate’) to, decorated, is a function (inner
decorated = decorate (ordinary)
decorated (}
Calling decoratea() yields the output...
s decorated!
am an ordinary function.
Decorators use the e symbol to automatically decorate a function.
tl Q
hitpsiltowardsdatascience.com/essential-pythor-concepts-any-serous-programmer-nesds-o-know-sxplained-420aad0b978 sore519722, 225 PM Essential Pytion Concepts & Structures Any Serious Programmer Needs to Know, Explained | by Andre Ye | Towards Data Science
Open in app
Using the ¢ symbol abo o. cse cece Ge esas weeeesnsdttically decorates the
function. It is computed the same way as the earlier outlined method to decorate a
function.
Multiple decorators can be chained on top of each other by adding several lines
of adecorate before a function.
Thanks for reading!
Ifyou have any questions about the code samples or concepts, do not hesitate to ask in
the responses below.
Sign up for The Variable
By Towards Data Science
Every Thursday, the Variable delivers the very best of Towards Data Science: from hands-on tutorials,
and cutting-edge research to original features you don't want to miss, Take a look,
(C cunisnensoe)
hitpsiltowardsdatascience.com/essential-pythor-concepts-any-serous-programmer-nesds-to-know-sxplained-420aad80b978 we519722, 225 PM Essential Pytion Concepts & Structures Any Serious Programmer Needs to Know, Explained | by Andre Ye | Towards Data Science
Cox
Wl iv awen tl il
Open in app
Cee ee
hitpsiitowardsdatascience.com/essental-pythor-concepts-any-serous-programmer-nesds-t-know-sxplained-420aad86b926 wane