Learning to Program
(…and a bit about ‘Life’)
2
What is a Computer Program?
© 2014 All Rights Reserved Confidential
A program is a sequence of instructions to perform a computational task. Essentially, any
computer program (however complex it may get), almost always is a combination of
below basic instructions:
 Input
 Output
 Mathematical Operation
 Conditional execution
 Repetition
Programming languages are formal languages that have been designed to express
computations.
3
Python
© 2015 All Rights Reserved Confidential
Python is an easy to learn powerful programming language. Some features of
python are:
• Simple
• Interpreted
• Free and Open Source
• High Level
• Portable
• Object Oriented
• Extensible
4
Interpreter vs Complier
© 2015 All Rights Reserved Confidential
• Programs written in high-level languages have to be converted into low-level language
for the computer to understand them.
• 2 kinds of program that convert high level source code to low level are: Interpreter and
Compiler
• An interpreter translates the source code line by line.
• A compiler reads the entire program and translates it completely before the program
runs. The source code is compiled into an object code which is then executed. Once a
program is complied, it can be executed many times without the need of compilation.
Source Code Interpreter Output
Source Code Compiler OutputObject Code Executor
5
Basics of Python
© 2014 All Rights Reserved Confidential
Comments: These are the descriptive text that is put in the program so that the person who is
reading it, can understand what a particular statement or a block of statements is doing. ‘#’
symbol is used to mark comments e.g
Print(“My name is Jack) # Using print() function to print name
Comments are not compiled. The compiler just ignores everything which is written after #
Numbers: Numbers are of 2 types – integers and floats. 2 is an integer but 2.34 is a floating
point number
Strings: A string is a sequence of characters. Strings are specified either using single-quotes or
double quotes.
Variables: A variable is a name that refers to a value. E.g n = 17 i.e The value 17 is assigned to
a variable named “n”. In python, variables names begin with a letter and can not contain special
characters. Also keywords can not be used as variable names. To know the type of variables,
use the function type()
6
Basics of Python..(Contd)
© 2014 All Rights Reserved Confidential
Operators: Operators are special symbols that represent computations like addition or
subtraction
+ addition
- Subtraction
* Multiplication
/ Division
** Power
// Integer Division
% Mod Operation
Expression: An expression is a combination of values, variables and operators.
7
Its refers to the methodology of programming where programs are made of object
definitions and function definitions and most of the computation is expressed in terms
of operations on objects. Each object definition corresponds to some object or concept
in real world and the functions that operate on that object correspond to the ways
real-world object interacts.
• Organizing your program to combine data and functionality
• Class creates a new type where objects are instances of the class.
• Class is like a blueprint or a template
• Variables that belong to an object or class are referred to as fields.
• Functions that belong to a class are called Methods
• Fields and Methods are known as attributes of a class.
• Fields are of two types - they can belong to each instance/object of the class or they
can belong to the class itself. They are called instance variables and class variables
respectively
Object Oriented Programming
© 2014 All Rights Reserved Confidential
8
Functions
© 2014 All Rights Reserved Confidential
• A function is a named sequence of statements that performs a computation.
• A module is a file that contains a collection of related functions.
• Packages are just folders to hierarchically organize modules.
• Each package contains a bunch of Python scripts. Each script is a module. Examples of
packages are Numpy, sckit-learn, pandas etc
9
Control Flow - If
© 2014 All Rights Reserved Confidential
3 control flow statements in Python – If, while and for
If statement is used to check a condition:
Cp = int(input(“Enter the cost price: ”))
Sp = int(input(“Enter the selling price: ”))
If(sp>cp):
print(“Congratulations! You have made a profit”)
Elif(sp<cp):
print(“Sorry! You are in loss”)
Else:
print(“No profit. No Loss”)
10
Control Flow - While
© 2014 All Rights Reserved Confidential
While statement is used to repeatedly execute a block of statements as long as a condition is
true.
# Read a number. Print the square of all numbers from 1 upto N
n= int(input("Enter a number: "))
# Initial Condition
i = 1
while(i<=n):
print(i*i)
i = i+1
11
Control Flow – For Loop
© 2014 All Rights Reserved Confidential
For statement is also used to repeatedly execute a block of statements as long as a condition is
true.
# Read a number. Print the square of all numbers from 1 upto N
n= int(input("Enter a number: "))
# Initial Condition
For I in range(1, N+1):
print(i*i)
12
Data Structures - Lists
© 2014 All Rights Reserved Confidential
Lists : A list is a data structure that holds an ordered collection of items i.e. you can
store a sequence of items in a list. Once you have created a list, you can add, remove
or search for items in the list. Since we can add and remove items, we say that
a list is a mutable data type i.e. this type can be altered.
shoplist = ['apple', 'mango', 'carrot', 'banana']
print('I have', len(shoplist), 'items to purchase.')
print('These items are:', end=' ')
for item in shoplist:
print(item, end=' ')
print('nI also have to buy rice.')
shoplist.append('rice')
print('My shopping list is now', shoplist)
print('I will sort my list now')
shoplist.sort()
print('Sorted shopping list is', shoplist)
13
Data Structures - Lists
© 2014 All Rights Reserved Confidential
print('The first item I will buy is', shoplist[0])
olditem = shoplist[0]
del shoplist[0]
print('I bought the', olditem)
print('My shopping list is now', shoplist)
# To print unique elements of a list
Mylist=list(set(mylist))
# To convert all elements of a list into numbers:
mylist=[int(x) for x in mylist]
# List Indexing:
fruits = [‘Orange’, ‘Banana’, ‘Apple’, ‘Pear’]
fruits[1] gives second element
fruits[-1] gives last element
14
Data Structures - Lists
© 2014 All Rights Reserved Confidential
# List Slicing:
To select multiple elements from a list :
Mylist[start:end]
fruits = [‘Orange’, ‘Banana’, ‘Apple’, ‘Pear’]
fruits[1:3] gives [‘Banana’, ‘Apple’]. The elements are returned with index
“start” upto index “end-1”
Fruits[1:] gives [‘Banana’, ‘Apple’, ‘Pear’]
Fruits[:3] gives [‘Orange’, ‘Banana’, ‘Apple’]
# Print last 3 elements:
Fruits[-3:]
15
Data Structures – Nested Lists
© 2014 All Rights Reserved Confidential
A list can contain other lists
>>> x = [["a", "b", "c"],
["d", "e", "f"],
["g", "h", "i"]]
X[1] results ["d", "e", "f"]
X[1][2] results “f”
16
Data Structures - Dictionary
© 2014 All Rights Reserved Confidential
A dictionary is like an address-book where you can find the address or contact
details of a person by knowing only his/her name i.e. we associate keys (name)
with values (details). Note that the key must be unique just like you cannot
find out the correct information if you have two persons with the exact same
name.
Note that you can use only immutable objects (like strings) for the keys of a
dictionary but you can use either immutable or mutable objects for the values of
the dictionary. This basically translates to say that you should use only simple
objects for keys.
17
Data Structures - Dictionary
© 2014 All Rights Reserved Confidential
ab = { ‘Gaurav' : ‘gaurav@itbodhi.com',
'Larry' : 'larry@wall.org',
'Matsumoto' : 'matz@ruby-lang.org',
'Spammer' : 'spammer@hotmail.com'
}
print(“Gaurav's address is", ab[‘Gaurav'])
# Deleting a key-value pair
del ab['Spammer']
print('nThere are {0} contacts in the address-bookn'.format(len(ab)))
for name, address in ab.items():
print('Contact {0} at {1}'.format(name, address))
# Adding a key-value pair
ab['Guido'] = 'guido@python.org'
if 'Guido' in ab:
print("nGuido's address is", ab['Guido'])

