DEV Community

loading...

Python 102! Introduction to Python : Intermediate Concepts.

Mwenda Harun Mbaabu
Software Engineer, Data Scientist and DevRel. Building Data Science East Africa, @DSEAfrica and Lux Tech Academy.
・4 min read

image

In the first part of python boot camp by Lux Academy and Data Science East Africa, we covered the basic python concepts, these included:

  • Python Installation and development environment set up.

  • Comments and statements in Python.

  • Variables in Python.

  • Keywords, identifiers and literals.

  • Operators in Python.

  • Comparison operators and conditions

  • Data types in Python

  • Control flow.

  • Functions in Python.

You can use this link to read more about the concepts if you have not yet read.

In this second part of the tutorial we are going to cover the intermediate python concepts, these includes:

  • Basics data structures, these lists, tuples, dictionary set.

  • Functions and recursion.

  • Anonymous or lambda function in Python.

  • Global, Local and Nonlocal.

  • 
Python Global Keyword.

  • 
Python Modules.

  • 
Python Package.

  • Classes in Python.

  • Closures and decorators

  • Inheritance and Encapsulation.

Basics data structures lists, tuples, dictionary set.

A data structure is a way of describing a certain way to organise pieces data so that operations and algorithms can be more easily applied, for example a tree type data structure often allows for efficient searching algorithms, so whenever you are implementing search component in your program it is advisable to use a tree data structure.

Basically, data structure in general computer science it is just a way of organising data to make certain operations easier or harder.

Questions: What is the difference between data types and data structures?

In layman’s language we can say data structures are specialised formats for organising and storing data in a program. Think of them as data with added structure.

In Python you can use the built-in types like list, sets, tuples, etc or define your own using classes and functions.

1) List - lists are ordered collection of items, you can create them using [ ] or list() constructor.

  • To access or edit values in a list use index or indices.
  • To add items use the append() method.
  • To remove items use remove or del statement.
# how to create a list.
todo = ['sleep', 'clean', 'sleep']

# how to access or edit a list items.
todo[0] = 'vacuum'

# how to add an items. 
todo.append('mow yard')

# how to remove an items
todo .remove('sleep')

Enter fullscreen mode Exit fullscreen mode

Tuples

Tuple are ordered collection of item like lists but immutable, that is unchangeable.

We create by providing comma separated values within optional () or use tuple() constructor. Once you have created a tuple you can not change it, that is you can not add, edit or remove any of the items in it.

# how to create a tuple 
student = ("freshman", 15, 4.0)

# how to access an item
print(student[0])

# how to access items
print(student[0:2])

# Hoe to delet a tuple
del student
Enter fullscreen mode Exit fullscreen mode

Dictionary.

Dictionaries are used to store data values in key:value pairs.

A dictionary is a collection which is ordered*, changeable and does not allow duplicates.

mycar = {
  "brand": "Ford",
  "model": "Mustang",
  "year": 1964
}
Enter fullscreen mode Exit fullscreen mode

Sets

Sets are used to store multiple items in a single variable, we can also define a set as a collection which is both unordered, unindexed and doesn’t support duplicates.

myset = {"apple", "banana", "cherry"}
print(myset)
Enter fullscreen mode Exit fullscreen mode

Function in Python.

A function is block of organised re-usable set of instructions that is used to perform some related actions.

For Example:

If you have 16 lines of code which appears 4 times in a program, you don't have to repeat it 4 times. You just write a function and call it.

Functions enables:

  • Re-userbility of code minimises redundancy.

  • Procedural decomposition makes things organised.

In python we have two types of functions:

1). User defined functions.

2). Built in functions.


def my_function(x):
    return list(dict.fromkeys(x))
    mylist = myfunction(["a", "b", "c", "d"])
    print(mylist)

my_function()
Enter fullscreen mode Exit fullscreen mode

 Parameters and arguments

A parameter is the variable defined within the parentheses during function definition. Simply they are written when we declare a function.

def sum(a,b):
  print(a+b)

# Here the values 1,2 are arguments
sum(1,2)
Enter fullscreen mode Exit fullscreen mode

An argument is a value that is passed to a function when it is called. It might be a variable, value or object passed to a function or method as input. They are written when we are calling the function.

def sum(a,b):
  print(a+b)

# Here the values 1,2 are arguments
sum(1,2)
Enter fullscreen mode Exit fullscreen mode

Decorator.

A decorator is a design pattern in Python that allows a user to add new functionality to an existing object without modifying its structure. Decorators are usually called before the definition of a function you want to decorate.

from fastapi import FastAPI

app = FastAPI()

#Here is the decorator 
@app.get("/")
async def root():
    return {"message": "Hello World"}
Enter fullscreen mode Exit fullscreen mode

Anonymous or lambda function in Python.

Lambda Function, also referred to as 'Anonymous function' is same as a regular python function but can be defined without a name. While normal functions are defined using the def keyword, anonymous functions are defined using the lambda keyword. However, they are restricted to single line of expression.


lambda arguments: expression 

Enter fullscreen mode Exit fullscreen mode

Lambda functions can have any number of arguments but only one expression. The expression is evaluated and returned. Lambda functions can be used wherever function objects are required.


double = lambda x: x * 2

print(double(5))

Enter fullscreen mode Exit fullscreen mode

Python Global, Local and Nonlocal variables.

In Python, a variable declared outside of the function or in global scope is known as a global variable. This means that a global variable can be accessed inside or outside of the function.

x = "global"

def foo():
    print("x inside:", x)


foo()
print("x outside:", x)
Enter fullscreen mode Exit fullscreen mode

A variable declared inside the function's body or in the local scope is known as a local variable

def foo():
    y = "local"


foo()
print(y)
Enter fullscreen mode Exit fullscreen mode

Nonlocal variables are used in nested functions whose local scope is not defined. This means that the variable can be neither in the local nor the global scope.

def outer():
    x = "local"

    def inner():
        nonlocal x
        x = "nonlocal"
        print("inner:", x)

    inner()
    print("outer:", x)


outer()
Enter fullscreen mode Exit fullscreen mode

Discussion (14)

Collapse
titusnjuguna profile image
Tito

A good piece

Collapse
grayhat profile image
Mwenda Harun Mbaabu Author

Thank you am glad you found it interesting

Collapse
cjsmocjsmo profile image
Charlie J Smotherman • Edited

A neat trick with sets

aset = [1,2,3,3,3,4,4,5]

list(set(aset))

Will give you

[1,2,3,4,5]

Collapse
grayhat profile image
Mwenda Harun Mbaabu Author

Thank you for adding this

Collapse
kubona_my profile image
kubona Martin Yafesi

Really great Article, I enjoyed it. Keep up.

Collapse
grayhat profile image
Mwenda Harun Mbaabu Author

Thank you for the feedback Martin.

Collapse
12944qwerty profile image
12944qwerty

I suggest that you add outputs as well to demonstrate what each idea would look like

Collapse
grayhat profile image
Mwenda Harun Mbaabu Author

Sure thank you for the feed back

Collapse
jefferson682 profile image
J. Jefferson N. do Vale

Excellent article. Congratulations

Collapse
grayhat profile image
Mwenda Harun Mbaabu Author

Thank you Jefferson

Collapse
ananddhruv295 profile image
Dhruv Anand

Nice work, this was really helpful.
Thanks for this. <3

Collapse
grayhat profile image
Mwenda Harun Mbaabu Author

Welcome, am glad it was helpful to you

Collapse
rukundob451 profile image
Benjamin Rukundo

Thanks for this indeed

Collapse
grayhat profile image
Mwenda Harun Mbaabu Author

Am glad you found it interesting