Browse by Domains

A Beginner’s Guide to Programming | How to Start Coding

As someone from a non-technical background, the word ‘Programming’ would itself be enough to send shivers down your spine! So, you must be thinking ‘Why should I even put in the effort to learn Programming’?

Well, programmers are in high demand all over the world and the median salary of a computer programmer is 100,000k$ per annum. And with the advent of artificial intelligence and the threat of many jobs becoming automated, you don’t have to be scared at all, because it will be you who will help in automating tasks as a computer programmer! Also, there are still many systems for the next several decades that still require human intelligence, coupled with the ability to write code that makes this a very secure job option.

Now, that we know the importance of programming, let’s understand what exactly it is!

To answer that, let me ask a question! How do humans communicate with each other? We humans use a common language to speak with each other, isn’t it?

Similarly, if we have to speak with a computer, we need to learn a language which the computer can understand! And this is where a programming language comes in.

So, simply put, we solve real-world problems, by speaking with the computer in a language it actually understands.

Let’s take the example of a calculator!

When you feed in ‘1234 * 4321’ in the calculator. It immediately shows you, the result is ‘5,332,114’. How was the calculator able to do this multiplication?

This was possible because you wrote in a simple program to multiply two numbers which the calculator can understand. 

Similarly, when you ask Siri, what is the distance between the sun and The Earth, it would immediately reply, “The distance is 148.63 million km”.

Now, how is this possible?

This is possible, because there is a program running in the background which takes in the audio input, converts it into a language which ‘SIRI’ can understand, processes the information and gives an output.

Salary Statistics for People in Programming

According to LinkedIn, the average salary of a computer programmer in the United States is 100,000$ per annum and Rs.8,00,000 per annum in India.

Also, someone, who has programming skills can fit in anywhere in any organization.

You can be a UI/UX developer and be responsible for applying interactive and visual design principles on websites and apps. According to Glassdoor, the average salary of a UI/UX developer is 75,000$ per annum in the US and 6 lakhs per annum in India.

Or you can be a back-end developer and ensure that the data or services requested by a user through the frontend system are delivered through programmatic means. The average salary of a Back-end developer would be 90,000$ per annum in the US and 8 lakhs per annum in India.

If you like both front-end as well as the back-end, why not become a full stack developer and handle everything from UI to backend databases. The average salary of a Full Stack developer would be 115,000$ in the US and 13 lakhs per annum in India

The best part is, you don’t have to be limited to traditional Software development roles. If you like working with data and have an analytical bent of mind, you can work as a data scientist or a machine learning engineer.

And when it comes to the pay packages of those in the field of data science, they can touch up to 300,000$.

Well, this should be a good enough motivation for you to start learning programming!


The top three Programming Languages

  • Python
  • Java
  • C++

Python Programming

Python is a language which helps us to do a lot of cool stuff such as:

  • Web Development
  • Game Development
  • Machine Learning &
  • Computer Vision

Now, let’s go ahead and look at some basics of Python:

How to Install Python:

You can install python from this link: https://www.python.org/downloads/

Since Python is a platform-independent language, you can download it and run on any operating system. So, irrespective of whether you have Linux, Windows or a Mac System, you can download and run python.

Python IDE:

IDE stands for Integrated Development Environment and these IDEs make the coding task extremely easy. Let’s look at some of the most commonly used Python IDEs:

JetBrains Pycharm:

You can download Pycharm from this site: https://www.jetbrains.com/pycharm/

Anaconda Python:

This is the site to install anaconda: https://www.anaconda.com/

Now that we have installed Python and Python IDEs, let’s go ahead and learn some basics of python:


Variable in Python:

Programming languages deal with data. So, the question which arises over here is how do we actually store this data if we want to reuse it?

Let’s you’re working with some data about employees of your organization and you’d have to store the names of employees, so how will you do that?

Well, this is where variables come in. Variables are temporary storage spaces to store values.

Let’s say we create a variable called “employee_name”. Then we can go ahead and store the value “John” inside the variable. After some time, I can replace the value with “Sam”. Again after some time I’ll replace it with “Matt”.

Let’s see how can we create variables in python:

var1 = “Sam”

var1 = “Matt”

var1 = “John”

Since a variable is a temporary storage space, we can change the values which are stored in the variable “var1”.


Data-type in Python:

Every variable is associated with a data type:

  • Int: When we are working with integer numbers such as 10, -30, 500, we are actually dealing with int type data.
  • Float: When we working with decimal point numbers such as 3.14, -6.54, we are dealing with floating point data type
  • Boolean: Boolean data type consists of two values: True and False
  • String: When we say statements such as “My name is Julia” or “This is Sparta”, we are dealing with string type data.

Operators in Python:

Operators in Python as the name states help us to perform different types of operations on the data.

Let’s start with Arithmetic operators:

Arithmetic Operators:

Arithmetic operators help us to perform simple arithmetic operations such as addition, subtraction, multiplication and division.

a=10

b=20

a+b

a-b

a/b

a*b

Relational Operators:

Relational operators help us to find the relationship between operands.

a<b

a>b

a==b

a!=b


Strings in Python:

Strings are a sequence of characters enclosed within single quotes(‘ ’), double quotes(“ “) or triple quotes(‘’’ ‘’’)

a = ‘Hello World’

b = “This is Sparta”

c = ”’I am

going

to France

tomorrow

”’


Extracting Individual Characters from a String:

Code Explanation:

Here we start off by creating a string variable called ‘my_string’ and assign the value “My name is John” to it. In a string, each individual character is at a particular index and the index value starts at 0.

So, if we have to extract the first character in the string ‘M’, then, we ‘d have to give this command:

my_string[0]

