List Comprehension

List comprehension is a way of making new lists. It allows you to create a list from any iterable object in a concise and efficient manner. See the basic syntax below:

# list comprehension syntax
new_list = [x for x in some_iterable]

Here you can see that list comprehension is specified by square brackets (just like the list itself) inside which you have a for loop over some iterable object. In our example, new_list will simply consist of all elements from some_iterable object. The code above is completely equivalent to the one below, however, it takes less space and works a little bit faster!

# the equivalent code
new_list = []
for x in some_iterable:
    new_list.append(x)

list comprehensions are used not just for copying elements from some iterable into a list, but mainly for modifying them in some way to create a specific new list. In this case, in the first place of the list comprehension, we write some function of our variable. For example, the code below shows how to create a list of squared numbers.

# squared numbers
numbers = [1, 2, 3]
square_list = [x * x for x in numbers]  # [1, 4, 9]

Also, we can use list comprehensions to convert elements of a list from one data type to another:

# from string to float
strings = ["8.9", "6.0", "8.1", "7.5"]
floats = [float(num) for num in strings]  # [8.9, 6.0, 8.1, 7.5]

OOP in Python 4

Instance Methods

This is the basic type of method and mostly used this method in OOP. This method take first parameter self which points to an instance of class. It can also accept more than one parameters but first parameter should be self. This method modify the current object state by using self parameter self can access all the attributes of current object and also can modify. This method can also change the class state by using self.__class__ attribute. Example

class MyClass:
  def method(self):
  return 'instance method called'

myclass_obj = MyClass()
print(myclass_obj.method())

This code will print instance method called

Class Method

This is an other type of method in OOP Python this method is marked with a decorator @classmethod to flag it as a class method.

Instead of accepting self parameter, class method take a cls parameter that points to the class and not the object instance When this method is called and if there are some changes to attributes by this method it will modify the main class attributes not only the current object. It’s means this method changes the class state.

Example:

class MyClass:
    @classmethod
    def classmethod(cls):
        return 'class method called'

So, this is the way how we can call a class method

Static Method

This is third type of method which is defined by using @staticmethod decorator to flag it as a static method.

This type of methods never take a self parameter nor a cls parameter (but we are free to pass other parameters to this function). Therefore a static method can neither modify object state nor class state. Static method are restricted in what data they can access. Example

class MyClass:
    @staticmethod
    def sMethod():
       return 'static method called'

This is how we can define a static method. We can call static method by using class name like MyClass.sMethod()

OOP in Python 3

Class variable

A variable that is shared by all instances of a class. Class variables are defined within a class but outside any of the class’s methods. Class variables are not used as frequently as instance variables are. For Example

class Employee:
    company = 'google'

In this code company is a class attribute and it will shared with all its object it should not be defined in any method it is always outside the methods. We can also access it by Employee.company

Instance variable

A variable that is defined inside a method and belongs only to the current instance of a class.

class Employee:
    company = 'google'

john = Employee()
print(john.comapny) #print google
john.comapny = 'Microsoft'
print(john.comapny) #print Microsoft

In this code when we create an object then all attributes inside the object of instance attribute changing to these variables are only for this object.

Defining a Method

Inside a class a method can be defined with the keyword def and every method inside a class should have first parameter with name self which is pointing to current object For example.

class Employee:
 class Employee:
    company = 'google'
    salary = 10000

    def getSalary(self):
        return self.salary

john = Employee()
print(john.getSalary())

In this code we define a method called getSallary() and pass a parameter self But when we create an object and call this method we did not need to add self parameter when we calling the method.

Define Method with Parameter

If want to add more parameters to method than we will put them after the self parameter and use them inside the method for example:

class Employee:
    company = 'google'
    salary = 10000

    def getTaxAmount(self, taxPercentage):
        return self.salary*(taxPercentage/100)


john = Employee()
print(john.getTaxAmount(10)) #will print 1000.0

In this code we define a method which will return us the actual amount of tax and we will provide the tax percentage as parameter, so when we define method we use 2 parms and when we call the method we use only one input parm only not the self

OOP in Python 2

Constructor Method

A constructor is a method which is called when an object is created. In Python the constructor method can be written with keyword “__init__()” Every line of code inside the __init__ method will be execute at the time of object creation For Example.

class Employee:
    company = 'google'

    def __init__(self):
        print('New Employee Object is created')
   

So, this is the method of defining a constructor, you have noticed that in __init__ function we also have passed a parameter with name of self this is the default parameter of every method defined inside the class. So, why we used it. The self keyword pointing to the current object of this class like other languages we use this keyword self is almost similar to this keyword in other programming languages. But in python it should be first parameter of every method otherwise interpreter will give an error.

