Tuesday, December 26, 2017

Object Oriented Approach in Python

So Classes and Why do we need them

In Java it require that you write code in inside class but in Python it does not required.you can write a code inside a class but you don't have to.In Python we define a class using class keyword similar to define a function using def keyword.

Let's take an complete object-oriented example:

classess.py

students =[]

class Student:

      school_name = "Abhinaw Demo"
     
      def __init__(self,name,student_id=1):
              self.name=name
               self.student_id=student_id
                students.append(self)

      def __str__(self):
            return "Student "+ self.name

     def get_name(self):
            return self.name.capitalize()
    
      def get_school_name(self):
             return self.school_name

class NewSchoolStudent(Student):

    school_name="Inheritance Abhinaw Demo"
 
    def get_school_name(self):
          return "This is inheritance"

     def get_name(self):
         original_value= supper().get_name()
          return original_value + "New School"

abhinaw= NewSchoolStudent("Abhinaw")
print(abhinaw.get_school_name())
print(abhinaw.get_name())

This demo code includes classes,adding methods to our classes,Constructor,Instance and Class Attributes and Inheritance and Polymorphism.













Lambda Functions in Python

So Lambda Functions are just an anonymous function.they are very simple just saves your space and time.they are useful in case of higher  order function.Lets take an example:

def double(a):
        return a*2

Convert to Lambda Function

double = lambda a: a*2

Friday, December 22, 2017

Generator Functions - Yield Python

So Yield is a keyword.first let's take an example.

student = []

def read_file():
        try:
              f=open("students.txt","r")
               for student in read_students(f):
                      students.append(student)
               f.close()
         except Exception:
                print("Could not read file")

def read_students(f):
       for line in f:
              yield line

read_file()
print(students)

So what I have done is created a single function read_students and what it does
it iterated over the file and yield the single line from that file.

Opening,Reading and Writing Files Python

Let's save our data in a file and read from that file again when we re-open our app.
So let's take an example:

Let's take an example:

students =[]

def get_students_titlecase():
       students_titlecase = []
        for student in students:
           students_titlecase .append( student["name"].title())

def print_students_titlecase():
       students_titlecase = get_students_titlecase()
       print(students_titlecase)

def add_student(name,student_id=1):
        student ={"name:name", "student_id": student_id}
         students.append(student)

def save_file(student):
       try:
            f=open("students.txt","a")
            f.write(student + "\n")
             f.close()
       except Exception:
             print("Could not save")
       
def read_file():
       try:
             f=open("students.txt","r")
              for student in f.readlines():
                      add_student(student)
                f.close()
         except Exception:
              print("Could not read file")

read_file()
print_students_titlecase()

student_name=input("Enter student name: ")
student_id= input("Enter student ID: ")

add_student(student_name,student_id)
save_file(student_name)

where a= append some text
             r = reading text file

So when you run the program.the output will be something like this

Output:

Could not read file
[]
Enter student name:

Nested Functions and Closures in Python

Let's take an example:

def get_students():
      
       students=["Abhinaw","Aman"]

def get_students_titlecase():

       students_titlecase = []

       for student in students:
              students_titlecase.append(student.title())
     
        return student_titlecase

students_titlecase_names=get_students_titlecase()

print(students_titlecase_names)

This is called Nested function and basically the inner function can access the outer students So this is called closures.

Create a simple python console app

Let's create an app where user will provide the student name and Student I'd from the console.

eg: student.py

students =[]

def get_students_titlecase():
       students_titlecase = []
        for student in students:
           students_titlecase = student["name"].title()

def print_students_titlecase():
       students_titlecase = get_students_titlecase()
       print(students_titlecase)

def add_student(name,student_id=1):
        student ={"name:name", "student_id": student_id}
         students.append(student)

student_list = get_students_titlecase()

student_name=input("Enter student name: ")
student_id= input("Enter student ID: ")

add_student(student_name,student_id)
print_students_titlecase()