Since indexing starts at 0, the index value of the first character ‘M’ will be 0.

Now, let’s see how can we extract the last character from the string:

We would have to give this command: 

my_string[-1] to extract the last character from this string.


Now, let’s look at some string functions:

We can use the len() method to find the number of characters present in the string. Here, when we pass the ‘my_string’ object into len() method, we see that there are 15 characters in total.

With the help of the lower() method, we can convert all the characters present in the string to lowercase

Similarly, with the help of the upper() method, we can convert all the characters present in the string into upper case.


Data Structures in Python:

We have four primary data structures in Python, which are:

  • Tuple
  • List
  • Dictionary &
  • Set

.Tuple in Python:

Tuple is an ordered collection of elements enclosed within round braces (). Tuples are also immutable which means that, once you create a tuple in python, you can’t modify it.

This is how we can create a tuple in Python:

tup1=(1,’a’,True)

Now, let’s see how can extract individual elements from a tuple:

Here, we have created a tuple called ‘tup1’ and have stored 6 values inside it. The indexing of a tuple also starts from 0, so if we have to extract the first element from this tuple, we’ll give this command:

tup1[0]

Similarly, we can extract the last element from the tuple by using this command:

tup1[-1]

Now, we can also go ahead and extract the first three elements from this tuple by using this command:

tup1[1:4]


Now, let’s see what happens if try to modify a tuple:

We get the error: ‘tuple’ object does not support item assignment. As we are trying to modify a tuple and since tuple is immutable, we get this error.


Tuple Basic Operations:

Let’s see how can we find out the length of a tuple:

Here, we have created a new tuple “tup1”. If we want to find out the number of elements present in the tuple, we just need to use the len() method:

Here, we use len(tup1) and this gives us a result of 6, which means that there are 6 elements in the tuple.


Now, let’s see how can we concatenate two tuples:

Here, we have created two tuples “tup1” and “tup2”. In tup1, we have stored the values 1,2 and 3. In tup2, we have stored the values 4,5 and 6. Now, if we have to concatenate the values of tup2 to tup1 all we have to do is use this command: 

tup1+tup2


Now, let’s see how can we repeat tuple elements:

Initially, we have created a tuple “tup1”, inside which we only have two elements: ‘sparta’ and 300. Now, if we want to repeat the elements all we have to do is multiply the tuple with a numerical value.

Here, we use this command: tup1 * 3. With this command, we are able to repeat the elements inside the tuple 3 times.


Finding minimum and maximum values from a tuple:

To find the minimum value from a tuple, we just need to use this command: min(tup1). Similarly, to find out the maximum value from the tuple, we need to use this command:

max(tup1)


List in Python:

List is an ordered collection of elements enclosed within []. Lists are also mutable. This means that once a list has been created we can actually modify it anytime we want.

This is how we can create a list:

L1 = [1,’a’,True]


Extracting Individual Elements from a List:

Extracting elements from a list is also a similar process. Here we are extracting the second element from this list. Since, it is the second element, we use this command:

l1[1]

Here, we see that we are extracting a series of elements. If we want to extract the second, third and fourth elements from this list, we use this command: 

l1[2:5]

Since the outer limit is exclusive, that is why we are extracting elements only till the 4th index.


Modifying a List:

Here, we have created a list, where the element ‘1’ is present at the 0th index. Now, we are adding a new element at the 0th index with this command:

l1[0] = 100

After using this command, we see that the element ‘100’ is stored at index 0 now and the rest of the elements have been shifted to one position upwards.

Now let’s see how can we append a new element to the end of the list:

 If we want to add an element at the end of the list, we can use the append() method. Here we are using this command:

l1.append(“Sparta”)

With the help of this command, we are able to append the word “Sparta” at the end of the list.

In the above example, we are popping out the last element from the list. We use this command:

l1.pop()

Before using the command, the last element in the list was “c”, and after using the pop() method, we are able to pop out the last element and we see that the last element in the list now is ‘3’

In the above example, we are reversing the elements of the list. We use this command:

l1.reverse()

After using this command, we see that the elements in the list are reversed.

In the above example, we are sorting the elements present in the list. We are using this command:

l1.sort()

Before using this command, we see that, the elements in the list are arranged in alphabetical order. After using the command, the elements are sorted in alphabetical order.


Basic Operations on a List:

Here we have created two lists. The first list l1 comprises of these three elements: 1 2 3

The second list l2 comprises these three elements: “a” “b” “c”. Now if we want to concatenate these two lists, we just have to type: l1 + l2

In the above example, we are repeating the elements present in the list. Initially, the elements present in the list were 1, “a”, and True. Then we go ahead and use this command:

l1*3

Since we are multiplying the list with 3, we see that the elements are being repeated three times.


Dictionary in Python:

Dictionary is an unordered collection of key-value pairs enclosed within {}. Dictionary is a mutable data structure. This means that once we create a dictionary, it can be modified later on whenever we want.

This is how we can create a dictionary:

Fruit={“Apple”:10,”Orange”:20}

Here, we have created a new dictionary called “Fruit”, which comprises of two key-value pairs. The first key is apple and the value for that is 10. The second key is orange and the value for that is 20.


Extracting Keys and Values from a Dictionary:

Here, we have created a dictionary called fruit which has four key-value pairs. 

  • The first key is “Apple” and the value for that is 10
  • The second key is “Orange” and the value for that is 20
  • The third key is “Banana” and the value for that is 30
  • The fourth key is “Guava” and the value for that is 40

After creating the dictionary, we extract the keys using this command:

fruit.keys()

This command gives us the list of all the keys.

Similarly, if we want to extract all the values, we can use this command:

fruit.values()


Modifying a Dictionary:

