GETTING STARTED WITH PYTHON

The vacations have started and its time to strike off few things from the wish list . One of them is learning Python. So today I have started learning python from Pluralsight.

Python is very much similar to other programming languages and it is considered as one of the easiest languages to learn. It is almost everywhere from game development to machine learning.

Python is really interesting and is quiet different from some other languages. We will start from its distinguished features, some which are as follows:

  • It uses indentation to separate one block of code from other instead of curly braces
  •  There is no need to declare the data type when declaring the variables
  • There isn’t any semi-colon at the end
  • There is nothing like multi-line comments in python. To add comments you need to write #in front of every line.
  • We write none instead of null to declare null variables
  • The boolean values true or false start with capital ‘T’ and ‘F’ i.e. ‘True’ and ‘False’
  • ‘and’ and ‘or’ in the statements are simply written in words instead of ampersand(&) or any other symbol

Let’s move to the basics of the programming and see how things work in Python.

Variables and Data Types:

As said earlier, Python doesn’t require to know the data type. It makes it easier to declare it. Another interesting thing about it is that we can add integers to floating numbers, which is not possible in another languages.

answer = 34
pi= 3.14
result =pi+answer # 37.14

Moving to the strings, in python, strings can be written using either single quotes or double quotes. Here strings supports a lot of methods like .capitalize(), .replace(“”, “”), .isalpha(), .isdigit(), .split(“”) and string format.

# “” represents the argument to be passed through the method.

Following are the examples of the strings with some methods:

# to show that single and double quotes doesn't matter
'My first Python blog'== "My first Python blog" 

#to capitalize the first letter
"first".capitalize()=="First"

# to replace a character with another (in this case 
# "y" with "i")
"Python".replace("y", "i") =="Pithon"

# to check that the string contains alphabets
"blog".isalpha()==True

# to check the string contain digits/numbers
"234".isdigit()==True

# to split the given string after a particular  
# character
"fish, tiger, lion".split(",")==["fish","lion","tiger"]

String Format:

name = "John"
devices = "mobiles"
"Hi, I am {0}. I sell {1}".format(name, devices)

# can also be written as:
f"Hi, I am John. I sell mobiles"

In case of boolean, like other languages it says either true or false. However, in python, we can convert boolean into integer 1 for true and 0 for false.

If-Else Statements:

Some important rules to remember in python:

  • Don’t forget indentation
  • if and else both end with a colon

Example

num = 45
if num:
  print ("The number is " +str(num))
else:
  print ("The number is not"+str(num))
# can also be written as:
num =45
print ("The number is " +str(num)) if num else  print ("The number is not"+str(num))

Maybe it looks complex but it is simple. The above block of code prints the given line only. str(num) is used to convert integer type into string type.

Lists:

In python, lists are used to store multiple objects under one variables. It is similar to arrays in other languages.

Example:

student_names =["Mark", "Bob", "Martha"]

# to add one more object
student_names.append(Jessica)
student_names ==["Mark", "Bob", "Martha", "Jessica"]

# to check if something is in the list or not
"Mark" in student_names == True

# to find the length of the list
len(student_names) ==4

# to delete any item in the list
del student_names[2] # deletes Martha in the list

# to slice the list
student_names[1:] ==["Bob", "Jessica"]
# it cuts the list after the given index
Loops:

In Python, most commonly used loop is’ for loop’ and ‘while loop’. Loops also have similar rules as if else statements.  There is a range function which is used in loops.  It can pass upto 3 arguments.

  • Only 1 argument represents the number of time the loop will be executed.
  • 2 arguments represents the starting and ending point of the iteration of the loop
  • Finally, 3 arguments tells the starting,  ending and number of time to skip in the loop

Example :

