Python table of content




Subscribe To Our Newsletter
You will receive our latest post and tutorial.
Thank you for subscribing!

required
required


Python – Function

A function is a group of related statements or commands that performs a specific task. Functions help break our program into smaller and modular chunks. As our program grows larger and larger, functions make it more organized and manageable. It avoids repetition and makes the code reusable. It only runs when it is called.

Syntax

def function_name(parameters):
    statements

You can pass data, known as parameters, into a function. The terms parameter and argument can be used for the same thing: information that are passed into a function. A parameter is the variable listed inside the parentheses in the function definition. An argument is the value that is sent to the function when it is called. By default, a function must be called with the correct number of arguments. Meaning that if your function expects 2 arguments, you have to call the function with 2 arguments, not more, and not less.

A function can return data as a result.

def function_name(parameters):
    statements
    return value;

Arbitrary Arguments with *args

If you do not know how many arguments that will be passed into your function, add a * before the parameter name in the function definition. This way the function will receive a tuple of arguments, and can access the items accordingly

def print_profile(*profile):
    print(f'name: {profile[0]}, age: {profile[1]}')

print_profile("Folau", 30)

You can also send arguments with the key = value syntax. This way the order of the arguments does not matter.

def say_hi(name):
    print(f'Hi {name}')

say_hi(name="Folau")

Arbitrary Keyword Arguments with **

If you do not know how many keyword arguments that will be passed into your function, add two asterisk: ** before the parameter name in the function definition. This way the function will receive a dictionary of arguments, and can access the items accordingly

def print_user(**user):
    print(f'name: {user["name"]}, age: {user["age"]}')

 

How to call a function?

Once we have defined a function, we can call it from another function, program or even the Python prompt. To call a function, use the function name followed by parenthesis

def say_hi(name):
    print(f'hi {name}')

say_hi('Folau')

The pass statement

function definitions cannot be empty, but if you for some reason have a function definition with no content, put in the pass statement to avoid getting an error.

def say_hi():
   pass

 

Lambda

Lambda is an anonymous function that is defined without a name. Lambda functions are defined using the lambda keyword. A lambda function can take any number of arguments, but can only have one expression.

Syntax

lambda arguments: expression

The expression is evaluated and returned. Lambda functions can be used wherever function objects are required.

doubleNumber = lambda num : num * 2

multiply = lambda num1, num2 : num1 * num2


# Lambda function
doubledNum = doubleNumber(3);
print(doubledNum) # 6

# Lambda function
result = multiply(3,3);
print(result)# 9

Uses of Lambda

We use lambda functions when we require a nameless function for a short period of time. We generally use it as an argument to a higher-order function (a function that takes in other functions as arguments). Lambda functions are used along with built-in functions like filter()map() etc.

numbers = [1,2,3,4,5,6]
new_numbers = list(filter(lambda x: (x%2==0), numbers))
print(f'{new_numbers}') #[2, 4, 6]

 

Module

Modules refer to a file containing Python statements and definitions. A file containing Python code, for example: user.py, is called a module, and its module name would be user. We use modules to break down large programs into small manageable and organized files. Furthermore, modules provide reusability of code. We can define our most used functions in a module and import it, instead of copying their definitions into different programs.

How to use a module?

We can import the definitions inside a module to another module or the interactive interpreter in Python. We use the import keyword to do this. To import our previously defined module user, we type the following in the Python prompt. Using the module name we can access the function using the dot . operator

import user

user.say_hi()

Python has tons of standard modules. You can check out the full list of Python standard modules and their use cases. These files are in the Lib directory inside the location where you installed Python.

Import but rename or give it alias

import user as u

from module import statement

# just one function
from user import say_hi

# import all functions
from user import *

Source code on Github

March 8, 2021

Python – Iteration(for/while loops)

For Loop

for loop is used for iterating over a sequence which can be a list, tuple, dictionary, set, or a string. Iterating is also known as traversing. Loop continues until we reach the last item in the sequence. The body of for loop is separated from the rest of the code using indentation.

Syntax

for val in sequence:
    # do something with val

Example

# list
numbers = range(1,10, 2)

for number in numbers:
    print(number)

# string
message = "Hello World"

for character in message:
    print(f'char: {character}')

# tuple
""" id, person info """
person = tuple(('12345',{"name":"Folau","grade":"3.5"}))
for p in person:
    print(p)

# set
names = set(('Folau','Lisa','Mele'))

for name in names:
    print(name)

#dictionary
profile = dict(name="Folau",age=30,job="SWE")
for attr in profile:
    print(attr)

 

The for loop does not require an indexing variable to set beforehand.

With the break statement we can stop the loop before it has looped through all the items. The example below stops its execution when count is 3.

numbers = range(1,10, 2)

count = 0;
for number in numbers:
    print(number)
    if count == 3:
       break
    count++

With the continue statement we can stop the current iteration of the loop, and continue with the next. The example below shows that when number is 0 the program will throw an error but instead of terminating the program it should keep going til the end of the list.