In this example, we have this dictionary called ‘fruit’ which has four key-value pairs. Now, we are adding a new key-value pair using this command:

fruit[“Mango”] = 50

With this have added a new key-value pair, where the key is “Mango” and the value is 50


Now let’s see how can we modify the value of an existing key:

Initially, in this dictionary, we have a key-value pair of “Apple”:10. Now, when we use this command:

fruit[“Apple”] = 100

We are updating the value from 10 to 100.


Dictionary Functions:

Here, we have created two dictionaries:

  • The first dictionary is fruit1 which has two key-value pairs: “apple”-10 and “Orange”:20
  • The second dictionary is fruit2 which again has two key-value pairs: “Banana”-30 and “Guava”:40

If we want to concatenate the elements of fruit2 to fruit1, we can use this command:

fruit1.update(fruit2)

After using this command, we see that the elements of fruit2 have been appended at the end of dictionary fruit1.

In the above example, we are popping out an element with this command:

fruit.pop(“Orange”)

Inside the pop() method, we pass in the key which we want to pop out. Since, we pass in “Orange”, we see that the key-value pair of “Orange”:20 has been popped out from the dictionary.


Set in Python:

Set is an unordered and unindexed collection of elements enclosed within {}. One important feature of “Set” is, duplicate values are not allowed inside it.

This is how can create a set:

S1 = {3,”Sparta”,True}


Operations on Set:

Initially, we have created a set “s1” which comprises of these elements: 1, “a”, True, 2, “b”, False. Now, if we want to add a new element to this set we can use the add() method. We are using this command:

s1.add(“Hello”)

After using the above command we see that we have successfully added a new element “Hello” into the set. Also, if you closely look at the result,, you would notice that the sequence of elements in the output is not the same as we had given while creating it. This is because a set is an unordered and unindexed collection of elements, that is why the insertion sequence is not maintained.


In the above example, we are adding multiple elements into the set in single go. For this purpose we are using this command;

s1.update([10,20,30])

With the help of the update() method, we can add a list of elements into the existing set. Though as you see in the result, the order of insertion will be totally haphazard.


Now, let’s see how can we remove an element from the set:

On the set “s1”, we are using this command:

s1.remove(“b”)

We see that in the result, we were able to successfully remove the element “b” from the entire set.


Union and Intersection of Sets:

Here, we have created two sets “s1” and “s2”. “s1” has the elements 1, 2 and 3 in it. While s2 has the elements “a”, “b” and “c” in it.

Now, if we want the union of these two sets, we can use this command:

s1.union(s2)

The union operators gives us all the elements from s1 as well as all the elements from s2.


If Condition in Python:

If the condition in Python is used to make a decision on the basis  of a condition.

Let’s understand the concept of if condition with this example. Here we have a condition which states that “If it’s raining”, we cannot play and have to sit inside, else if it is not raining, then we can happily go out and play.

Now, let’s see how can we use if condition in Python:

a=10

b=20

if b>a:
    print("B is greater than A")

Code Explanation:

Here we have declared two variables: a and b. Variable a is initialized with the value of 10 and Variable v is initialized with the value of 20. After that we use the if statement and check if the value in variable b is greater than the value in variable a with this command:

if b>a:
    print("B is greater than A")

If the condition is satisfied, we go ahead and print out the result.


else if in Python:

Now, let’s see how can we compare more than two numbers using else if in Python:

a=10

b=20

c=30

if (a>b) & (a>c):
    print("A is the greatest")
elif (b>a) & (b>c):
    print("B is the greatest")
else:
    print("C is the greatest")

Code Explanation:

Here we have declared three variables a,b and c. Variable a is initialized with the value of 10, Variable b is initialized with the value of 20 and Variable c is initialized with the value of 30.

After that, we start off by using the if statement to check if the value of variable a is greater than variable b and variable c with this command:

if (a>b) & (a>c):
    print("A is the greatest")

Since value of variable a is less than b and c, that is why this command will be skipped.

Then, we go ahead and check if the value of Variable b is greater than a and c using elif command:

elif (b>a) & (b>c):
    print("B is the greatest")

Here, this elif statement also evaluates to False, so this block of statement will also be skipped.

Finally, if the above two statements are evaluated to value we will just go ahead and print out “C is the greatest” using this command:

else:
    print("C is the greatest")

for loop in Python:

Looping statements are used to repeat a task multiple times. 

Let’s take this example to understand the concept of looping better. Consider that you have to fill up a bucket with water using only a mug. So, you’ll take a mug of water and then pour it in the bucket, after that you’ll check if the bucket is complete with water or not. Then again, we take a mug of water and pour it into the bucket. Again, we’ll check if the bucket is full or not. This process will go on while the bucket is not full with water and this is how looping works.

Now, let’s see how can we use for loop in Python:

fruits = ["apple","mango","banana"]
for i in fruits:
    print(i)

Here, we start off by creating a list named fruits which has these three elements: “apple”, “mango” and “banana”. Then, we use the for loop to print out the individual elements in the list using this command:

for i in fruits:
    print(i)

Number Pattern Problem:

1  

2 2  

3 3 3  

4 4 4 4  

5 5 5 5 5

Let’s go ahead and see how can we print this pattern of numbers:

depth = 6
for number in range(depth):
    for i in range(number):
        print(number, end=" ")  
    print(" ")

Code Explanation:

We start off by initializing a variable called “depth” and give it a value of 6 with the help of this command:

 depth = 6

Going ahead, we have a nested for loop. We have the outer for loop to set the depth or number of rows in this pattern. When we use the command: for number in range(depth), this helps us to get a list of numbers 0-5. Because the depth value is 6, this means that 6 is exclusive and that is why the range goes from 0-5.

