Getting started with Python: basics

·

7 min read

If you are here I assume you have tried programming initially and want to know how we declare variables, arrays, loops in Python.

Python seems like a magic when it comes to syntax as as first I thought it some sort of pseudo but it is a powerful language which I learnt to understand backend development. Having said that let's just dive into how top use Python to create cool stuffs.

How to declare variable?

As easy as it gets, you don't have to worry about declaring type of variable in Python. You can just start by writing

var1 = "This is a variable"

But this was a string so we enclosed it in apostrophes. How we declare other variables? Just like that.

var_integer = 1000
var_boolean = True
var_float = 20.8

You can name the variable anything! var_integer is used for understanding purpose here.

Conditional Flow elements

Unlike Java or JavaScript where we use curly brackets to wrap the if - else state, here we have to use a : separator between the condition and statement body.

You use elif instead of else if in Python. Here are the sample usage of if else statement that we use in Python

if 1 < 2:
  print("1 is less than 2")
if(1>2):{
  print("If statement")
}
else: {print("Else statement")}
if(1>2):{
  print("If statement")
}
elif(1<2):{print("Elif statement")}
else: {print("Else statement")}

Run the three statements statements and see which part will be executed.

Loops in Python

Using a loop in Python is similar to how we write a conditional statement in Python, we have to use the : symbol.

num = 0

while (num<10):
    print(num);
    num+=1;

This program will print all numbers from 0 to 9.

The same program can be written using for loop.

for i in range(0,10):print(i)

The range defines the lower and upper limit where upper limit is excluded. This seems similar to how we use splice() function in JavaScript or substring() function in Java.

How to declare arrays?

Till now you have declared arrays as

int[] arr = new int[] - JAVA
let arr = [] - JAVASCRIPT

In Python you get flexibility to declare and add elements in you array without using the int or let Here is how you declare an array

arr = []
arr2 = [1,"String", True, 10.5]

As you can see you can add different types of element in the array in Python just like JavaScript.

Adding an element in arr.

arr2.append("new element")

arr2 -> [1,"String", True, 10.5, "new element"]

Now we are want to iterate through the array. Following is a method to iterate in Python using for loop

nums = [1, 2,"3", "String_example"]
for i in nums:(print(i))

All the values will be printed of nums.

There is a dictionary data structure. It involves the concept of key-value pair. A similar data structure you have seen as Objects in JavaScript but the way to access dictionary element and object are not same and we will see how.

The way to declare a dictionary in Python is declaring a variable and then initializing it with curly brackets.

dictionary_object = {}

dictionary_ex = {
  "name":"Siddhant",
  "language":"Python",
  "telling_truth":True,
  "blog_number":4
}

You might have noticed we are declaring keys as Strings in Python which was not the case in JavaScript.

Accessing the elements of dictionary is also not similar to JavaScript. Consider you have to access the value at key telling_truth, this is how you will do it

print(dictionary_ex["telling_truth"])

You will get True as output.

Now it is time to iterate in the dictionary. You are free to use any of the two methods

for key in dictionary_ex: print(dictionary_ex["key"]

OR

for key, value in dictionary_ex.items(): 
print("This is key" ,key, "This is value ",value)

You can name the two parameters anything. You don't need to name it key and value.

Classes and Objects in Python

Objects represent the real world entities which have some data and some behavior.

The classic example of Bike as an object tells us that Bike has wheels, petrol tank, engine, exhaust pipe and other things.

Now these wheels exhibit some behavior, wheels can accelerate, rotate. Engine can produce power, exhaust, petrol tank stores fuel.

So data is attributes and behaviors are methods.

Class becomes a blueprint from which individual objects are created. Different bikes have same blueprint and have amen data and same behavior.

So class is a blueprint model for it's objects. Class doesn't take a space on it's own. Remember that!

The simplest form of class definition looks like this:

class ClassName: 
<statement-1>
.
.
.
<statement-N

Creating an instance of a class is simplest of all in Python. It is done in the following manner

instance_class = ClassName()

Currently instance of ClassName() will be empty. If we want to create an instance which have instances customized to a specific initial state we have to defince a special method in class init()

def __init__(self):
self.data = []

This initiate the object with an empty array. init() method have many arguments to give us flexibilty. A sample class will be defined as follows in Python:

class SampleClass:
  num = 10000
  word = "String_type"

  def ___init__(self):
      self.data = []

  def sample_function(self):
        return "Hello World"

Create an instance of class like this

sample = SampleClass()

Access the methods like this and all are valid

sample.num
sample.word
sample.sample_function()

Consider the following implementation example from Python Docs

class Dog:
    favourite_food = []
    kind = 'canine'         # class variable shared by all instances

    def __init__(self, name):
        self.name = name    # instance variable unique to each instance

    def add_food(self,food):
          self.favourite_food.append(food)  

>>> d = Dog('Fido')
>>> e = Dog('Buddy')
>>> d.kind                  # shared by all dogs
'canine'
>>> e.kind                  # shared by all dogs
'canine'
>>> d.name                  # unique to d
'Fido'
>>> e.name                  # unique to e
'Buddy'
>>> d.add_food('oats')
'['oats']'

Inheritance in Python

Python supports inheritance like any other Object Oriented Programming language.

The simple syntax of a derived class will look like this:

class DerivedClassname(BaseClassName):
<statements>

In case the BaseClassName is from another module, this is how you will use inheritance

class DerivedClassName(module_name.BaseClassName)

The instantiation of the base class will be same as we do for classes.

Python provides two functions that work with inheritance:

isinstance() to check the instance type. It returns boolean value.

issubclass() to check class inheritance. It also returns boolean value.

Read more about them here

You can also derive from multiple classes in Python. It is a sort of multiple inheritance and the order of looking in the bases classes for attributes is left to right.

class Derived_Class(baseClass_1, baseClass_2, baseClass_3.....,baseClass_n):
<statements>

The compiler will look for attribute first in baseClass_1 and if the attribute is not found it will look in base classes of baseClass_1 until the attribute is found.

If the attribute is not found then the attribute will be searched in the baseClass_2 and so on.

The left to right ordering of searching makes sure that one base class is searched only once for any attribute.

Encapsulation in Python

By definition Encapsulation means hiding direct access to methods and data objects. This ensures the working mechanism of object is hidden from outside view.

Till now in all above examples we have seen the variables declared as public. We can change the variable value, access it from outside.

But how we declare a private or non-ppublic variable or method in Python?

Private instance variables don't actually exist in Python. There is a convention followed that if a name has underscore as prefix we should treat it as non-public part of API

Here is how you write it

class Bike:

  def __init__(self, brand, price):
    self.brand = brand
    self._price = price

The _price variable is a non-public variable. You can still access it from outside and update it's value.

class Bike:

  def __init__(self, brand, price):
    self.brand = brand
    self._price = price

  def update_price(self, new_price):
    self._price = new_price

  def price(self)
    print(_price)

We can update and access _price now.

That's all for now. I hope you got a basics of how Python works, you will need more hands on experience to understand the working of Python and trust me it is a valid investment of time.