So in console you have to something like this and output will be

Enter student name: Abhinaw
Enter student ID:3455
Abhinaw

this is very simple Python app taking console input and also we can modify the program.

Thursday, December 21, 2017

Functions Arguments in Python

            Functions Arguments

So argument is parameters where you can  provide the values to functions and also useful in case you don't have to make variable global.So let's modify our existing code for input argument.

functions.py :

students = []

def get_students_titlecase():
        student_titlecase = []
        for student in students:
                students_titlecase = student.title()
          return students_titlecase

def print_students_titlecase():
       students_titlecase = get_students_titlecase()
       print(students_titlecase)

def add_student(name) :
        students.append(name)

student_list = get_students_titlecase()

add_student("Abhinaw")

So now modify our add_student method:

def add_student(name,student_id=332)

        students.append(name)

So here you will notice student_id=332 is basically a default or optional student_id if any user does not provide student_id then it will add the value automatically but if any user provides then in that case it will be overridden by the userinput value.

Now let's add student Dictionaries to our add_student method:

def add_student(name , student_id=222)
        student = {"name:" name, "student_id", student_id}
       students.append(student)

So call this function like this

add_student(name="Abhinaw" , student_id=14)

In Python there can be multiple variable arguments such as inbuild print function.

print("hello", "World", 34, None , "Wow')

you must have question here like how come it possible let me create our own function just to cater above.

def var_args(name, *args)
        print(name)
         print(args)

just to call the function

var_args("Abhine","Android Developer",None, True)

you can add any number of argument.

There is also a concept called kwargs.
let's have a look.

def var_args(name,**kwargs):
print(name)
print(kwargs["description"],kwrgs["feedback"])

var_args("Abhinaw" ,description="Loves Android", feedback=None,androidcodingworld_subscriber=True)

it is called kwargs argument and defined with **kwrgs.So it is not a list it is Dictionaries thats where it differs from above example.

basically it was an example of variable arguments you can add as much as you can in the form of list or can also make it  Dictionaries.


Functions in Python

                     Functions

A functions is a block organized and re-usable code and use to perform certain action.Pyhthon comes with lot of built in functions such as

print("hello world")

str(3) == "3"

int("5") == 15

username = input("Enter the user's name: ")

So now let's create our own functions.So for this you can use PyCharm editor I will provide the code here and you can run it directly using pycharm.

functions.py :

students = []

def get_students_titlecase():
        student_titlecase = []
        for student in students:
                students_titlecase = student.title()
          return students_titlecase

def print_students_titlecase():
       students_titlecase = []
       for student in students:
       students_titlecase=student.title()
       print(students_titlecase)

def add_student(name) :
        students.append(name)

student_list = get_students_titlecase()

add_student("Abhinaw")

So actually I have by knowingly added some repeated code in functions which can be removed.Lets see

def print_students_titlecase():
       students_titlecase = get_students_titlecase()
       print(students_titlecase)

So if you write functions for single responsibility then it will be very helpful to write Unit Testing cases and code will be organized too.

Other Data Types in Python

We went over some data types such as integers,strings,floats.ther are more types in python.i will give breife over view then.

For numbers we have gone through integers and float.we also have type called complex which denotes complex numbers.So other types are

complex
long # only in Python 2
bytes and bytearray

tuple = (3, 5, 1 ,"Abhinaw") similar to list but immutable.cannot change there values.

set and frozenset

set([3,2,3,1,5]) == (1,2,3,4,5)

So I tried to represent all data types but remember there are many things which I have not mentioned but in my next post .I will create Python app and provide source code.

Friday, December 15, 2017

Exceptions in Python

Exceptions are event occurred during your program execution.that normally cause your program to stop actually.it usually means some error has been encountered.And your program simply does not know how to deal with it.So take an example of exception code.

eg:

student = {

       "name": "Abhinaw"
       "student_id": 123
       "feedback": None
}

last_name = student["last_name"]

Output:
KeyError: 'last_name'

To handle this scenario grecfully.we use try and except blog to handle this code.
So let's take another example with exception handled.

eg:
student = {

       "name": "Abhinaw"
       "student_id": 123
       "feedback": None
}

try:
      last_name = student["last_name"]
except KeyError:
      print("Some error occurred")

print("this code executed!!!!")

Output:

Some error occurred
This code executed!!!

Note both try and except block can have more than one line of code.
There can be many error occurred  like TypeError.Can be many other too.

eg:
student = {

       "name": "Abhinaw"
       "student_id": 123
       "feedback": None
}

student["last_name"] = "Tripathi"

try:
      last_name = student["last_name"]
      number_last_name = 3 + last_name
except KeyError:
      print("Some error occurred")

print("this code executed!!!!")

Output:

TypeError unsupported operand types .if you have noticed  this code executed! does not execute because we are only catching KeyError.So let's take another example.

eg:

student = {

       "name": "Abhinaw"
       "student_id": 123
       "feedback": None
}

student["last_name"] = "Tripathi"

try:
      last_name = student["last_name"]
      number_last_name = 3 + last_name
except KeyError:
      print("Some error occurred")
except TypeError:
      print("I can add multiple together")

print("this code executed!!!!")

Output:

I can add multiple together
This code executed!!!

you can also generic exception like

eg:
student = {

       "name": "Abhinaw"
       "student_id": 123
       "feedback": None
}

student["last_name"] = "Tripathi"

try:
      last_name = student["last_name"]
      number_last_name = 3 + last_name
except Exception:
      print("Some error occurred")

print("this code executed!!!!")

And you can also add finally at the end of except block.

Python Dictionaris

So Dictionary allows me to store key-value pair of any data very easily.if you have used JSON in the past then you will be very familiar with the Dictionary in Python.

for example:

student = {

        "name": "Abhinaw"
        "student_id": 20042343
        "feedback": None
}

this is what dictionary looks like in Python.So it has key and value And the value can be of any type.Dictionaries are very helpfull in case ,when you want to store some kind of structured data.

   List of Dictionaries

all_student = [

    {"name:" "Abhinaw" ,"student_id": 20042343},
     {"name:" "Rajat" ,"student_id": 20042345},
{"name:"Gaurav" ,"student_id": 20042893},

]

      Dictionary Data

student["name"] == "Abhinaw"

suppose if you are using key which does not exists in the Dictionary then it will raise an exception called "KeyError" like

student["last_name"] == KeyError

but you can set the default value if key is not present like this

student.get("last_name", "Unknown") == "Unknown".

in case you do not find the last_name in the Dictionary.

if you want all keys in the Dictionary you can simply do like this

student.keys() =["name" ,"student_id" , "feedback"]

student.values() = ["Abhinaw" , 20042343,None]

Similarly you can delete like this

student["name"] = "James"
del student["name"]

While Loops in Python

So while loop is theoretically same like other programming language.take an example in Python.

x =0

while x < 10:

        print("Count is {0}".format(x))
         x+=1

        Infinite Loops

num =10

while True:
       if num == 42:
        break

   print("Hello World")

Wednesday, December 13, 2017

break and continue in Python

So break and continue theoretically same as other programming language.taking a small example to demonstrate both in Python.

break example:

student_names = ["james" ,"Mark", "Abhinaw", "Arudhra" ,"Rajat", "Gaurav"]

for name in student_names:
       if name == "Arudhra":
             print("Found him!" + name)
              break
         print("Currently testing " + name)

Output:

Currently testing james
Currently testing Marks
Currently testing Abhinaw
Found her! Arudhra

continue example:

student_names = ["james" ,"Mark", "Abhinaw", "Arudhra" ,"Rajat", "Gaurav"]

for name in student_names:
       if name == "Arudhra":
             print("Found him!" + name)
              continue
         print("Currently testing " + name)

Output:

Currently testing james
Currently testing Marks
Currently testing Abhinaw
Currently testing Rajat
Currently testing Gaurav

we see that except for Arudhra .it print all names.

Loops in Python

Loops: let's take a example of list.

eg: students_names = ["Abhinaw", "Aman", "Ashish", "Himanshu']

if you want to print single element then

print(student_names[0])

is fine but print every element of list we need some kind of loop.

There are two main loops in Python for loop and while loop.lets have a for loop example.

for name in student_names:

       print("Students name is {0}" .format(name))

So it will print all the elements of list student_names.Simply name is a variable.

other programming for loop:

for(var i=0; I<someArray.length; I++)
{
   var element=someArray[i];
   console.log(element);
}

However this is not the case with the Python.this is not the way Python for loop works.pyhton does hide many things.it automatically assumes that you want to start from the first element from the list and also it knows when to stop.Pyhton does not have foreach loop.

        range function

let's have an example.

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

output will be

The value of a is 10
The value of a is 20
The value of a is 30
The value of a is 40
The value of a is 50
The value of a is 60
The value of a is 70
The value of a is 80
The value of a is 90
The value of a is 100

So whats the range function do.basically it takes a range value and kind of converts  it in list.it will execute 10 times.So in this case the index will be the element of the list.So if you don't want to start your for loop to start from 0 then range function also supports two argument like this

range(5,10)
in this case index value will be

[5,6,7,8,9]

And also if you want to increment the index value by 2 every time it execute it also supports such as

range(5,10,2)

in this case 2 denots the increment.So our list will be

[5,7,9]

you can also exit the loop in between based on some logic using break and continue.

Tuesday, December 12, 2017

Lists in Python

So Lists,some time we want to form multiple objects under a single variable name.To define a list in python.you have to do something like this.

eg:
student_names = []

simple you have created empty student names list.if you want to add some student names then simple replace empty brackets like this

student_names = ["Abhinaw", "Rajat', "Gaurav", "Babli"]

now our list has 4 string elements.In order to access the names from list we use something called index staring from 0.
eg:

student_names[0] == "Abhinaw"
student_names[2] == "Gaurav"

So suppose you want to get last element from the list.then you have to do something like this.

student_names[-1] == "Babli"

So actually this gives the first element from right side of the list.In Python just remember there is no such thing negative zero.

                  List Functions

suppose you want add some names to list then you have to do like this.

eg:

student_names = ["Abhinaw", "rajat", "Gaurav"]

student_names[3] = "Babli" # No can do!

student_names.append("Babli") # Add to the  end

So now list will be:

student_names == ["Abhinaw", "rajat", "Gaurav", "Babli"]

*if you want to check the name already exist or not

eg:

"Abhinaw" in student_names == True

# Abhinaw is still there

*check how many elements in the list
eg:

len(student_list) == 4

Note: if you have noticed in Python we have never tell that it is list of string.So this is added advantage with the Python over other programming language.

    Delete element from List

eg:

students_names = ["abhinaw", "rajat", "Gaurav"]

del student_names[2]

this will delete 2nd element from list
which is "Gaurav" .Now the whole list will be going to shift after this operation.

                       List Slicing

student_names = ["Mark" ,"Katarina" ,"Homer"]

let say we want to ignore the first element which is "Mark" and get all other.

student_names[1:] == ["Katarina", "Homer"]

student_names[1:-1] == ["Katarina"]
Note this will not modify the list.list will be same it is just a temporary ignoring certain elements.

there are many more operations you can perform like reverse and pop etc.




If Statements in Python

If Statement is very simple in Python.Let me give you an example.

number = 5
if number == 5:
       print("Number is 5")
else:
       print("Number is NOT 5")

Remember one thing Python uses indentation rather than curly braces for any code blocks.notice that there is colon(:) at if and else both.this is required in python.we use == equal sign to check the  equality in Python.

in Python there is a concept of "Truthy and Falsy Values" for example.

number=5
if number:
 
     print("Number is defined and truthy")

text = "Python"
if text:
   
    print("Text is defined and truthy")

In many other programming language you have to check the length of the variable if it is value greater or less than zero but in Python you could just write like above.

okay in case of Boolean and None:it also has Truthy and Falsy Values.
eg:

pyhton_course = True

if python_course :

# Not python_course == True

    print("this will execute")

aliens_found = None

if aliens_found :
    print("This will NOT execute")

you can also set the same thing for None like I have done above.

               Not If

number = 5

if number !=5 :
      print("this will not execute")

python_course = True

if not python_course:

     print("this will also not excute")

Multiple If Conditions

number = 3

python_course = True

if number  == 3 and python_course:
   
    print("this will execute")

if number == 17 or python_course :

   print("this will also execute")

Note: in Python there is no && or || for and  and or like in other programming language.

           Ternary If Statements

a = 1
b = 2

"bigger" if a>b else "smaller"

This is called Ternary if Statement in Python.

Boolean and None in Python

As you know about boolean in other programming language. it is same in python too but with small differences .boolean can be  a true or false value.can be declared as either of them.

eg:

python_course = True
java_course = False

Simply type a name and assign a value "True" or False .

if you have noticed only difference with other programming language is that it starts with Capital letter T for True and Capital letter F for False .interestingly you can convert Boolean value to int and it will give you values 1 and 0 in case of True and False like below.

eg:

int(python_course) == 1
int (java_course) == 0
str(python_course) == "True"

And for string it will simply give textual representation "True" or "False".

Now coming to None: it is similar to null like other programming languages.

eg:

aliens_found = None

I find it useful as a place holder variable.Something that I will use later.However there is difference between variable you have defined None and other the  variable not defined at all.
Simply type k in idle and idle will tell you that k has not been defined but if I assign None to k then it will not give any result but normal for None and also it will not cause any error to show either.So None is called None type.

Monday, December 11, 2017

Strings in Python

We use string to represent text.by default it's Unicode text in Python 3 but ASCII text in Python 2.And this is one of  the big advantage in Python 3 by the way.Strings can be defined like below:

eg:

'hello world' == "Hello World" == " " "Hello World " " "

There is absolutely no difference which one you use.you can write multi-line string using 3 double quotes but this string  is not going to assign to any variable.it just to be sitting there as a comment.your editor will recognize it.it is a comment.Definning String is very simple just type a variable name and assign it a textual value  and done.
String in Python supports lot of utility methods.some of them are:

eg:

"hello" .capitalize() == "Hello"
"hello".replace("e" , "a") == "hallo"
"hello" .isalpha() == True
"123".isdigit() == true # Usefully when converting to int

"some ,CSV,values" .split(",") == ["Some" , "CSV" , "Values"]

String Format Function-

normally, use when you want to replace existing text in a given string with a variable value.

For example:

name = "pyhthonBO"
machine = "HAL"

Let's print it like this:

"Nice to meet you {0}.I am {1}".formate(name,machine)

So you must be thinking it of bit weird.So let me tell you here {0} and {1} meaning.
{0} represents the variable name argument position in format function.
you can add many argument to the formate function.
python 3.6 introduces string interpolation though So now you can do some thing like

f"Nice to meet you{name}.I am {machine}"

you can also pre-fix with r and u before the string.to deal with raw and Unicode text.its up to you.what you choose.
There are many other string properties like slicing and cutting etc.

Integers and Floats in Python

Defining integers in Python is very easy.
eg:
answer=42

pi=3.14159

Python 3 also introduces complex numbers as a type.There is no real need to worry about types in Python.atleast not in the beginning.

answer + pi = 45.14159 # Don't worry about conversion !

you can seamlessly add integers, float .pyhton does not complain about it.it will produce desired results.And to cast anything.just have to do something like this.

int(pi) == 3
float(answer) == 42.0

this is needed when we really want to cast the integer and float variables.

Thursday, December 7, 2017

Types in Python

In Python type has been handled differently than other programming languages.in many programming languages including JAVA or C# .you have to declare variable type before you declare variable itself.that variable type can be int,float,double, String,char Boolean or your own custom types such as Student.So before you even declare variable you have to write something like this.

// C# or java

int answer=42;
String name="Pyhton";

With pyhton take this approach in opposite direction.in pyhton it is not necessary  to declare type anywhere.in fact you will do something like this.

# Python

answer = 42
name = "Python'

And same thing goes with other types including your own type.
Now there are some advantages and disadvantages of this approach.
Pyhton also called dynamically typed language.So not declaring types leads many bugs for example suppose we have simple function they just adds two numbers.will look like below.

def add_numbers(a,b)
print(a+b)

Call the function
add_numbers(5,11)
16. everyhting is fine.

but what if we call like below:

add_numbers(5,"something")

It will give type error:unsupported operand types.
well python does not have any machenism to tell you in advance while other languages have.

There is something called "type hinting".

Type Hinting: this is new features added in Python version 3.5 .they will help you to add data types in your program.it will help your IDE.it will not prevent your wrong  code running.So you can do something like this:

def add_numbers(a: int, b: int)  -> int:
return  a + b

Installing PyCharm

Although we have started using IDLE for python.now we will use PyCharm integrated Developer environment.this is excellent IDE and this is built by the same forks who brought  IntelliJ ide.They have a free community edition for PyCharm available for download from there Website.
If you don't want to use PyCharm don't use it. any text editor will work fine including notepad.for the purpose I will certainly give all tutorials using PyCharm.

To download it simply go to"www.jetbrains.com/pycharm/" then click on the "Download Now" button and then "Download" free community edition of PyCharm.once you download and install PyCharm.click "Create New Project" and make sure that "Pure Python" is selected.
also you can see Location and Interpreter path.if you click on Interpreter you will see all the installed pyhton interpreter on your computer. And also make sure you select Python version 3 and above.in Location path basically it's your workspace.
now click on create.then you will be able to see Pycharm IDE with some files in it.And you can also add Python files by right click on your project and select pyhton file,name it helloworld.py  and click ok and write below code.

print("Hello World") and then right click on the HelloWorld.py you will see "Run helloworld'". in consloe you will able to see Hello World .

Now your PyCharm IDE is ready to use.

The Awesomeness of the Python

One you install python.you will have a handy tool called PowerShell or python terminal.if you just type Python 3 then you will have an access of entire pyhton programming language.this is pretty much different than any other programming languages such as Java ,C and if you are a front end developer.think of this as JavaScript console in your browser developer tools.

So what it mean exactly?.

Well being able to just type Python in terminal gives you some advantages as a developer.

for example,
suppose you are not really sure about a result of a function or any other code out put.you can simply start the Python interpreter on your machine and see what happening when you used that function.Now a days many pyhton I'd is coming with integrated pyhton console.thats the same when we ran the program through our command prompt terminal.
unfortunately this also comes with a draw back every Python program we ran pre-fix it with the Python command.

let say we  have a sample program:

# hello.py
print("Hello World")

It simply prints Hello World but in order to run it we need to open terminal and write
hello.py

And you will see below output
Hello World

During development it is a distraction but now many Python I'd are coming in a single package.

Towards the end of the course I will teach you how to create one binary file from windows,Mac or Linux machine. then you can run on any operating system.as I have mentioned if you use python from command line you will have full power of python  but if you want little bit more than that such as Syntax highlighting then you will want to run the "idle" integrated development environment.
Not that this not just any IDE .this is comes installed by default.
To open it just simply search it idle and tap it,CMD will be opened . there is not much difference when you were using CMD.
The advantages of using IDLE over CMD(Command Prompt) is code completion,Syntax highlighting etc.
Very soon I will tell you about a free integrated development environment called PyCharm.