Then, we set the inner for loop using this command:  for i in range(number).

In the inner for loop, initially the value of number is 0, that is why we skip the first row. Then we go back to the outer for loop and the number value becomes 1. Once the number value is 1, we head inside the inner loop and print 1.

After that number value is incremented again and it becomes 2, then we head to the inner loop and print 2 2.

Similarly, we go back to the outer loop and this time number value becomes 3. After this inside the for loop we print 3 3 3.

Further which, again we go back to the outer loop, then the value of “number“ becomes 4 and we print 4 4 4 4 with the inner loop.

Finally we will print 5 5 5 5 5.


Incrementing Number Pattern Problem:

1 2 

1 2 3 

1 2 3 4 

1 2 3 4 5

Now, let’s go ahead and see how can we have sequence of numbers in each row with python:

depth = 6
for number in range(1, depth):
    for i in range(1, number + 1):
        print(i, end=' ')
    print("")

Code Explanation:

We start off by initializing the value of depth to be 6. Then, we set the outer for loop with this command: for number in range(1, depth). With the help of this command, we create a range of numbers which go on from 1 to 5. Then, we go ahead and set the inner for loop with this command:  for i in range(1, number + 1). Inside the for loop we print the digits using this command:  print(i, end=’ ‘).

Initially, the value of number is 1 in outer for loop, so we enter the inner for loop and go ahed and print 1.

Then in the outer for loop, the value of number becomes 2, so we enter the inner for loop and we print 1 2.

Similarly, we go back to the outer loop and here the number value becomes 3, so this time we enter the inner loop and print 1 2 3.

Going ahead, the value of “number” in outer loop becomes 4, so with the inner loop we print 

1 2 3 4

And in the final iteration, we print out: 1 2 3 4 5


Pyramid Pattern Problem with Stars:

*

* *

* * *

* * * *

* * * * *

Let’s see the code for this:

def diamond(n):
   for m in range(0, n):
      for i in range(0, m+1):
         print("* ",end="")
      print("\r")
n = 5
diamond(n)

Code Explanation:

We start off by defining a method called “diamond” with this command: def diamond(n).

We set the outer for loop with this command:    “for m in range(0, n)”. Then, we go ahead and set the inner for loop using this command:       “for i in range(0, m+1)”:

Initially, the value of ‘m’ is 0 in the outer for loop, so we go inside the for loop and print *.

Then, the value of ‘m’ in the outer for loop becomes 1, this time we go inside the inner loop and print * *.

Similarly, the value of ’m’ in the outer loop becomes 2, so, we go inside the inner loop and print 

* * *.

Going ahead, the value of ‘m’ is incremented in the outer loop and it becomes 3, so, with the inner loop, we print * * * *.

In the final iteration, we print out * * * * *.


Inverted Semi-Pyramid Pattern Problem with Numbers:

1 1 1 1 1 

2 2 2 2 

3 3 3 

4 4 

5

Let’s write the code for this:

row = 5
a = 0
for i in range(row, 0, -1):
    a += 1
    for j in range(1, i + 1):
        print(a, end=' ')
    print('\r')

Code Explanation:

We start off by initializing two variables. We set the value of row to be equal to 5 and the value of a to be equal to 0. After that we set the outer for loop with this command: 

for i in range(row, 0, -1):

This outer for loop, gives us numbers in descending order starting with 5 going on till 1. In the outer for loop, we increment the value of a with 1. After that, we set the inner for loop using this command:     for j in range(1, i + 1).

In the first iteration, the value of ‘i’ in outer for loop is 5, so with the inner for loop we print: 

1 1 1 1 1

In the second iteration, the value of ‘i’ in outer for loop is 4, so in the inner for loop we print:

2 2 2 2

In the third iteration, the value of ‘i’ in outer loop is decremented to 3, then, with the inner loop we print:

3 3 3

Going ahead in the fourth iteration, the value of ‘i’ in the outer loop is decremented to 2, so this time with the inner loop, we print:

2 2 

And finally, in the last iteration, we print out 1.


Inverted Semi-Pyramid Pattern Problem with Descending order of Numbers:

5 5 5 5 5 

4 4 4 4 

3 3 3 

2 2 

1

Let’s look at the code to implement this pattern:

depth = 5
for i in range(depth, 0, -1):
    n = i
    for j in range(0, i):
        print(n, end=' ')
    print("\r")

Code Explanation:

We start off by initializing the value of depth to be equal to 5. Then using the outer for loop, we produce a list of numbers in descending order from 5 to 1. Inside the outer for loop, we set the value of n to be equal to i. After that, we start off the inner for loop using this command:     

for j in range(0, i):

In the first iteration the value of ‘i’ is 5 in the outer loop, so with the inner loop we print: 5 5 5 5 5

In the second iteration, the value of ‘i’ in the outer loop is decremented to 4, so we enter the inner loop and print 4 4 4 4

Then in the third iteration, the value of ‘i’ becomes 3, so with the inner loop, we print: 3 3 3

Going ahead in the fourth iteration, the value of ‘i’ becomes 2, this time we print out 2 2 with the inner loop.

Finally, in the last iteration, the value of ‘i’ becomes 1 and we print out 1.


Semi-Pyramid Pattern Problem with Numbers descending in each row:

2 1 

3 2 1 

4 3 2 1 

5 4 3 2 1

Let’s look at the code for this:

size = 6
for row in range(1, size):
    for column in range(row, 0, -1):
        print(column, end=' ')
    print("")

Code Explanation:

We start off by setting the value of variable size to be equal to 6. Then, we set the outer for loop with this command: for row in range(1, size). With this outer for loop, we produce a list of numbers starting from 1 going on till 5. Then, we set the inner loop with this command:     for column in range(row, 0, -1)

 In the first iteration, the value of row is 1 in the outer loop, so we enter the inner for loop and print 1.

Then in the second iteration, the value of row is 2 in the outer loop, so this time we enter the inner loop and print: 2 1

After that, in the third iteration, the value of row becomes 3 in the outer loop, so in the inner loop we go ahead and print: 3 2 1

Going ahead, in the fourth iteration, the value of row becomes 4 in the outer loop, so this time, in the inner loop we print: 4 3 2 1

Finally, in the last iteration, we go ahead and print: 5 4 3 2 1


OOPs Concepts in Python:

What do you see when you look around you? You see a lot of objects, don’t you!

If you see a laptop in front of you, what is it? Well, it is a real-world object!

Similarly, if there’s a car on the road? What is that? A car again is a real-world object!

Now, if you see a dog on the street, what do you think it is? You guessed It right, it’s an object again!

Now, if you have to represent these real-world entities in the programming world, you would need an object-oriented programming language. This is where Python comes to the rescue! Python is the most widely used object-oriented programming language and it is also pretty simple to learn.

So, let’s understand Object-Oriented Programming in python  –

Object-Oriented Programming in Python comprises of two main components:

  • Classes
  • Objects(This is obvious 🙂 )

Let’s start with Classes ~

You can consider a class to be a template/blueprint for real-world entities. Let’s take this example to understand the concept of classes better:

If we take a class called as ‘Phone’. You can consider this to be a template for the real-world entity phone.

This class would have two things associated with it: Properties and Behaviour.

The class ‘Phone’ would have certain properties associated with such as:

  • Color
  • Cost &
  • Battery Life

Similarly, the class ‘Phone’ would have certain behavior associated with such as:

  • You can make a call
  • You can watch videos &
  • You can play games

When you combine these properties and behavior together, what you get is a class!

Now, let’s learn about objects!

Simply put, you can consider objects to be specific instances of a class.

So, if ‘Phone’ is our class, then ‘Apple’, ‘Motorola’ and ‘Samsung’ would be the specific instances of the class, or in other words, these would be the objects of the class ‘Phone’.

Now that this covers the basics of object-oriented programming, you’d want to deep dive into OOP with Python.


Let’s go ahead and create our first class in python:

class Phone:
    
    def make_call(self):
        print("Making phone call")
    
    def play_game(self):
        print("Playing Game")

Code Explanation:

Here, we have created a new class called ‘Phone’. To create a new class we use the keyword ‘Class’ and follow it up with the class-name. By convention, the class-name should start with a capital letter.

Inside the class, we are creating two user-defined functions:

make_call() and play_game().

make_call() method is just printing out “making a phone call” and play_game() method is just printing out ‘Playing Game’.


Now that we have created the class, we’d have to go ahead and create an object of the class:

p1=Phone()

p1.make_call()

p1.play_game()

Code Explanation:

We are creating a new object called as p1 with the command: p1=Phone(). Now, if we’d have to invoke the methods which are present in the class, we’d have to use the ‘.’ operator.

To invoke the make_call() method from the Phone class, we use: p1.make_call(). Similarly, to invoke the play_game() method from the Phone class, we use: p1.play_game().


Now, let’s go ahead and add parameters to the methods of our class:

class Phone:
    
    def set_color(self,color):
        self.color=color
        
    def set_cost(self,cost):
        self.cost=cost
        
    def show_color(self):
        return self.color
    
    def show_cost(self):
        return self.cost
    
    def make_call(self):
        print("Making phone call")
    
    def play_game(self):
        print("Playing Game")

Code Explanation:

Inside the Phone class, we are creating 6 methods:

  • set_color()
  • set_cost()
  • show_color()
  • show_cost()
  • make_call()
  • play_game()

set_color(): This method takes in two parameters: self and color. With the code self.color=color, we are able to set a color to the attribute ‘color’.

set_cost(): This method also takes in two parameters: self and cost. With the code: self.cost=cost, we are able to set a cost value to the attribute ‘cost’.

show_color(): With this method, we are just returning the color of the phone.

show_cost(): With this method, we are returning the cost of the phone.

make_call(): With this method, we are simply printing out: “Making a phone call”.

play_game(): With this method, we are printing out: “Playing Game”


Now that we have created the class, it’s time to instantiate the class and invoke the methods:

p2=Phone()

p2.set_color("blue")

p2.set_cost(100)

p2.show_color()

p2.show_cost()

Code Explanation:

We start off by instantiating the class Phone: p2=Phone(). Once, we have the object, it’s time to go ahead and invoke the methods of the object.

By using, p2.set_color(“blue”), we are passing in the value “blue” to the attribute color.

Similarly by using, p2.set_cost(100), we are passing in the value 100 to the attribute cost.

Now, that we have assigned the color and cost to the attributes, it’s time to return the values.

By using, p2.show_color(), we go ahead and print out the color of the phone.

Similarly by using, p2.show_cost(), we go ahead and print out the cost of the phone.


Constructor in Class: 

A constructor is a special type of method inside a class, with the help of which we can assign the values to the attributes directly during the instantiating of the object.

Let’s understand the concept of constructor, through this example:

class Employee:
    def __init__(self,name,age, salary,gender):
        
        self.name = name
        self.age = age
        self.salary =  salary
        self.gender = gender
        
    def employee_details(self):
        print("Name of employee is ",self.name)
        print("Age of employee is ",self.age)
        print("Salary of employee is ",self.salary)
        print("Gender of employee is ",self.gender)

Code Explanation:

Here, we are creating a new class called as Employee. Inside the ‘Employee’ class, we have two methods:

  • __init__()
  • employee_details()