x =0
for index in range(10):
 x+=10
 print (The value of x is {0}". format(x))

Moreover,  ‘break’ and ‘continue’ are used in loops in order to get out of the loop or continue by skipping a block of code.

Dictionaries:

Dictionaries in python allow us to store key value pairs of any data. It is like the list where we can store more details.

Example:

# name, student_id, feedback are keys
# others are values
student= {
 "name":"Mark",
 "student_id":15163,
 "feedback": None
}

The thing to keep in mind is that it gives error when we try to get the details for any undefined key.

This is where exception handling comes in. It is done using ‘try’ and ‘except’ keywords.

Example:

try:
  last_name = student["last_name"]
except KeyError:
  print("Error finding last_name")

There may be different types error like KeyError,  Type Error etc.

 

 

DATA SCIENCE STUDENTS CHALLENGE

This Friday and Saturday were pretty busy. I participated in Data Science Students Challenge. Data Science Student Challenge is part of a global series of Hackathons. These events are organised by Microsoft and are designed to ignite a passion for the amazing things made possible by Data Science and to help students develop the skills necessary to harness the power of analytics.

The reason it has become an unforgettable moment is that our team SentimenTAL  ended in the top 6 teams at this event. It is a great achievement for all of us as we all have just started participating in these events.
My journey in this hackathon was about to end when three teams refused to take me as a team member because I am a first year student. I was about to go home but I gave a last shot and asked Brendan whether he has a team or not and he said no. Then I asked him can we team up together and he said yes and I was very happy at that moment. In a similar way, we met Nicholas and Shantanu and the hackathon began for us.

The challenge was divided into three categories, which includes exploring the data-set provided by TAL and identifying the key indicators and self harm risks in policy applicants,  create innovative solutions to identify and support customers who are at risk of self-harm and  accurately predict claims propensity at policy application
stage more broadly. It was not an easy task.

Idea was to use the customer’s social media account to analyse their sentiments according to their tweets/posts and combine it with the predicting model designed using azure machine learning, in order to predict the probability of depression and stress of that customers.

We started with merging the data into one sheet but we found it very hard due to duplicacy of data. Somehow, with the help of special mentors we manged to do it and prepare a predicting model, which can predict the chances of suicide with some information about the customer on the basis of historical data. We add it to excel sheet using excel add-ins and it does the same thing but in excel sheet and with the click of one predict button.

Brendon, Shantanu and Nicholas come up with the model of sentimental analysis and the the Power BI visualization which uses the text data and predict the negative and positive sentiments. We managed to do all the things with the 24 hour of hard-work and team work.

We presented it the judges in the first round but the moment of the day for us was yet to come. We all gave our best shot and hoped for the best. The best moment was when our name was announced among top 6 finalist.  For me, it was  invaluable moment. We gave our best shot in the final presentation.

The time when they handed over that big cheque of $1000 to our team is unforgettable.

For some of us it was a thing to strike out of the bucket list and for some it was a proudful moment but for me it was a moment to prove that no one should under-estimate someone because that person is new. That person may have more capability than you. We, the team of underdogs, have proved this. 

Thanks to all my team-mates!!!

IMPLEMENTING EQUALITY FOR REFERENCE TYPE

In the continuation of last post, now we are going to discuss overriding the equality for reference types.

Why to implement equality for reference type?

The two main situations where it is helpful to override equality for reference type are:

  • In case of a class which wraps the strings.
  • In case of classes which represents mathematical objects (e.g. Vectors).

In these situations one would prefer to check for value equality not reference equality. Hence it is useful to implement or override the equality.

How to implement equality?

In case of reference type, it is a bit different as compare to value type.

First of all, the equality is implemented for the base type.
  • To do so, commence with overriding object.Equals and replace it with value semantics.
  • Remember to do couple of more checks since it is an object which expects a parameter to pass, so it is important to check for null parameter.
  • Then have a check for ReferenceEquals.
  • Finally, check for the type of object because if types of object are unequal, it will never return true.
Then, the equality is implemented in the derived type.
  • First start with overriding base class and check what the base type returns.
  • Afterwards , deal with GetHashCode.
  • At last we need to overload equality and inequality operator.
***Points to remember:
  • Always seal the derived class as in this way there will be no issue with inheritance.
  • It is important to overload equality operator, otherwise it can lead to bug.

IMPLEMENTING EQUALITY FOR VALUE TYPES

In this post we are going to discuss how to implement equality for value types.

Why to implement equality for value type?

There are following three main reasons why one needs to override equality for value types:

  • To use equality reporter for value type as the equality operator doesn’t work for value types until it is overloaded.
  • To improve the poor performance due to boxing and reflection of the default equality comparison
  • To change the meaning of equality in order to give different meaning from default value type (it is least used situation)

How to implement equality?

  • First of all IEqualitable<T> interface is implemented. We know that == checks for value equality for strings. In this case too, it will check for value equality even for enums.
  • The next step is to override objects.Equals() method. However this method is still less efficient but we can’t do much about it.
  • Then implement equality operator. To do this only delegate the call to IEquatable<T> method.
  • Int he same way as above implement the inequality operator.
  • Then finally implement GetHashCode() in order to allow the type to be used as a key in collections that internally use hash tables.

 

At the end one would surely prefer to hit both the Equals methods and the GetHashCode override.

One more fact to know: In order to practice good coding try to follow all steps.

**Remember that implement equality and overriding equality means implementing some custom equality behaviors for value types that overrides what would otherwise have been.

C# EQUALITY OPERATOR

In this post, we are going to discuss the use of equality operator(==).

Equality for Integers, Strings, Buttons and Tuples

Integers

For integers equality operator in C# and object.Equals method do same thing i.e. check the given integers for value equality.

Strings

In case of strings, if we check for reference equality, the result will be false (because both are  different instances) whereas in case of value equality and the Equals method it is true.  String overloads the equality operator to make sure that it does the same thing as the Equals method.

Buttons

If we use equals method or equality operator for buttons in C#, the result will be false because both ways check for reference equality in both situations. It only checks whether both references are pointing to the same memory location or not.

Tuples

A tuple is a data structure that has a specific number and sequence of elements. When we check equality for tuples using both methods a surprising thing happens. Equality operator and Equals method gives opposite results. This is because tuple overrides object.Equal to provide value equality semantics.

Comparing == operator and Object.Equals()

For primitive numeric types both method and operator checks for value equality. Whereas for reference type they check for reference equality by default unless the code has been modified by overloading the operator or by overriding the method.

== Operator with Inheritance and Generics

Inheritance

If we change the variable declaration to object type and then check for equality using both operator and method, the output will be different in both cases. The reason for this is that for non-virtual methods or operators the decision of the method to invoke has to be made at compile time. Since, the variable declaration has been changed to object type, the compiler emits the code which checks for equality and because no equality operator overloads for object, the compiler will always check for reference equality. Hence the output will be false.

Generics

When working with generics, always avoid the use of equality operator. The main reason is that when we use equality operator to compare the values it gives an error while building which says that == operator cannot be applied to type T operands (which is passed as parameter for generic method). This is because T  can be anything and hence there is no guarantee for equality operator.

Whereas when we use the Equals method, the static Equals method internally calls the virtual Equals method and hence correct override will be invoked during the runtime. This proves that the use of method is more beneficiary while dealing with generics.

 

 

The fact to know that equals to(==) and not equals to(!=) operator works similarly except the fact that their roles are completely opposite to each other.

 

 

EQUALITY IN .NET

In this post, we are going to discuss how .NET deals with the issues described in previous post.

The Virtual Object.Equals() Method

To begin discussing about .NET, first we need to know that .NET framework has no concept of operators (like ==).  Here we mostly use objects.Equals. However, the noticeable thing about objects.Equals is that its implementation evaluates reference equality and thus it only checks whether or not the two variables refer to same instance.

Let us suppose we have created a base class named animals and DomesticAnimals is a derived class. Now consider the following code:

static void Main (string[] args)
{
  Animals lion = new Animals("lion");
  Animals lion2 = new Animals("lion");
  Animals tiger = new Animals("tiger");

  Console.WriteLine(lion.Equals(tiger));
  Console.WriteLine(lion.Equals(lion2));
 }

The first reaction is that output of first console.WriteLine is false and of second one is true. However, the fact is that both outputs are false. This is because object.Equals doesn’t care about that the data in two is same or not. The only thing that matters is that they both are different instances.

Apart from the virtual Equals Method, .NET framework defines a couple of other ways that enables checking for natural equality ona type . These are

  • two static methods defied on objects, Equals and RefenceEquals
  • Interface IEquatable of <T>

Static Equals() Method

When we use virtual Equals Method, the only problem is when we pass two parameters and among them the first one is null. After running it the output will always be false irrespective of the second parameter.

This is where Static Equals Method is useful. It does exactly same work as the virtual method except that it checks nulls first.  In particular, because the static method calls the virtual method, if you override the virtual Equals method your override will automatically be picked up by the static method. That’s important, because you want these two methods to behave consistently.

RefernceEquals() Method

ReferenceEquals does a different work from the two Equals methods. Itis useful in those particular cases, where you want to determine whether two variables refer to the same instance. Both Equals methods, usually compare references for reference types, but they’re not guaranteed to do so, because the virtual method can be overridden to compare values. So ReferenceEquals will give the same result as Equals for types that don’t have Equals overrides.

IEquatable <T> Interface

The generic IEquatable of <T> interface exists to solve a slightly different problem with Equals.Object. Equals method takes an object as a parameter. This is, of course, the only type of parameter that’s possible if you want object.Equals to work for all types. But object is a reference type and that means that if you want to pass any value type as an argument, the value type will end up getting boxed, which will give a performance hit. Having an object as an argument means there’s no type safety.

 

WHY IS EQUALITY SO HARD?

In the continuation of C#, we are going to start new topic which is about the proper use of equality and comparison in C#.

Today, we are going to explore the reasons which make performing equality in C# is difficult. There are following four main reasons for this:

  • Reference vs Value Equality
  • Multiple ways to compare values
  • Accuracy (specially with floating points)
  • Conflict with Object Orientation Programming
Referencing vs Value Equality

Reference equality means ” do the two variables refer to the same location in memory?”  even if their value is same. Conversely, Value equality means “do the two variables have same value?” even if they are stored in different locations.

In C# or .NET equality refers to referencing equality for some and Value Equality for others. Hence it is difficulty to predict the function of == (operator to check equality).

For example

static void Main(strings[] arg)
{
 Button button1 = new Button();
 button1.text = "Click me now!";

 Button button2 = new Button();
 button2.text = "Click me now!";

 Console.WriteLine(button1==button2);
}

The output for this will be False because C# and .NET check referencing equality for buttons and button1 and button2 are stored in different locations.

static void Main(strings[] arg)
{
string str1 = "Click me now!";
string str2 = "Click me now!";


 Console.WriteLine(str1 == str2);
}

In this case, the output will be true because now C# compiler refers to value equality.

This problem is only for reference types, whereas in case of unboxed value types like int or float,  the value directly contains the value, so there is no need of referencing equality.

Multiple Ways to Compare Values

The other problem is that there are many ways to check the equality. Sometimes it depends on the developers how much precision they they want while checking the equality.

For example let us suppose we take two strings “chocolate cake” and “chocolate cake” . In a generic way both are equal as both contain same characters. However, if  we change one into title case (“Chocolate Cake” ). Now it is hard to say. It depends on the context of chocolate cake. If it is used as the name of recipe then it case sensitivity does not matter but if it is a password then case sensitivity values.

Hence, it depends on the developers how they write code, they can avoid case sensitivity if they want. The same thing goes with the white spacing.

Accuracy (specially with floating points)

The floating type values can loose precision, which would be another error in equality.

For example here are two numbers 43.0000000 and 43.0000001.  It is clear that two numbers are not equal. 

static void Main(string[] args)
 {
   float Num = 43.0000000f;
   float nearlyEqualsNum = 43.0000001f;
   Console.WriteLine(Num == nearlyEqualsNum);
 }

But when the above code is executed, the output will be true. This is because computer can store numbers with certain level of accuracy and the float type cannot store enough significant digits to distinguish these two particular numbers.

Conflict with Object Orientation Programming

The final error is that there is a conflict between Equality comparison, Type Safety and good Object Oriented Programming (OOP) practices.

For instance let us suppose we have created a base class called recipe which describes list of recipes and a derived class named Desserts, which tells about list of recipes of desserts. If we wanted Recipes to declare that Recipes instances know how to check whether they are equal to other Recipes instances, we might  implement the interface, IEquatable of <Recipes >. This requires it to implement an Equals method, which takes a Recipes instance as a parameter. If we want Desserts to also declare that Desserts instances know how to check whether they are equal to other instances, we’d probably have it implement IEquatable of <Dessert>. That means it’ll implement a similar Equals method, but one which takes a Dessert instance as a parameter. Thus is a problem.  In a well-designed OOP code, Dessert Equals implementation should override Recipes’ Equals implementation.However, Desserts’ Equals method has a different argument type from Recipes’ interface method, Thus it will not override it.The object.Equals method is the most basic way most types implement equality and in order to deal ith the problem it loses type safety.This method takes an object as a parameter, which means it’s not type safe, but it will work correctly with inheritance. 

 

C# OBJECT ORIENTED PROGRAMMING

Today we will discuss the concepts and syntax for object- oriented programming in C# which will include Encapsulation, Inheritance and polymorphism.

An object is a basic run-time entity of an object oriented system which may represent anything that a program can handle.

ABSTRACTION:  It is a keyword used to represent an abstract class or method. Abstraction means putting all the necessary variables and methods in a class that are necessary. It allows you to focus on what the object does instead of how it does it.

A simpler way to understand abstraction is to think it as the most common information which is required everywhere as it is the process of hiding the working style of an object, and showing the information of an object in an understandable manner.

ENCAPSULATION

Encapsulation means to wrap up data member and a method together into single class. It is the primary pillar of  object- oriented programming (OOP) .It helps to hide the complexity of program. It enables a programmer to implement a required level of abstraction. It can be achieved with the help of access specifiers like public, private, protected and internal.

INHERITANCE

Inheritance means a class having the property of another class i.e. it makes creating and maintaining application easier. The syntax for inheritance is to use a colon(:) after the name of class and then mention base class.

<access-specifier> class <base_class>
{
   ...
}
class <derived_class> : <base_class>
{
   ...
}
POLYMORPHISM

Poly means multiple and morphism means forms. Hence Polymorphism means one function behaving as different forms. A good example of polymorphism in real world is a person behaves the son in a house at the same time that the person behaves an employee in an office.

It can either be static or dynamic. Two ways to implement static polymorphism are

  • Function overloading
  • Operator overloading

. Two ways to implement static polymorphism are

  • Abstract classes
  • Virtual functions

C#: CONTROL FLOW

Today, we are going to look at Control Flow in a C# application. It particularly includes branching, looping and to jump to various points in an execution path.

BRANCHING

Branching means to execute code in one of the multiple directions.  This can be achieved in following ways:

  • IF STATEMENT:  It executes the code only if the statement is true. It takes a boolean expression as a condition

Syntax:

  if (condition )
{
//statement;
}
  • IF ELSE STATEMENT: If the statement in if block is false only then else block will be executed.

Syntax:

if (condition )
{
//statement;
}
else
{
//statement;
}
  • ELSE IF STATEMENT: It is another kind of if else statement. In it firstly if block is checked, then else if and if both are false,  then it will execute else block.

Syntax:

if ( condition)
{
//statement;
}
else if( condition)
{
//statement;
}
else
{
//statement;
}

Number of else if statements can vary according to the complexity of program.

SWITCHING

The switch statement is used to branch the execution of program to a set of statements that are inside of a case label, using case keyword. The switch statement checks each case according to their condition and execute the one which is true. At the end of each case break statement is used to jump out of the switch block.

Syntax:

switch (variable)
{
case 1:
//statement;
break;
case 2:
//statement;
break;
default:
//statement;
break;
}
ITERATING OR LOOPING

It is used to execute the block of code repeatedly or we can say looping over the code.

  • WHILE LOOP:  The block of code inside while loop runs only if the condition is true  until the condition fails.

Syntax:

variable;
while ( condition )
{
//statement;
}
  • DO-WHILE LOOP: This loop is executed at least once and then it checks the condition. If it is false, it jumps to next block of code.

Syntax:

variable;
do
{
//statement;
}
while ( condition );
  • FOR LOOP: It is similar to while loop. The only difference is that unlike while statement, the variable which initialize and the iteration statement goes with with the  condition.

Syntax:

for( initialization; condition; iteration)
{
//statement;
}
  • FOREACH LOOP:  It is mostly used to loop through a collection. Most of the time an array is used to give that collection.

Syntax:

// collection of datatype values in variable
foreach (condition)
{
//statement;
}
JUMPING AND THROWING

There are many ways to jump out of the loop unconditionally.

  • BREAK: It is not only used inside switch statement but also to break the loop.
  • CONTINUE: It is similar to break. However instead of jumping outside the loop, it is used to skip any block of code and continue to the next iteration.
  • GOTO: It is used to jump to another piece of code that is marked by the label. However this is the least used and is mostly avoided by programmers.
  • RETURN: As we know from the earlier posts it is used to return the string or integer of some kind.
  • THROW: the throw keyword is used to raise the exceptions. An exception is a signal to change normal control flow and should only be thrown in exceptional conditions. When  an exception is thrown, you are throwing an object, this is why we say exception handling is type safe because every exception with C# is going to be of a known type, and the compiler can help you handle exceptions. We also say that working with exceptions is structured, because you can set up blocks of code to handle exceptions, meaning you can structure your program to anticipate certain exceptions, and try to recover from those error conditions.
HANDLING

IN C# we can handle the exception using try and get blocks. Use try/catch blocks around code that can potentially generate an exception, and use a finally block to clean up resources, if necessary. This way, the try statement generates the exception, the catch statement handles the exception, and the finally statement closes or reallocates resources whether or not an exception occurs. In catch blocks, always order exceptions from the most specific to the least specific. This technique handles the specific exception before it is passed to a more general catch block.

FINALLY

Finally block is always executed whether there is an exception or not. However it is optional and its use completely depends on developer. It is a good place to finalize the code.

 

C#: METHODS, FIELDS ,EVENTS AND PROPERTIES

Today, we will discuss some of the familiar topics like method and introduce to the new topics:

METHODS: 

In the post C# Program Structure, we confer about (main) method. We know that

  •   method is invoked to execute the code
  •  it describes behavior of the program
  • it has access modifier (private or public)

Now, we will learn a bit more about it. A method has following components:

  • Access modifier (discussed earlier)
  • Return Type : A method may or may not return a value. When it does not return a value, we use return type void  otherwise return keyword is used to return the value.
  • Method name: It is a unique and case sensitive identifier  of a method.
  • Parameter list: It is an optional component enclose in parentheses, used to pass data from method.
  • Method Body: It is a set of instructions required to complete the activity.

These method name and parameters together are called method signature. Every method must have unique method signature as it allow C# compiler to distinguish between various methods.  Following is an example of method:

FIELDS AND PROPERTIES:

FIELD: A variable declared inside a class or struct is defined by fields. Fields can be marked as public, private, protected, internal or optionally as static.

PROPERTY: A property is similar to field except that a property has a special syntax to control what happens when someone reads the data. These are get and set accessors. These are like methods and are contained inside property declaration. Get is used to return the property value and set is used to assign the value.

EVENTS:

Event is another member that we can have in class. It gives a way for object to signal state change. A good example of event is in Graphical User Interface in which it notifies when user does something with controls.

In order understand events,first we need to understand Delegates.

DELEGATES:

Delegate keyword is used for a variable to reference a method. A variable of this type points to method and takes a string parameter.

Syntax for delegate declaration is:

delegate <return type> <delegate-name> <parameter list>

A delegate object must be created with the new keyword and be associated with a particular method. One delegate can hold reference to more than one methods. A way it is done is using += operation.

EVENTS REVISITED:

Now as we have discussed about delegates, it is very easy to understand events because these are based on and use delegates. While using events, we can get rid of multiple number of lines of delegate.