numbers = range(1,10, 2)

for number in numbers:
    print(number)
    try:
      result = 12 / number
    except:
      continue

 

for loops cannot be empty, but if you for some reason have a for loop with no content, put in the pass statement to avoid getting an error.

numbers = range(1,10, 2)

for number in numbers:
    pass

else statement with for loop

We can use else statement with for loop to execute some code when the for loop is finished. It’s useful in logging or sending a notification when the processing of a sequence is successfully completed.

teams = ['Lakers','Jazz','Suns']
for team in teams:
    print(team)
else:
    print("done looping through teams")

Reverse iteration using reversed function

The for loop iterates through the sequence elements in the order of its occurrence. Sometimes we have to iterate through the elements in the reverse order. We can use reversed() function with the for loop to achieve this.

numbers = (1, 2, 3, 4, 5)

for num in reversed(numbers):
    print(num)

 

While Loop

while loop is used to repeat a block of code until the specified condition is False. It is used when we don’t know the number of times the code block has to execute. We should take proper care in writing while loop condition if the condition never returns False, the while loop will go into the infinite loop. Every object in Python has a boolean value. If the value is 0 or None, then the boolean value is False. Otherwise, the boolean value is True. We can define an object boolean value by implementing __bool__() function. We use the  reserved keyword  – while – to implement the while loop in Python. We can terminate the while loop using the break statement. We can use continue statement inside while loop to skip the code block execution. Python supports nested while loops.

Syntax

while condition:
    # while body
else:
    # else body

Example

count = 0
while count < 10:
    print(count)
    count+=1
else:
    print("done counting!")

Python for loop and while loops are enough to create any type of loops. We can use the break and continue statements to control the loop execution flow. You can also use the “else” block for logging successful execution of the loops.

 

Source code on Github

March 8, 2021

Python – Introduction

What is Python?

Python is a powerful general-purpose programming language. It is used in web development, data science, Machine Learning applications, creating software prototypes, and so on. Fortunately for beginners, Python has simple easy-to-use syntax. This makes Python an excellent language to learn to program for beginners. Python is a cross-platform programming language, which means that it can run on multiple platforms like Windows, macOS, Linux, and has even been ported to the Java and .NET virtual machines. It is an open source, object-oriented, high-level powerful programming language. If you come from a language like Java you will be able to feel at home. 

Even though most of today’s Linux and Mac have Python pre-installed in it, the version might be out-of-date. So, it is always a good idea to install the most current version.

Facts about Python Programming Language:

  1. Python is currently the most widely used multi-purpose, high-level programming language.
  2. Python allows programming in Object-Oriented and Procedural paradigms.
  3. Python programs generally are smaller than other programming languages like Java. Programmers have to type relatively less and indentation requirement of the language, makes them readable all the time.
  4. Python language is being used by almost all tech-giant companies like – Google, Amazon, Facebook, Instagram, Dropbox, Uber… etc.
  5. The biggest strength of Python is huge collection of standard library which can be used for the following:
    •  Machine Learning 
    • GUI Applications (like  Kivy , Tkinter, PyQt etc. )
    • Web frameworks like Django (used by YouTube, Instagram, Dropbox) and Flask (used by Netflix)
    • Image processing (like  OpenCV , Pillow)
    • Web scraping (like Scrapy, BeautifulSoup, Selenium)
    • Test frameworks
    • Multimedia
    • Scientific computing
    • Text processing and many more..

Before we start Python programming, we need to have an interpreter to interpret and run our programs. If you have python installed you have an interpreter.

First Python program

print("Hello World!")

# console
Hello World!

As you can see above, it is so much easier to get started with python than any other language like Java, C++, etc.

 

Why should you learn python?

python and programming in general – is in such high demand because it is useful in just about every industry. Python is used by companies in recruiting, healthcare, financial services, marketing, education and many more.

Python is great for quick prototyping, hence is used extensively by startups to build their first minimum viable product (MVP). It is also highly scalable for medium to big applications.

According to iDataLabs 67% of the companies that use Python are small (<$50M in revenue), 9% are medium-sized ($50M – $1000M in revenue) and 17% are large (>$1000M in revenue).

Companies that use python

Python is the fastest growing programming language

Given Python’s uses across many industries and applications – and its recent explosive use in data science, machine learning and AI, Python is on a major growth trajectory. Stackoverflow.com shows Python as the fastest growing major programming language by a long-shot, by analyzing the number of visitors vs. questions about a certain topic.

Python is in high demand for jobs

Going hand-in-hand with lightning speed growth, Python programming is in high demand for jobs. Based on the number of job postings on one of the largest job search platforms, LinkedIn.com, Python ranks #2 in the most in-demand programming languages of 2020.

Python is easy to read, write, and learn

Python was built with the goal of getting rid of the complex and keeping only the necessary. Because of this, Python is easier to read, write, and learn than most other major programming languages.

Other languages like Java and C++ have some kind of a steep set up for a simple program to run. Python has a simple and easy way to get you set up and start coding in a matter of a few seconds.