__init__() method is what is known  as the constructor in the class. With the help of this __init__ method, we are able to assign the values for name, age, salary and gender.

By using,  self.name = name, we are assigning the value for name. Similarly, by using, self.age = age, we are assigning the value for age. Then by using,    self.salary =  salary, we are assigning the value for salary. And finally, we are assigning the value for gender by using: self.gender = gender.

Then, with the help of the employee_details() method, we are just printing out the values for name, age, salary and gender.


Now, that we have created a class using a constructor, it’s time to create an object and instantiate the values with the help of this object:

e1 = Employee('Sam',32,85000,'Male')
e1.employee_details()

Code Explanation:

By using this command: e1 = Employee(‘Sam’,32,85000,’Male’), we are creating an object of Employee class e1 and also instantiating the values for name, age, salary and gender.

We pass in the value ‘Sam’ for name, 32 for age, 85000 for salary and ‘male’ for gender.

Then, we just go ahead and print out the employee details by using the command: 

e1.employee_details()


Inheritance:

With inheritance one class can derive the properties of another class.

Consider this example: You would have certain features similar to your father and your father would have certain features similar to your grandfather. This is what is known as inheritance. Or in other words, you can also say that, you have inherited some physical traits from your father and your father has inherited some physical traits from your grandfather.

Now, that we know what exactly is inheritance, let’s see how can implement inheritance in python:

class Vehicle:
    
    def __init__(self,mileage, cost):
        self.mileage = mileage
        self.cost = cost
        
    def show_details(self):
        print("I am a Vehicle")
        print("Mileage of Vehicle is ", self.mileage)
        print("Cost of Vehicle is ", self.cost)

Code Explanation:

Here, we are creating our parent class called as ‘Vehicle’. This class has two methods:

  • __init__()
  • show_details()

With the help of __init__() method, we are just assigning the values for mileage and cost. Then, with the help of ‘show_details()’, we are printing out the mileage of the vehicle and the cost of the vehicle.


Now, that we have created the class, let’s go ahead and create an object for it:

v1 = Vehicle(500,500)
v1.show_details()

Code Explanation:

We are starting off by creating an instance of the Vehicle class. The Vehicle class takes in two parameters which are basically the values for mileage and cost. Once, we assign the values, we just go ahead and print out the details, by using the method v1.show_details().


Now, let’s go ahead and create the child class:

class Car(Vehicle):
    def show_car(self):
        print("I am a car")

c1 = Car(200,1200)

c1.show_details()

c1.show_car()

Code Explanation:

We are starting off by creating the child class ‘Car’. This child class inherits from the parent class “Vehicle”.

This child class has it’s own method ‘show_Car()’, which just prints out ‘I am car’. Once we create the child class, it’s time to instantiate the class. We use the command: 

c1 = Car(200,1200), to create an object ‘c1’ of the class ‘Car’. 

Now, with the help of c1, we are invoking the method, c1.show_details(). Even though, show_details in exclusively a part of the ‘Car’ class, we are able to invoke it because the ‘Car’ class inherits from the ‘Vehicle’ class and the show_details() method is part of the Vehicle class.

Finally, we are using c1.show_car() to go and print out ‘I am car’.


Now, let’s see how can we over-ride the __init__ method during inheritance:

class Vehicle:
    
    def __init__(self,mileage, cost):
        self.mileage = mileage
        self.cost = cost
        
    def show_details(self):
        print("I am a Vehicle")
        print("Mileage of Vehicle is ", self.mileage)
        print("Cost of Vehicle is ", self.cost)

Code Explanation:

We are again creating the same parent class ‘Vehicle’ with the methods : __init__() and show_details().


Now, let’s go ahead and over-ride the init method inside child class ‘Car’:

class Car(Vehicle):
    
    def __init__(self,mileage,cost,tyres,hp):
        super().__init__(mileage,cost)
        self.tyres = tyres
        self.hp =hp
        
    def show_car_details(self):
        print("I am a car")
        print("Number of tyres are ",self.tyres)
        print("Value of horse power is ",self.hp)

Code Explanation:

Here the child class ‘Car’, itself has an __init__() method. This __init__() method takes in 5 parameters:

  • Self
  • Mileage
  • Cost
  • Tyres
  • Hp

Inside the __init__() method, we are using super() method to pass in parameters for the parent class. So, mileage and cost go into the parent class’s __init__() method.

Once we pass in the parameters of the parent class, we are assigning the values for ‘tyres’ and ‘hp’.

By using self.tyres = tyres, we are assigning the value for ‘tyres’. Similarly, by using self.hp =hp, we are passing in value for ‘hp’.

Then we have another method called as show_car_details(), with the help of which we are just printing out the number of tyres in the car and the horsepower of the car.


Now, let’s go ahead and create an instance of the car class:

c1 = Car(20,12000,4,300)

c1.show_details()

c1.show_car_details()

Code Explanation:

We are starting off by creating an object of the car class. This take in 4 parameters:

  • 40 for the Mileage of the car
  • 12000 for the cost of the car
  • 4 for the number of tyres
  • HP for the value of horsepower of the car

Then, we go ahead and invoke c1.show_details(), which is from the parent class. Similarly, we invoke c1.show_car_details(), which is from the child class.


Multiple Inheritance:

In multiple inheritance, the child inherits from more than one class.

Let’s have an example to understand the concept of multiple inheritance:

class Parent1(): 
    def assign_string_one(self,str1): 
        self.str1 = str1
        
    def show_string_one(self): 
        return self.str1

class Parent2(): 
    def assign_string_two(self,str2): 
        self.str2 = str2
        
    def show_string_two(self): 
        return self.str2