Note: It is also not necessary to use only self keyword as first parameter but you can also use any other keyword in replace of self but this keyword will point to current object. In most cases every developer is using self keyword because of better readability of code.

So, when we create an object of above given code Like

john = Employee()

Now when we run the code it will print New Employee Object is created because this print statement is inside the constructor method.

Parameters to constructor

We can also pass other parameters to constructor and use them inside the constructor and that code will be executed at the time of object creation For Example:

class Employee:
    company = 'google'

    def __init__(self, name, age):
        self.name = name
        self.age = age

john = Employee('John', 20)
print(john.name)
print(john.age)
print(john.company)

In above given code we also put 2 more parameters to constructor method, and inside the method we used self.name so what its means that this is creating a new property called name and getting the value from parameter name and assigning it to property. So, self is pointing to current object and doing work for current object .

when we create an object of this class we only pass parameters name & age and ignore the first parameter self which is default parameter of method and every method inside class always have this method so when we execute the this code it will create 2 more properties called name & age and object creation and than we print all the properties by accessing them with object name and it will print result like this.

John  #This is the Employee name which is set in constructor
20    #This is the Employee age which is also set in constructor
google #This is the Employee company name which is class default property

OOP In Python .1

Python is an object oriented programming language every thing in python is object and it have its own properties and methods. The OOP concept focuses on reusable code.

Class

A class is blueprint or template of an objects every class has its own properties and methods a class can be made in python with following syntax.

The simple class definition will look like this

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

For defining a class we start it with the name class and than add class name the first character of class name will be capital than add colon, after colon on new line the class inner block will be started than we add ident of whitespaces minimum of one space “Ident is required in python for function, loops, conditions and classes e.t.c. after ident we can put properties and methods with same ident for example a class with some properties will looks like this.

class Fruit:
  name = "Apple"
  weight = "2kg"

So, this is a simple class with the name “Fruit” and have 2 properties.

Objects

An object is an instantiation of a class, When we define a class it is only a template or blue print. After creating a object we can access the properties of that class and can also call that’s class methods. A class can have as many objects as many a user need. Every new object can have different values.

How to create an object

An object can be created by calling a class name like a function and than assign it to a variable now an object of that class is stored in that variable after that we can implement all the methods and properties of class with this variable name For Example.

class Fruit:
  name = "Apple"
  weight = "2kg"

new_fruit = Fruit()

Above given code will create an object of Fruit class now we can access the properties of Fruit class by variable new_fruit like

print(new_fruit.name)
print(new_fruit.weight)
First Line of code will print Apple
Second Line of code will print 2KG

Python Lambda

Lambada is a small function usually written in one statement it can take any number of arguments but expression is only one Example.

x = lambda a : a + 10
print(x(5))

In this code the a at the right side of lambda before the colon is an argument for function and after the colon there is a expression which one is calculated after the x function is called with value so this function will get an argument 5 and add it with 10 and the result of this function will be 15.

Lambda with 2 arguments

As there is mention above a lambda function can take as many arguments as you need to execute for example.

x = lambda a, b : a + b
print(x(10, 30))

In this function there are 2 arguments a and b and than add both of them and return the result. Similarly you can add as many arguments as you need for example if you need to evaluate 3 arguments than the expression would be like this.

x = lambda a, b, c : a * b *c
print(x(2, 3, 4))

This expression take 3 arguments and multiply them and return multiplication result. So you can add as many arguments at left side with comma separated and than evaluate them at right side.

Lambda in function

A lambda can be used in side the other function and than take argument first from main function than return a lambda function to a variable than it function can be called again For example.

def my_main_fun(n):
  return lambda a : a * n
x = my_main_fun(2)

In this function first we define main function and than call it when we call the main_function it took a argument 2 and replace with n at the right side of n and return a lambda function with expression lambda a : a * 2 Now

print(x(3))

No we call the lambda function which is stored inside the x it will now multiply 3 by 2 and return answer as 6. So in this way we can use lambda function efficiently.

Python Learning Resources

Books

Think Python 2nd edition (I started with an older version of this)

Python crash course:

Tools/IDE

Code visualization to help learning

http://www.pythontutor.com

Pycharm Community Edition for the IDE or the Professional Edition is free with a .edu email address.

Videos

Python I

https://www.edx.org/course/computing-in-python-i-fundamentals-and-procedural

Python II

https://www.edx.org/course/computing-in-python-ii-control-structures

Python III

https://www.edx.org/course/computing-in-python-iii-data-structures

Video Courses

I haven’t tried these specific videos, but pluralsight is usually high quality. Each course has reviews.