Python is also an interpreted programming language. This means that unlike compiled languages like C++ or Java, you can run each line of code as soon as you finish writing it and see the results immediately. This is especially great for new programmers because you can get instantaneous feedback instead of waiting for the whole program to compile and run before you figure out that you forgot one character somewhere!

Python developers make great money

Python developers are some of the highest paid developers in the market, particularly in data science, machine learning and web development.

Python has a great community

One of the greatest tools a programmer will ever have is the support of their community. Thanks to online forums, local meet-ups, and the open source community, programmers continue to learn from and build on the success of their predecessors.

Stack Overflow is a programming question and answer platform critical for all developers when they are stuck, or wanting to share wisdom with the community. On Stack Overflow, Python is tagged in more than one million questions, demonstrating incredibly robust and active community for current and aspiring Python developers. GitHub is where developers store project code and collaborate with other developers. With over 1.5M repositories on GitHub and over 90,000 users committing or creating issues in these repositories, Python has the second largest GitHub community.

March 8, 2021

Python – Conditional Statements

Decision making is required when we want to execute a code only if a certain condition is satisfied. if statement is the most simple decision making statement. It is used to decide whether a certain statement or block of statements will be executed or not i.e if a certain condition is true then a block of statement is executed otherwise not.

  • Equals: a == b
  • Not Equals: a != b
  • Less than: a < b
  • Less than or equal to: a <= b
  • Greater than: a > b
  • Greater than or equal to: a >= b

A program evaluates anexpression and will execute statement(s) only if the expression is True. If the expression is False, the statement(s) is not executed.

In Python, the body of the if statement is indicated by the indentation. The body starts with an indentation and the first unindented line marks the end.

Python interprets non-zero values as TrueNone and 0 are interpreted as False.

if 1>10:
    print("greater than 10")
elif 1 > 5:
    print("greater than 5")
else:
    print("less than 5")

The and keyword is a logical operator, and is used to combine conditional statements

if 1>10 and 2 > 3:
    print("")
elif 1 > 5:
    print("")
else:
    print("less than 5")

The or keyword is a logical operator, and is used to combine conditional statements

if 1>10 or 2 > 3:
    print("")
elif 1 > 5:
    print("")
else:
    print("less than 5")

 

Pass statement

if statements cannot be empty, but if you for some reason have an if statement with no content, put in the pass statement to avoid getting an error.

if 3 > 2:
  pass

 

Source on Github

March 7, 2021

Python – Class

Python is an object oriented programming language. Unlike procedure oriented programming, where the main emphasis is on functions, object oriented programming stresses on objects. An object is simply a collection of data (variables) and methods (functions) that act on those data. Similarly, a class is a blueprint for that object.

We can think of class as a sketch (prototype) of a house. It contains all the details about the floors, doors, windows etc. Based on these descriptions we build the house. House is the object. As many houses can be made from a house’s blueprint, we can create many objects from a class. An object is also called an instance of a class and the process of creating this object is called instantiation.

Syntax

# create class
class class_name():
   variables
   def __init__(self, parameters):
   functions

# create object of class
variable = class_name();

__init__() function

This special function gets called whenever a new object of that class is instantiated. This type of function is also called constructors in Object Oriented Programming (OOP). We normally use it to initialize some if not all variables within the class or perform any operations that are necessary for the object.

Object method

instance method or object method is a method that can freely access attributes and other methods on the same object. This gives them a lot of power when it comes to modifying an object’s state.Not only can they modify object state, instance methods can also access the class itself through the self.__class__ attribute. This means instance methods can also modify class state.

class User():
    name = str
    age = int

    def __init__(self, name, age):
        self.name = name
        self.age = age

    def get_name(self):
        return self.name

class method

Because the class method only has access to this cls argument, it can’t modify object instance state. That would require access to self. However, class methods can still modify class state that applies across all instances of the class.

static method

This type of method takes neither a self nor a cls parameter (but of course it’s free to accept an arbitrary number of other parameters).

Therefore a static method can neither modify object state nor class state. Static methods are restricted in what data they can access – and they’re primarily a way to namespace your methods.

class User():
    name = str
    age = int
    admin_type = "ADMIN"
    user_type = "USER"

    def __init__(self, name, age):
        self.name = name
        self.age = age

    def get_name(self):
        return self.name

    @classmethod
    def get_admin_role(cls):
        return "ROLE_"+cls.admin_type

    @staticmethod
    def get_user_role():
        return "ROLE_" + User.user_type
# class method
print(User.get_admin_role())

# static method
print(User.get_user_role())

 

You can delete properties on objects by using the del keyword

kinga = User("Kinga", 8)
print(kinga.get_name())
del kinga.name
print(f'name: {kinga.get_name()}')

# output
Kinga
name: <class 'str'>

class definitions cannot be empty, but if you for some reason have a class definition with no content, put in the pass statement to avoid getting an error.

class User():
    pass

 

Source code on Github

 

March 5, 2021