class Derived(Parent1, Parent2): 
    def assign_string_three(self,str3): 
        self.str3=str3
          
    def show_string_three(self): 
        return self.str3

Code Explanation:

We start off by creating our first parent class “Parent1”. This parent class has two methods:

  • assign_string_one()
  • show_string_one()

With the help of assign_string_one(), we are printing out the value of the attribute str1. Then, with the help of show_string_one(), we are just printing out the value of attribute str1.

Once, we have defined our first class, we go ahead and create our second parent class: “Parent2”. This class again has two methods:

  • assign_string_two()
  • show_string_two()

With the help of assign_string_two(), we are printing out the value of the attribute str2. Then, with the help of show_string_two(), we are just printing out the value of attribute str2.

Finally, we go ahead and create our child class: “Derived”. This “Derived” class is inheriting from both “Parent1” and “Parent2”.

This “Derived” class again has two methods:

  • assign_string_three()
  • show_string_three()

With the help of assign_string_three(), we are printing out the value of the attribute str3. Then, with the help of show_string_three(), we are just printing out the value of attribute str3.


Now, that we have all the classes ready, let’s go ahead and create an object for the “Derived” class:

d1 = Derived()

d1.assign_string_one("one")
d1.assign_string_two("two")
d1.assign_string_three("three")

d1.show_string_one()
d1.show_string_two()
d1.show_string_three()

Code Explanation:

We create the object d1 for the class “Derived” by using this command: d1 = Derived(). Then, we go ahead and assign the value for str1 by invoking assign_string_one(). Similarly, we assign the value for str2 by invoking assign_string_two() and finally, we assign the value for str3 by invoking assign_string_three().

Once we assign the values, we print out the values for str1, str2 and str3.


In multilevel Inheritance, we have parent-child-grandchild relationship.

Let’s go through an example to understand this better:

class Parent(): 
    def assign_name(self,name): 
        self.name = name
        
    def show_name(self): 
        return self.name


class Child(Parent): 
    def assign_age(self,age): 
        self.age = age
        
    def show_age(self): 
        return self.age


class GrandChild(Child): 
    def assign_gender(self,gender): 
        self.gender = gender
        
    def show_gender(self): 
        return self.name

Code Explanation:

We start off by our first class “Parent”. This class has two methods:

  • assign_name()
  • show_name()

With the help of assign_name(), we are assigning the value for name attribute. Then, with the help of show_name(), we are returning the value for name.

Once we have created the “Parent” Class, we are creating the “Child” class. This “Child” class is inheriting from the “Parent” class.

This class again has two methods:

  • assign_age()
  • show_age()

With the help of assign_age(), we are assigning a value for the age attribute. Then, with the help of show_age(), we are printing out the value for age.

Finally, we have the “GrandChild” class. This class is inheriting from the “Child” class.

Inside this class we have two methods:

  • assign_gender()
  • show_gender()

With the help of assign_gender(), we are assigning a value for the “gender”. With the help of show_gender(), we are returning the value for gender.


Now that we have created the classes, let’s go ahead create an object for the GrandChild class:

g1 = GrandChild()

g1.assign_name("Sam")
g1.assign_age(25)
g1.assign_gender("Male")

g1.show_name()
g1.show_age()
g1.show_gender()

Code Explanation:

Here, we are creating the object ‘g1’ for the ‘GrandChild’ class by using this command: 

g1 = GrandChild().

Once, we create the object, we go ahead and assign the values for name, age and gender.

Finally, we print out the values for name, age and gender.


Python Numpy

Numpy is a library in python. ‘Numpy’ stands for Numerical Python and is the core library for numeric and scientific computing.

It consists of multi-dimensional array objects and a collection of routines for processing those arrays.

Let’s see some examples on how to create single-dimensional and multi-dimensional arrays using bumpy:

This is how we can create a single-dimensional array:

Similarly, we can go ahead and create a multidimensional array:

If we want to initialize a numpy array, with only zeros, we can use the ‘zeros()’ method:

Now, let’s see how can we initialize a numpy array within a range:


Python Pandas:

Pandas” stands for Panel Data and is the core library for data manipulation and data analysis.

It consists of single and multi-dimensional data-structures for data-manipulation.

  • The single-dimensional data-structure is known as Series &
  • The multi-dimensional data-structure is known as Data-frame.

Data-frames are the bread and butter of any data-science project. So, if you want to be good at data science, then you definitely have to be good at working with dataframes.

Now, let’s see a few examples on how you can create a Series object and Dataframe in using Pandas.

We’d have to start off by importing the pandas library, by using ‘import pandas as pd’.

Then, to create a Series object we will use the command – “pd.Series()”. This would help us to create a series object from a list.

Now, similarly, let’s create a dataframe:

Here, we are creating a dataframe from a dictionary. As you see, the ‘keys’ in the dictionary have been represented as the column names in the dataframe and the ‘values’ go as the ‘rows’/’records’ in the dataframe.


Seaborn in Python:

Seaborn is library in python which is used for creating beautiful graphs and plots. It’s also very easy to learn and work with this library. Let’s see some examples of graphs using seaborn package.

We will start off by creating a line plot:

  1. import seaborn as sns
  2. from matplotlib import pyplot as plt
  3. fmri=sns.load_dataset(‘fmri’)
  4. fmri.head()
  1. sns.lineplot(x=”timepoint”,y=”signal”,data=fmri)
  2. plt.show()

Now, similarly, let’s go ahead and create a bar-plot:

  1. sns.barplot(x=”is_legendary”,y=”speed”,data=pokemon)
  2. plt.show()

