Avatar

Blogging tips

Avatar

Python, Django and Flask

Avatar

Latest tech posts

Tuesday, February 25, 2020

Constants in python - The workaround!

Having transitioned from other languages, including PHP and JavaScript, constants are engrained in my practice.

When I adopted Python, I quickly found myself asking the question, does Python have constants?

The answer is kind of, but not really. Let’s dig deeper!

What is a Constant?
Image result for constants



Before we move on, let’s define what a constant is, in case you’re unfamiliar.

A constant value is similar to a variable, with the exception that it cannot be changed once it is set. Constants have a variety of uses, from setting static values to writing more semantic code.

How to Implement Constants in Python

I said earlier that Python “kind of, but not really” has constants. What does that mean? It means that you can follow some standard conventions to emulate the semantic feel of constants, but Python itself does not support non-changing value assignments, in the way other languages that implement constants do.

If you’re like me and mostly use constants as a way of writing clearer code, then follow these guidelines to quasi-implement constants in your Python code:

  • Use all capital letters in the name: First and foremost, you want your constants to stand out from your variables. This is even more critical in Python as you can technically overwrite values that you set with the intention of being constant.

  • Do not overly abbreviate names: The purpose of a constant — really any variable — is to be referenced later. That demands clarity. Avoid using single letter or generic names such as N or NUM.


  • Create a separate constants.py file: To add an element of intentional organization in structure and naming, it’s common practice to create a separate file for constants which is then imported.


What does this all look like in practice?

We’ll create two files, constants.py and app.py to demonstrate.

First, constants.py:

# constants.py
RATIO_FEET_TO_METERS = 3.281
RATIO_LB_TO_KG = 2.205
Next, main.py:





Notice how the constant values are more apparent in the code as well as being outside the file itself. Both of these qualities help communicate the distinction between constant and variable.

If you do not want to continually type constant. you can import values individually:



from constants import RATIO_LB_TO_KG
from constants import RATIO_FEET_TO_METERS
print(RATIO_LB_TO_KG) # 3.281
print(RATIO_FEET_TO_METERS) # 2.205

Unfortunately, after taking all these steps it’s still possible to overwrite the values:


from constants import RATIO_LB_TO_KG
print(RATIO_LB_TO_KG) # 3.281
RATIO_LB_TO_KG = 1
print(RATIO_LB_TO_KG) # 1


Monday, February 10, 2020

Map function in python [map()]

       Map function is a good alternative for the “for loops” in python. Sometimes we do not want our code to look clumsy because of all the for loops we have used. In this case the “map()” in python comes to the rescue.

What are map functions?

map() function returns a map object(which is an iterator) of the results after applying the given function to each item of a given iterable (list, tuple etc.)



Syntax

map(fun, iter)


map() Parameter
  1. function - map() passes each item of the iterable to this function.
  2. iterable iterable which is to be mapped

You can pass more than one iterable to the map() function.

The map() function applies a given to function to each item of an iterable and returns a list of the results.

The returned value from map() (map object) then can be passed to functions like list() (to create a list), set() (to create a set) and so on.


Map function with a list

In this example there is a single list called numbers and a function square. The map function iterates the list one by one, passes the value to the function, gets the returned value and stores it in a map object. This can be converted to a list or tuple later.



Map function with a lambda function

This example is also similar to the previous one. But instead of passing the value to a separate function we are using the lambda function inline.



Map function with multiple lists or iterables

This example has two lists. The map function iterates both the list and adds them. I,e it adds the first value of the first list with the first value of the second list and so on.
(li1[0] + li2[0]) + (li2[1] + li2[1]) + (li3[2] + li3[2]) + …….



Scenarios where map function can be used.

  1. Given a list find the square of all the numbers in the list
  2. Check if the values of the list are “odd” or “even” etc



Friday, February 7, 2020

Python program to calculate the number of days a person have lived on earth

This is a simple python program to calculate the number of days a person has lived on earth.
This program uses the datetime module in python.



Datetime in python
A date in Python is not a data type of its own, but we can import a module named datetime to work with dates as date objects.



Creating Date Objects
To create a date, we can use the datetime() class (constructor) of the datetime module. The datetime() class requires three parameters to create a date: year, month, day.



With these concepts we can proceed to create our code snippet.

Get today's date.
Create a date object using the birthday, month and year as the arguments.
Find the difference between two objects.
Access the day's value from the result.



Wednesday, February 5, 2020

Important definitions - website

List of Definitions

1. DOM
2. jQuery


1. DOM

The Document Object Model (DOM) is an application programming interface (API) for valid HTML and well-formed XML documents. It defines the logical structure of documents and the way a document is accessed and manipulated.

2. jQuery

jQuery is a fast and concise JavaScript Library created by John Resig in 2006 with a nice motto: Write less, do more. jQuery simplifies HTML document traversing, event handling, animating, and Ajax interactions for rapid web development.

Monday, February 3, 2020

Make a flat list out of list of lists in django

Lists

Unlike C++ or Java, Python Programming Language doesn’t have arrays. To hold a sequence of values, then, it provides the ‘list’ class. A Python list can be seen as a collection of values.

To create a python list of items, you need to mention the items, separated by commas, in square brackets. This is the python syntax you need to follow. Then assign it to a variable. Remember once again, you don’t need to declare the data type, because Python is dynamically-typed.

  1. >>> colors=['red','green','blue']

flat list out of list of lists


Combining a list of lists to a single list is called a flat list.


[[1,2,3], [4,5], [6]] => [1, 2, 3, 4, 5, 6]

Django

Django provides a method called flatten for this purpose. This will flatten the list directly thereby saving us a lot of time and code.




#Happy coding

Wednesday, January 29, 2020

Python program for beginners - part 1

codesimple


This post will have 5 simple python programs. They are


  1. print using python
  2. check palindrome
  3. Armstrong number
  4. Find the greater number
  5. print prime numbers in a range
All these programs are provided along with a code snippet in this part. More programs on the next part.


1. Print using python

This simple code snippet shows how to print using python.
The simplest way to produce output is using the print() function where you can pass zero or more expressions separated by commas. This function converts the expressions you pass into a string before writing to the screen.


2. Check palindrome

Given a string, write a python function to check if it is palindrome or not. A string is said to be palindrome if reverse of the string is same as string. For example, “radar” is palindrome, but “radix” is not palindrome.



Tuesday, January 28, 2020

"Try/Except" and "Try/Except/Finally" statements in python

        In Python — along with most other languages — we use try statements to safeguard our code.

Let’s learn about what try statements do and how to begin using them!




What are Exceptions?
Before we dive into the syntax and implementation of try statements, it’s important to establish what exceptions are. 
An exception is the result of code within a try statement that fails. Think of an exception as your code being insulted — “I take exception to that request!”
There are a variety of exception types, we’ll be introduced to a few of them through this tutorial.

How to Use Try Statements?

A try statement, often referred to as a try block, in fact consists of at least two parts: try and except. 

The code we want to safeguard goes inside the try portion of the block. Afterwards, we define what happens when something goes wrong within the except.




In the example above, we use the catch-all value Exception to route any exception to this portion of the block. We also print a vague