Machine learning session3(intro to python)

  • 1.
    Learning to Program (…anda bit about ‘Life’)
  • 2.
    2 What is aComputer Program? © 2014 All Rights Reserved Confidential A program is a sequence of instructions to perform a computational task. Essentially, any computer program (however complex it may get), almost always is a combination of below basic instructions:  Input  Output  Mathematical Operation  Conditional execution  Repetition Programming languages are formal languages that have been designed to express computations.
  • 3.
    3 Python © 2015 AllRights Reserved Confidential Python is an easy to learn powerful programming language. Some features of python are: • Simple • Interpreted • Free and Open Source • High Level • Portable • Object Oriented • Extensible
  • 4.
    4 Interpreter vs Complier ©2015 All Rights Reserved Confidential • Programs written in high-level languages have to be converted into low-level language for the computer to understand them. • 2 kinds of program that convert high level source code to low level are: Interpreter and Compiler • An interpreter translates the source code line by line. • A compiler reads the entire program and translates it completely before the program runs. The source code is compiled into an object code which is then executed. Once a program is complied, it can be executed many times without the need of compilation. Source Code Interpreter Output Source Code Compiler OutputObject Code Executor
  • 5.
    5 Basics of Python ©2014 All Rights Reserved Confidential Comments: These are the descriptive text that is put in the program so that the person who is reading it, can understand what a particular statement or a block of statements is doing. ‘#’ symbol is used to mark comments e.g Print(“My name is Jack) # Using print() function to print name Comments are not compiled. The compiler just ignores everything which is written after # Numbers: Numbers are of 2 types – integers and floats. 2 is an integer but 2.34 is a floating point number Strings: A string is a sequence of characters. Strings are specified either using single-quotes or double quotes. Variables: A variable is a name that refers to a value. E.g n = 17 i.e The value 17 is assigned to a variable named “n”. In python, variables names begin with a letter and can not contain special characters. Also keywords can not be used as variable names. To know the type of variables, use the function type()
  • 6.
    6 Basics of Python..(Contd) ©2014 All Rights Reserved Confidential Operators: Operators are special symbols that represent computations like addition or subtraction + addition - Subtraction * Multiplication / Division ** Power // Integer Division % Mod Operation Expression: An expression is a combination of values, variables and operators.
  • 7.
    7 Its refers tothe methodology of programming where programs are made of object definitions and function definitions and most of the computation is expressed in terms of operations on objects. Each object definition corresponds to some object or concept in real world and the functions that operate on that object correspond to the ways real-world object interacts. • Organizing your program to combine data and functionality • Class creates a new type where objects are instances of the class. • Class is like a blueprint or a template • Variables that belong to an object or class are referred to as fields. • Functions that belong to a class are called Methods • Fields and Methods are known as attributes of a class. • Fields are of two types - they can belong to each instance/object of the class or they can belong to the class itself. They are called instance variables and class variables respectively Object Oriented Programming © 2014 All Rights Reserved Confidential
  • 8.
    8 Functions © 2014 AllRights Reserved Confidential • A function is a named sequence of statements that performs a computation. • A module is a file that contains a collection of related functions. • Packages are just folders to hierarchically organize modules. • Each package contains a bunch of Python scripts. Each script is a module. Examples of packages are Numpy, sckit-learn, pandas etc
  • 9.
    9 Control Flow -If © 2014 All Rights Reserved Confidential 3 control flow statements in Python – If, while and for If statement is used to check a condition: Cp = int(input(“Enter the cost price: ”)) Sp = int(input(“Enter the selling price: ”)) If(sp>cp): print(“Congratulations! You have made a profit”) Elif(sp<cp): print(“Sorry! You are in loss”) Else: print(“No profit. No Loss”)
  • 10.
    10 Control Flow -While © 2014 All Rights Reserved Confidential While statement is used to repeatedly execute a block of statements as long as a condition is true. # Read a number. Print the square of all numbers from 1 upto N n= int(input("Enter a number: ")) # Initial Condition i = 1 while(i<=n): print(i*i) i = i+1
  • 11.
    11 Control Flow –For Loop © 2014 All Rights Reserved Confidential For statement is also used to repeatedly execute a block of statements as long as a condition is true. # Read a number. Print the square of all numbers from 1 upto N n= int(input("Enter a number: ")) # Initial Condition For I in range(1, N+1): print(i*i)
  • 12.
    12 Data Structures -Lists © 2014 All Rights Reserved Confidential Lists : A list is a data structure that holds an ordered collection of items i.e. you can store a sequence of items in a list. Once you have created a list, you can add, remove or search for items in the list. Since we can add and remove items, we say that a list is a mutable data type i.e. this type can be altered. shoplist = ['apple', 'mango', 'carrot', 'banana'] print('I have', len(shoplist), 'items to purchase.') print('These items are:', end=' ') for item in shoplist: print(item, end=' ') print('nI also have to buy rice.') shoplist.append('rice') print('My shopping list is now', shoplist) print('I will sort my list now') shoplist.sort() print('Sorted shopping list is', shoplist)
  • 13.
    13 Data Structures -Lists © 2014 All Rights Reserved Confidential print('The first item I will buy is', shoplist[0]) olditem = shoplist[0] del shoplist[0] print('I bought the', olditem) print('My shopping list is now', shoplist) # To print unique elements of a list Mylist=list(set(mylist)) # To convert all elements of a list into numbers: mylist=[int(x) for x in mylist] # List Indexing: fruits = [‘Orange’, ‘Banana’, ‘Apple’, ‘Pear’] fruits[1] gives second element fruits[-1] gives last element
  • 14.
    14 Data Structures -Lists © 2014 All Rights Reserved Confidential # List Slicing: To select multiple elements from a list : Mylist[start:end] fruits = [‘Orange’, ‘Banana’, ‘Apple’, ‘Pear’] fruits[1:3] gives [‘Banana’, ‘Apple’]. The elements are returned with index “start” upto index “end-1” Fruits[1:] gives [‘Banana’, ‘Apple’, ‘Pear’] Fruits[:3] gives [‘Orange’, ‘Banana’, ‘Apple’] # Print last 3 elements: Fruits[-3:]
  • 15.
    15 Data Structures –Nested Lists © 2014 All Rights Reserved Confidential A list can contain other lists >>> x = [["a", "b", "c"], ["d", "e", "f"], ["g", "h", "i"]] X[1] results ["d", "e", "f"] X[1][2] results “f”
  • 16.
    16 Data Structures -Dictionary © 2014 All Rights Reserved Confidential A dictionary is like an address-book where you can find the address or contact details of a person by knowing only his/her name i.e. we associate keys (name) with values (details). Note that the key must be unique just like you cannot find out the correct information if you have two persons with the exact same name. Note that you can use only immutable objects (like strings) for the keys of a dictionary but you can use either immutable or mutable objects for the values of the dictionary. This basically translates to say that you should use only simple objects for keys.
  • 17.
    17 Data Structures -Dictionary © 2014 All Rights Reserved Confidential ab = { ‘Gaurav' : ‘[email protected]', 'Larry' : '[email protected]', 'Matsumoto' : '[email protected]', 'Spammer' : '[email protected]' } print(“Gaurav's address is", ab[‘Gaurav']) # Deleting a key-value pair del ab['Spammer'] print('nThere are {0} contacts in the address-bookn'.format(len(ab))) for name, address in ab.items(): print('Contact {0} at {1}'.format(name, address)) # Adding a key-value pair ab['Guido'] = '[email protected]' if 'Guido' in ab: print("nGuido's address is", ab['Guido'])