Now, let’s go ahead and create a scatter-plot on top of the iris dataset:

  1. iris = pd.read_csv(‘iris.csv’)
  2. iris.head()
  1. sns.scatterplot(x=”Sepal.Length”,y=”Petal.length”,data=iris)
  2. plt.show()

That was all about Python, now let’s go the next language on our list: “Java”

Java Programming Language:

Java is also a free and open source, cross-platform compatible, object oriented programming language.

Let’s see how can we install java:

To install java we’d have to go to this site and download jdk: https://www.oracle.com/java/technologies/javase-downloads.html

Jdk stands for Java Development Kit and it provides all the tools to write, compile and execute java code.


Eclipse Java:

The most widely used IDE for Java is Eclipse. You can download eclipse from this site.


First Java Program:

package javatutorial;

public class JavaTutorial {

	public static void main(String[] args) {
		// TODO Auto-generated method stub

		System.out.println("This is sparta !");
		
		}

		
	}

Code Explanation:

We start off by creating a class called “JavaTutorial”. Since Java is an object oriented programming language, everything has to be inside a class. Once, we create our primary class, we go ahead and create our main function in it. Finally, in the main function, we just print out “This is sparta !”


If Statement in Java:

package javatutorial;

public class JavaTutorial {

	public static void main(String[] args) {
		// TODO Auto-generated method stub

int marks = 65;

if(marks<50) {
	System.out.println("You have failed the exam");

}
else if(marks>=50 && marks<60) {
	
	System.out.println("You have got D grade");
}
else if(marks>=60 && marks<75){
	System.out.println("You have got C grade");
} else if(marks>=75 && marks<90){
	System.out.println("You have got B grade");
			}

else if(marks>=90 && marks<100){
	System.out.println("You have got A grade");
			}
			else {
				System.out.println("Invalid score");
			}			
		
	}

Code Explanation:

In this we start off by assigning the value of 65 to “marks” variable. Then, we start off with the first if statement:

if(marks<50) {
	System.out.println("You have failed the exam");

}

In this first if statement, we are checking if the value of marks is less than 50, and if that evaluates to true, we go ahead and print out “You have failed the exam.”. If this condition fails, then we go ahead to the subsequent else if statement:

else if(marks>=50 && marks<60) {
	
	System.out.println("You have got D grade");
}

With this else if statement, we are checking if the value of marks is between 50 and 65. If this evaluates to true, we go ahead print out “You have got D grade”. If this fails as well, we go to the next else if statement:

else if(marks>=60 && marks<75){
	System.out.println("You have got C grade");
} 

With this else if statement, we are checking whether the marks are between 60 and 75 and if this evaluates to True, we print out “You have got C grade”. If this fails, we go to the next if statement:


else if(marks>=75 && marks<90){
	System.out.println("You have got B grade");
			}

Here, we are checking, if the marks are between 75 and 90 and if this evaluates to True, we print out “You have got B grade”. If this also fails, we again go to the next else if statement:

else if(marks>=90 && marks<100){
	System.out.println("You have got A grade");
			}

Here, we are checking, if the marks are between 90 and 100 and if this is true, we print out:

“You have got A grade”.

Finally, if all the above conditions fail, then we just use else statement and print out “Invalid Score”.


While Loop in Java:

package javatutorial;

public class JavaTutorial {

	public static void main(String[] args) {
		// TODO Auto-generated method stub

	int x=1;
	while(x<=4) {
		
		System.out.println(x);
		x++;
		
	}
	
	
	}			
		
	}

Code Explanation:

We start off by assigning the value of 1 to the variable x. Then, we start the while loop, where the condition is whether x is less than or equal to 4. If condition is evaluated to true, then we enter the loop and execute whatever is present in the loop.

Initially, value of x is 1 and since 1 is less than 4, we go inside the loop and print out the value 1 onto the console. Then, value of x is incremented to 2. Again we check if 2 is less than or equal to 4, since this as well evaluates to true, we again go inside the loop and print out 2. This process is repeated until we get: 1 2 3 4 as the result.


Pattern Problem in Java:

*

* *

* * *

* * * *

* * * * *

package javatutorial;

public class JavaTutorial {

	public static void main(String[] args) {
		// TODO Auto-generated method stub

int n =5;

for(int i=0;i<n;i++) {

	for(int j=0;j<=i;j++) {
		
		System.out.print("*");
	}
	System.out.println();
}
	
	
	}			
		
	}

Code Explanation:

We start off by initializing the value of variable n to 5. Then we have the outer for loop which starts at 0 and goes till 4. When value of i is 0 in outer for loop, we go inside the inner for loop and print  *. Then, value of i is incremented to 1. This time, we go inside the inner for loop and print * *. Similarly, the value of i incremented to 2, then we go inside the inner loop and print * * *. This goes on till value of i becomes 5.


C++ Programming:

C++ is a machine independent, compiled type, object oriented programming language. It also supports pointers which then leads to direct memory access. C++ was used in the development of operating systems such as Ubuntu and Windows. Not just operating systems, but it was the language to be used for the development of browsers such as chrome and firefox.

Basic Syntax of a C++ Program:

using namespace std;
#include <iostream>
int main(){
	cout<<"Hello World";
	return 0;
}

Code Explanation:

Here, we start off by including the library: iostream. This library provides us with all the input and output functions. Then, we have the main function. It has to be kept in mind that the program execution starts at main and ends at main. Inside the main function, we go ahead and print out “Hello world”.

This brings us to the end of this blog on top programming languages, where we learnt about Python, java and C++.

Avatar photo
Great Learning Team
Great Learning's Blog covers the latest developments and innovations in technology that can be leveraged to build rewarding careers. You'll find career guides, tech tutorials and industry news to keep yourself updated with the fast-changing world of tech and business.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top