https://www.pluralsight.com/paths/core-python

Short Hand If Condition

If there is only one statement to test than we use shorthand if condition and it can be placed only in single line Like.

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

This code will check either a is greater than b or not after comparing it will print “a is greater than b”

Short Hand If , Else

If there is only one statement one for if and one for also it can also be place in one same line for Example.

num_1 = 2
num_2 = 40
print("A") if num_1 > num_2 else print("B")

In this one line code program will print A if num_1 is greater than num_2 and Print B in else case.

Note: This method is similar to ternary operators.

One Line if, else with 3 condtions

num_2 = 330
num_1 = 330
Print("A") if num_1 > num_2 else print("=") if num_1 == num_2 else print("B")

In this statement program first check if num_1 is greater than num_2 than it will print A and remaining statement will not execute if this statement will become false than in else block there is another if statement that will check if num_1 is equal to num_2 than it will print = sign and at the end in last else it will print B .

File Handling in Python

Python has several functions for updating, creating, reading and deleting files. Major function for file handling is open() This function will open a file for reading content from file writing content to file or append some content to a file.

Any file we want to use firstly we will open this file with open() function it takes 2 parameters first File Path and second file opening mode. File opening modes are given below.

  • “r” – Read Open a file for reading error if file not exist
  • “a” – Append Open a file for appending, Create a file if not exist
  • “w” – Write Open a file for writing, Create a file if not exist
  • “x” – Create a New file, return an error if file already exist

“t” and “b” can also be used for open a file in text or binary mode.

How to write

file = open("demo.txt")

This code will open a file in read and text mode because “r” and “t” are default mode of Open() function.

read() function

After successfully opening a file we can read its data with read() function.

file = open("demo.txt")
print(file.read())

This code will read a file named “demo.txt” and print all its data. If you want to read only some part of data you can pass a parameter to read() function that how many character you want to read from file.

Read Lines

readline() function will read a single line of opened file. Call this function again and again for next line read like.

file = open("demo.txt")
print(file.readline())
print(file.readline()) 

This code will read first 2 lines of files.

With the help of loop you can read all lines of opened file like below given method.

file = open("demofile.txt")
for single_line in file:
  print(single_line) 

This code will read the opened file line by line and print it.

Write to a file

Open file in “w” or “a” mode to write in a file or append some content in file like.

file = open("demo.txt", "a")
file .write("Now the file has more content!")

In this code program will open a file in append mode and add some new content to file existing content will not be changed.

file = open("demo.txt", "a")
file .write("Now the file has more content!")

In this code program will open a file in write mode and add some new content to file existing content will be overwrite.

Note: Both of above given code will also create a new file if file not exist.

Close a file

A file should always closed if you have finished working on it, if you will not close the file all the changes may be lost. to close a file below given code will work.

file = open("demo.txt", "a")
file.write("Now the file has more content!")
   file.close()

In this code “file.close()” function will close the opened file after all the process is done

Functions In Python

A function is a block of reusable code which can be defined and used as many as you want. A function take some parameters(optional) and return some value or perform any action as per parameters. There are 2 types of function in python.

  • Built in Functions
  • Custom Defined Functions

Built-in

Built in functions are function which are provided by python like print(), len() etc.

Custom

Custom functions are defined by user as per working requirements

How to Create

A function can be created by def keyword and function name, function inner block also written with ident block if ident is not used interpreter will through an error. Example

def new_function():
  print("Hello Word")

How to call

A function can be called by its name and round brackets like above function we can call like.

new_function()

This function will print Hello Word

Parameter of function

A parameter is a value or a set of values which can be passed to function and perform different action inside the function block we can pass parameters to function with different styles like.

def my_function(fname):
  print(fname + " Refsnes")


my_function("Emil") #Will Print Emil Refsnes

You can pass as many parameters as you want there are more styles available for passing parameters here is a list and details.

  • def my_function(fname, lname): Will accept 2 parameters
  • def my_function(*kids): Will used if parameter quantity is unknown parameters can be accessed by its index like kids[0], kids[1]
  • def my_function(param_1, param_2, param_3): Param also can be passed by param name when a function is called like my_function(param_1 = ‘a’ , param_2 = ‘b’, param_3 = ‘c’) in this method order does not matter
  • def my_function(fname = ‘john’ , lname): Will accept fname as john if no value provided by user

Return Value

After performing some action a function can also returned a value of any type

def my_function(x):
  return 5 * x
print(my_function(3)) #will return the answer of 5*3 and print function will print it 15

Pass Statement

If you want to leave empty a function block and do not want to perform any action on it you can use simply pass keyword inside the function block