You are on page 1of 57

Python Programming

Chandra Hampiholi
Contnents - Python Programming
Contents for PYTHON - BASICS Contd ..
1: Introduction To Programming
Why Code ? And Why code in Python ? 5: Python Functions, Modules And Packages
Algorithmic Thinking Organizing python codes using functions
What is Programming ? Organizing python projects into modules
Importing own module as well as external modules
2: Introduction To Python Understanding Packages
IDE & Python Shell Window “Hello World” Programming using functions, modules and external
Understanding Python variables packages
Python basic Operators
Understanding python Syntax 6: Python String, List And Dictionary Manipulations
Building blocks of python programs
3: Python Data Types Understanding string in build methods
Numeric data types: int, float, complex List manipulation using in build methods
Using string data type and string operations Dictionary manipulation
Defining list and list slicing
Use of Tuple & Dictionaries data type 7: Python File Operation
Reading & writing files in python
4: Python Program Flow Control Understanding read functions, read(), readline() and
Conditional blocks using if, else and elif readlines()
Simple for loops in python Understanding write functions, write() and writelines()
For loops using ranges, string, lists and dictionaries Manipulating file pointer using seek
Use of while loops in python Programming using file operations
Loop manipulation using pass, continue, break and else
8: Python Object Oriented Programming – Oops
Concept of class, object and instances
Constructor, class attributes and destructors
Use of class in live projects
Inheritance , overlapping and overloading operators
What is- Programming
It is going to stay whether you like it or not

There is a lot of people in the Basic Requirements


world who can program,
but none that can also do what 1. Curiosity to learn

you know how to do


2. Readiness to unlearn old ways
3. Ample Time to practice
4. A Laptop with Windows
So better to write you own program 5. Anaconda or (Repl.it) Account
instead of instructing a programmer 6. Access to Internet

Great Example : No typist around, If no internet, then can use


You Type your own letters…. Right ? 1. Pycharm or Atom (Free)
2. Visual Studio 2017 Community
3. VS-Code (Python Tools for VS)
So Start Coding … 4. Python Interpreter(python.org)
Automate your business processes
!!!
SLIDE 3
Coding : language of choice?
As on Sep 2018
IMPLEMENTATION OF PYTHON
Cpython (Python written in C)
IronPython (Python on .NET)
Jython (Python on the Java VM)
PyPy (fastpython with a JIT compiler)
Stackless Python (Branch of CPython)
MicroPython (Python on micro controllers)
Anaconda Python (Python distribution for
data management, analysis and
visualization of large data sets)
PythonAnywhere (freemium hosted
Python installation which lets
you run Python in the browser)
PythonToolsForVS (Free- from Microsoft)

LIBRARIES
NumPy Numerical arrays & math
functions.
PyPlot For visualization tools.
why python ?
• Python is Easy to learn & understand; almost English like ..
• Python is Flexible & Scalable & Portable to platforms
• Python works on many platforms : PC, Mac, Unix, Mobiles, Internet, etc..
• Python is a general purpose programming language.
• Developing desktop, web, complex scientific & visualisation apps & also
ML & AI
• Python has a large open source community support & huge library
• Of-course Python is FREE Hurray !!!

SLIDE 5
future of Python ?
Why Python is so popular

Machine Learning
01 Statistical techniques to give computer systems the
ability to "learn" from data, without being explicitly
programmed

Artificial Intelligence
02 Artificial intelligence (AI) is an area of computer science
that emphasizes the creation of intelligent machines
that work and react like humans

BIG Data
03 Making sense out of gigantic data that is available for
the purpose of Business Intelligence

Web Programming
04 dJango
Excellent framework for web programming.

API Programming
05 API is the acronym for Application Programming
Interface, which is a software intermediary that allows
two applications to talk to each other.
SLIDE 6
type of Languages ?

Interpreted Language Compiled Language


Compiled Language Vs Interpreted Language

JAV
A

C#, C++

Java Python PYTHON


C Ruby
C # Perl
C + + R
P H P, R U B Y
Fortran Lisp
PERL, R
SLIDE 7
Who uses Python ?
• Google…..
• You Tube.. ..
• Spotify…...
• FaceBook
• Reddit ..
• Instagram
• Quora
• Netflix
• Dropbox

• Python is very mature … It is Scalable to any size and shape


SLIDE 8
Algorithmic- Thinking
An algorithm is an unambiguous description that
makes clear what has to be done/ implemented.

Examples :
• In a recipe, a step such as “Bake until done” is ambiguous
• Because it doesn’t explain what “done” means.
• A more explicit way - “Bake until the cheese begins to bubble”

An algorithm expects a defined set of inputs


An algorithm produces a defined set of outputs.
An algorithm must produce a result, stopping after a finite time
An algorithms is guaranteed to produce the correct result.
What is a - Program?
It is a list of sequential instructions that tell a computer what to do

Instructions to Human Instructions to Computer


100 : !Fill Kettle with water

Flow direction of instructions


Fill Kettle with water
Boil water 200 : !Boil water
Get teapot 300 : !Get teapot
Fill teapot with bags 400 : !Fill teapot with bags
Fill with water 500 : !Fill with water
Get cups 600 : !Get cups
Wait until ready 700 : !Wait until ready
Pour out 800 : !Pour out
Add Milk 900 : !Add Milk
Serve Tea 1000 : !Serve Tea

Sequential Colon Instructions


Operation Separation set to
Number Computer
What is- Programming
Logical and unambiguous set of Instructions Instructions to Human
100: !Fill Kettle with water Fill Kettle with water

The ALL-CAPS are the part of Code & Rest are Variables
Pseudo Code for the Computer
IF kettle (empty) THEN (Fill kettle with water) Boil water
IF kettle (filled) THEN GOTO 200 :!Boil water Get teapot
Fill teapot with bags
200: !Boil water
IF water (boiling) THEN (turn kettle off) ELSE CONTINUE (boil)
Fill with water
Get cups
300: !Get teapot Wait until ready
IF (number of people) less or equal to 2 THEN (GET smallteapot) Pour out
IF (number of people) greater than 2 THEN (GET largeteapot) Add Milk
IF teapot (dirty) THEN (wash out teapot) UNTIL (clean) Serve Tea
IF teapot (clean) THEN (swirl hot water) UNTIL (warm)
IF teapot (warm) THEN (Fill teapot with bags) !continue

400: !Fill teapot with bags


LET teatype=USERCHOOSE(EarlGrey,Lapsang,Camomile,Green)
IF teapot (large) THEN add 2 teabag USING teatype
IF teapot (small) THEN add 1 teabag USING teatype

500: !Serve Tea


POUR tea INTO cup UNTIL cup/s ( is/are full)
IF (need more tea) THEN GOTO 100:
ELSE (enough tea) STOP (making tea)
Warmup - Programming
BASIC (Beginner's All-Purpose Symbolic Instruction Code) Programming created in 1964 for a PC

Let’s open http://www.quitebasic.com/

NOW Click RUN Button


See What happens
Now Let’s write a simple
program
100 CLS
150 let a=25
200 let b=3
300 let c=a+b
400 let d=(a+b) * (a-b)
500 print c
600 print d
700 print "That was cool"

Where to get Python from ?


https://www.python.org/downloads/
Download for the Interpreter Version 3.7
Before you start - Some Geeky Stuff !
Get Command Prompt (DOS Box)
Windows>Run : & cmd 8
https://www.python.org/downloads/
Download for the Interpreter Version 3.7

OR
Web Based Python IDE – repl.it

Keystroke Result
CTRL+C Copy selected text
CTRL+X Cut selected text
CTRL+V Paste
CTRL+Z Undo the last keystrokes
CTRL+SHIFT+Z Redo the last keystrokes
F5 Run the module/ Code

SLIDE 13
Python - IDLE
Python Interactive IDE (Integrated Development Environment)

Microsoft Visual Studio 2017 OR Web Based Python IDE – repl.it (Totally
Free)
Let’s Start – IDLE-Repl.it

Browse to https://repl.it/repls
Create an Account (using your email)
&
We are ready to go
lets start - Hello World ! – First Program
NOW LETS TYPE IN THE CONSOLE & HIT ENTER
print("Hello world!") 8 ✓
CORRECT
Observe Spaces
print ("Hello world!")
8 ✓
Observe Capital/Small cases
print( "Hello world!")
8 ✓
Observe Parentheses
Observe
WATCH FOR SYNTAX
print "Hello world!"  WRONG
Observe Spaces
Print("Hello world!")  Observe Capital/Small cases
Observe Parentheses
print(Hello world!)
 Observe
NOW LETS INTRODUCE A VARIABLE
msg = "Hello world!"
8
print(msg)
8
SLIDE 16
Welcome Python ! – Second Program
print("Hello, Welcome Python!") # print statement must use brackets
num1=20
num2=30
sum1 = num1+num2

print (sum1)

print("___________")

num3, num4 = 20.5, 30.5


print(num3+num4)
what is a - VARIABLES! EXAMPLES
Variables store single value
A=5
B=6
VARIABLES : are PlaceHolders to store data
C=A*B
a,b,c = 1,2.65,"John"
print(C)
Raining = True # True is a Reserved Word
print('3+4')
print(a,b,c)
print(3+4)
print ("var a is of type ", type(a))
print('The value of 3+4
print ("var b is of type ", type(b))
is', 3+4)
print ("var c is of type ", type(b))
print('A', 1, 'XYZ', 2)
print ("var Raining is of type ",
type(Raining))
x ="Python is "
firstNumber = 10
y ="awesome"
secondNumber = 20
z = x + y
print (firstNumber + secondNumber)
print(z)
Angry=bool(0) # To Define Something is
True/False
Hungry=bool(1) x = 5
print(Angry, Hungry) y = "John"
print ('First line..'), print(x + y)
print ('Continuation on the same line')
what are - OPERATORS
Operator Description Example
x, y = 15, 4
print('x + y =',x+y) + Addition Adds values on either side of the a + b = 30
print('x - y =',x-y) operator.

print('x * y =',x*y) - Subtraction Subtracts right hand operand from a – b = -10


left hand operand.
print('x / y =',x/y)
* Multiplies values on either side of a * b = 200
print('x // y =',x//y) Multiplication the operator
print('x ** y =',x**y)
/ Division Divides left hand operand by right b/a=2
print('~~~~~~~~~~~~~~~~') hand operand
a = 5*3+4-9 % Modulus Divides left hand operand by right b%a=0
b = 27/3-3 hand operand and returns
remainder
c = 1+3**2
** Exponent Performs exponential (power) a**b =10
d = a%b calculation on operators to the power 20
e = c-d // Floor Division - The division of 9//2 = 4 and
print(a,'|', b,'|',c,'|',d,'|',e) operands where the result is the 9.0//2.0 = 4.0,
quotient in which the digits after the -11//3 = -4,
check1 = c < d decimal point are removed. But if -11.0//3 = -4.0
print (check1) one of the operands is negative, the
result is floored, i.e., rounded away
x,y,z = 10,20,30 from zero (towards negative infinity)
print(x**2+2*x*+z**2) −

SLIDE 19
what is a - FUNCTION
https://docs.python.org/3/library/functions.html

Built-in Functions Functions are named blocks of code, designed to


abs() delattr() hash()
memoryview(
set() do one specific job. Information passed to a
)
function is called an argument, & information
all() dict() help() min() setattr() received by a function is called a parameter.
any() dir() hex() next() slice()
ascii() divmod() id() object() sorted()
staticmethod(
bin() enumerate() input() oct()
)
bool() eval() int() open() str()
isinstance(
breakpoint() exec() ord() sum()
)
issubclass(
bytearray() filter() pow() super()
)
bytes() float() iter() print() tuple()
callable() format() len() property() type()
chr() frozenset() list() range() vars()
classmethod(
getattr() locals() repr() zip()
)SLIDE 20
compile() globals() map() reversed() __import__()
some- BUILT-IN FUNCTIONS(Some
) Built-in Functions
name = input('Enter your name: ') input()
print('Hello,', name, '-Welcome to Python Class') dict()
print('Type of Variable Name', type(name)) eval()
temp = eval(input('Enter temp in Celsius: ')) len()
print(temp,'degree Celcius is', 9/5*temp+32,'degree Fahrenheit') format()
print('____________________________________________') type()
bill = 23.60 print()
tip = 23.60*.15
print('(15% Tip) Bill amount=', bill,'+ Tip=', tip)
print('Total Amount is ' '€{:.3f}'.format(bill))
print('____________________________________________')
print('Cost: ${:.2f}, Total: ${:.4f}'.format(tip, bill+tip))
a = 12.1691 * 0.176
print('2 Decimals {:.2f}'.format(a))
print('3 Decimals {:.3f}'.format(a))
print('7 Decimals {:.7f}'.format(a))
print('{:3d}'.format(2))
print('{:3d}'.format(25))
print('{:3d}'.format(138))
SLIDE 21
BUILT-IN FUNCTIONS…contd
EXAMPLES of - MIN() & MAX()
print("Maximum of 4,12,43.3,19,225 and 100 is : ",end="")
print (max( 4,12,43.3,19,225,100 ) )
print ('Minimim of 4.03 & 3.04 is :', min( 4.03,3.04) )
print("The word occuring 1st in dict. among given is : ",end="")
print (min( "geeks", "chandra", "algorithm", "programming" ) )
print('____________________________________________________________')

SLIDE 22
STRINGS (…)
Strings store multiple Words
String1 = 'Welcome to the Geeks World.'
String2 = "I'm going to be a Python Geek soon"
print(String1, String2) # Printing both strings
print(String1[8:14]) # Printing chars between 8th & 14th
print(String2[0], String2[-1]) # Printing first & last characters
print(String1[3:-2]) # Printing characters between 3rd and 2nd last char
LISTS […]
Lists store multiple values
List1 = [] # Creating a blank List
print(List1)
MyList = ["Apple", "Dell", "HP"]

print("List containing multiple values: ")


print(MyList[0], (MyList[2]))
List = [['Apple', 'iPod'] , ['Acer']]

print("\nMulti-Dimensional List: ")


print(List)
List = [1, 2, 4, 4, 3, 3, 3, 6, 5] # Creating a List with duplicate Numbers

print("\nList with the use of Numbers: ")


print(List)
List = [1, 2, 'Compaq', 4, 'For', 6, 'Banana'] #Creating a List with mixed type of
values
print("\nList with the use of Mixed Values: ")
print(List)
TUPLES (...)
Tuples store multiple values & are indexed
Tuple is a collection of Python objects much like a list. The
sequence of values stored in a tuple can be of any type,
and they are indexed by integers. The important difference
between a list and a tuple is that tuples are immutable
Tuple0 = ('Geeks', 'For')
print("\nTuple with the use of String: ")
print(Tuple0)

Tuple1 = (0, 1, 2, 3) # Nested Tuples


Tuple2 = ('python', 'geek')
Tuple3 = (Tuple1, Tuple2)
print("\nTuple with nested tuples: ")
print(Tuple3)
SETS (...)
Tuples store multiple values & are indexed
Set is an unordered collection of data type that is
iterable, mutable and has no duplicate elements

set1 = set() #Intial blank Set


print(set1)
set1 = set("PythonForDesigners") # Creating a Set with a String
print("\nSet with the use of String: ")
print(set1)
String = 'PythonForDesigners' # Creating a Set with a Constructor
set1 = set(String)
print("\nSet with the use of an Object: " )
print(set1)
set1 = set(["Python", "For", "Designers"]) # Creating a Set with a List
print("\nSet with the use of List: ")
print(set1)
set1 = set([1, 2, 4, 4, 3, 3, 3, 6, 5])
print("\nSet with the use of Numbers: ")
print(set1)
set1 = set([1, 2, ‘Python', 4, 'For', 6, 'Designers']) # Creating a Set with mix
print("\nSet with the use of Mixed Values")
print((set1))
DICTIONARY {…}
Dictionary maps unique keys to values.
Dict = {}
print("Empty Dictionary: ")
print(Dict)
Dict = {1: 'Python', 2: 'For', 3: 'Designers'} # Creating a Dictionary with Integer Keys
print("\nDictionary with the use of Integer Keys: ")
print(Dict)

Dict = {'Name': 'Python', 1: [1, 2, 3, 4]} # Creating a Dictionary with Mixed keys
print("\nDictionary with the use of Mixed Keys: ")
print(Dict)
Dict = dict({1: 'Python', 2: 'For', 3:'Designers'}) # Creating with dict() method

print("\nDictionary with the use of dict(): ")


print(Dict)
# Creating a Nested Dictionary
SJ_Arch = {1: {'A' : 'Studio1', 'B' : 'Studio2', 'C' : 'Studio3'},
2: {'D' : 'Township1', 'E' : 'Township2', 'F' : 'Township3'}}
print("\nNested Dictionary: ")
print(SJ_Arch)
ARRAYS […] are LISTs
Array are similar to Lists, which can hold more than one value at a time
Method Description

append() Adds an element at the end of the list


cars = ["Ford", "Volvo", "BMW"]
for x in cars: clear() Removes all the elements from the list

print(x) copy() Returns a copy of the list


print('\n..........................') count() Returns the number of elements with the
cars[0] = "Toyota" specified value

print(cars) extend() Add the elements of a list (or any iterable), to


the end of the current list

cars.append("Mecedes") index() Returns the index of the first element with the
specified value
cars.append("Mazda")
print('\n', (cars)) insert() Adds an element at the specified position

cars.remove("BMW") pop() Removes the element at the specified


position
print('\n', (cars))
remove() Removes the first item with the specified
cars.count(3) value
print('\n', (cars)) reverse() Reverses the order of the list

sort() Sorts the list


ARRAYS vs Lists
Array are similar to Lists, except that it arrays contain same type of data

MyList = [1, 2, 'Compaq', 4, 'For', 6, 'Banana']


print(MyList)

import array as arr


YrArray = arr.array(93.5, 5.6, 9.9, 2.1)
print('\n',YrArray)

MyArray = arr.array('d', [1, 3.5, "Hello"])


import array as arr
a = arr.array('d', [1.1, 3.5, 4.5])
print(a)
USER-DEFINED FUNCTIONS( )
def sum_two_numbers(a, b):
return a + b

def my_function(): # Define our 3 functions


print("Hello From My Function!")

def my_function_with_args(username, greeting):


print("Hello, %s , from this city, I wish you %s"%(username, greeting))

my_function() # print(a simple greeting)


my_function_with_args("Johnson", "good day") # print with Arguments

print(sum_two_numbers(1,2))
USER-DEFINED FUNCTIONS( )
def greet(name): def fruit_basket():
print ('Hi',name,'Good return "Mango", "Banana", "Apple", "Grapes", "Durian"
morning!')
greet('Patrick')
def essay(quality): # concatenate to each line in essay !"
def area(r): return "%s tastes nice if grown organically!" % quality
a = (22.0/7.0)*r*r
return a
L=(area(21)) def write_essay():
def add(x,y): Fruits = fruit_basket()
sum = x + y for quality in Fruits:
return sum print(essay(quality))
M=add(25,34)
print(L,'\n',M) write_essay()
USER-DEFINED FUNCTIONS( )
def sumProblem(x, y): x= sorted([5, 2, 3, 1, 4])
sum = x + y print(x)
sentence = 'The sum of {} and {} is
{}.'.format(x, y, sum) list1=[1,10,3,23,333,0,65,99]
print(('\n'), sentence) list1.sort()
def main(): print (list1)
a = int(input("Enter an integer: "))
b = int(input("Enter another integer: ")) list2 =
sumProblem(a, b) ["Bans","Trop","Indi","Firr","Bor","Borr"]
list2.sort()
sumProblem(1234567890123, 535790269358) print(list2)
print('\n')
main() list3 = ["1","10","3","22","23","4","2"]
list3.sort(key=int)
print(list3)
IF, CONDITIONAL STATEMENTs
#4 Days in a month
l=[0,1,2,3,4,5,6,7,8,9]
days = int(input('Enter number of days: '))
lo=0
if days == 28 or days == 29:
for i in l:
print('Feb')
lo=lo+100
elif days == 30:
if not l[i]<5:
print('Apr, Jun, Sep, Nov')
break
elif days == 31:
print(lo)
print('Jan, Mar, May, Jul, Aug, Oct, Dec')
else:
print('Error - Key in 28,29,39 or 31')
FOR LOOP
for i in 'abcd':
fruits = ["apple", "banana", "cherry"]
print(i)
for x in fruits:
if x == "banana":
for i in 'abcd':
break
for j in 'abcd':
print(x)
print (i, j )
print ('----')
l=[0,1,2,3,4,5,6,7,8,9]
Total=0
for i in l:
Total=Total+100
if not l[i]<5:
break
print(lo)
WHILE LOOP i = 0 # While loop & if condition.
while i < 10:
x = -20 print(i) # Add two now .
y = 20 i += 2
while x <= y: if i > 6:
print ("X is now: ", x) print ("The Value of i is ", i)
x = x + 1 break
print ("Never gets printed")

countdown, newYear = 10, 0


while countdown > newYear:
# Infinite Loop !
print (countdown)
var = 1
countdown -= 1
while var == 1 : # An infinite loop
print ('Happy New Year!')
num = input("Enter a number :")
print ("You entered: ", num)
CLASSES
def is used to define a function # Define Class
class is used to define a class class HDBunit:
So What is the class ? unit_type = "5Room"
Simply a logical grouping of data and functions def function(self):
referred to as "methods" when defined within a print("This inside HDBunit.")
class
# Create Object using Class definition
unit_x = HDBunit() #Object created
unit_y = HDBunit() #Object created

#Instantiate Objects with properties


unit_y.unit_type = " Maisonette"
print(unit_x.unit_type)
print(unit_y.unit_type)
CLASSES
class Car:
class Try:
def __init__(self,brand,model,color,fuel):
def __init__(self):
self.brand=brand
pass
self.model=model
self.color=color
def printhello(self,name):
self.fuel=fuel
print(f"Hello, {name}")
def start(self):
return name
pass
obj=Try()
def halt(self):
obj.printhello('Chandra')
pass
def drift(self):
pass

MyCar=Car('BMW','305','Black','Diesel')
YourCar=('Hyundai','Verna','Black','Diesel')
EricCar=('Mercedes','D500','Black','Diesel')

print(MyCar.fuel)
INHERITANCE class Person(object):
def __init__(self, name): # Constructor
self.name = name
def getName(self): # To get name
return self.name
def isEmployee(self): # check if employee
return False

class Employee(Person): # Inherited or Sub class


def isEmployee(self): # Here we return true
return True
# Driver code
emp = Person("Geek1") # An Object of Person
print(emp.getName(), emp.isEmployee())
emp = Employee("Geek2") # An Object of Employee
print(emp.getName(), emp.isEmployee())

Geek1 False
Geek2 True
POLYMORPHISM class Parrot:
def fly(self):
print("Parrot can fly")
def swim(self):
print("Parrot can't swim")

class Penguin:
def fly(self):
print("Penguin can't fly")
def swim(self):
print("Penguin can swim")

# common interface
def flying_test(bird):
bird.fly()

#instantiate objects
blu = Parrot()
peggy = Penguin()

# passing the object


flying_test(blu)
flying_test(peggy)
PACKAGES, MODEULES, >>> math acos frexp
acosh fsum
asin gamma
import math asinh hypot
x= math.pi atan isinf
print(x) atan2 isnan
atanh ldexp
from math import pi ceil lgamma
r = float(input ("radius : ")) copysign log
Circ= 2*pi*r cos log10
print("Circumference f the Circle is :" , r) cosh log1p
degrees modf
e pi
import math erf pow
def distance_bet_two_points(x1,x2,y1,y2): erfc radians
return math.sqrt((x1-x2)**2 + (y1-y2)**2) exp sin
res = distance_bet_two_points(1,-4,0,-1) expm1 sinh
print(res) fabs sqrt
factorial tan
floor tanh
fmod trunc
PACKAGES, MODEULES, >>> date, time
import time
import datetime

print ("Time in seconds since the epoch: %s" %time.time())


print ("Current date and time: " , datetime.datetime.now())
print ("Or like this: " ,datetime.datetime.now().strftime("%y/%m/%d %H:%M"))

print ("Current year: ", datetime.date.today().strftime("%Y"))


print ("Month of year: ", datetime.date.today().strftime("%B"))
print ("Week number of the year: ", datetime.date.today().strftime("%W"))
print ("Weekday of the week: ", datetime.date.today().strftime("%w"))
print ("Day of year: ", datetime.date.today().strftime("%j"))
print ("Day of the month : ", datetime.date.today().strftime("%d"))
print ("Day of week: ", datetime.date.today().strftime("%A"))

DOB = datetime.date(1943,3, 13) #year, month, day


print(DOB.strftime("%A"))
PACKAGES, MODEULES, >>> calender
import pandas as pd
# Create some variables
trials = [1, 2, 3, 4, 5, 6]
subj_id = [1]*6
group = ['Control']*6
condition = ['Affect']*3 + ['Neutral']*3
# Create a dictionairy
data = {'Condition':condition,
'Subject_ID':subj_id,
'Trial':trials, 'Group':group}
# Create the dataframe
df = pd.DataFrame(data)
df.head()
print(df)
PACKAGES, MODEULES, >>> pandas Excel
I/E
import pandas as pd
xlsx_source = 'd:\\360products.xlsx'
col_names = ['Col' + str(i) for i in range (1,
5)]
# Reading the excel file to a dataframe.
# Note, there's only one sheet in the example
file
df = pd.read_excel(xlsx_source,
sheet_name='ByAllProducts', skiprows=[0])
df.head()
print(df)
PACKAGES >>> beautifulsoup
import bs4
import requests

res=requests.get('http://www.boa.gov.sg/register.html')
# type(res) #What is this object
# print(res.text) #What is content of this object

soup = bs4.BeautifulSoup(res.text, 'lxml' )


type(soup)
soup.title
soup.title.name
soup.title.string
soup.title.parent.name
BEAUTIFULSOUP
import bs4
import requests

res=requests.get('http://www.boa.gov.sg/register.html')
# type(res) #What is this object
# print(res.text) #What is content of this object

soup = bs4.BeautifulSoup(res.text, 'lxml' )


type(soup)
soup.title
soup.title.name
soup.title.string
soup.title.parent.name
BEAUTIFULSOUP
import requests
from bs4 import BeautifulSoup

page = requests.get("https://www.gebiz.gov.sg/ptn/opportunity/BOListing.xhtml?origin=search")
# print(page.content)

soup = BeautifulSoup(page.content, 'html.parser')


# print(soup)
# print(soup.prettify())

tender_no= soup.findAll ('div', {'class' : 'formSectionHeader6_TEXT'})


#print(tender_no)
#_____________________________________________________________________________________________
tender_ttl= soup.find_all('a', {'class' : 'commandLink_TITLE-BLUE'})
#print(tender_ttl)

tno=[]
tttl=[]
for x in range(len(tender_no)):
print (tender_no[x].get_text())
tno.append(tender_no[x].get_text())

#print(tender_ttl)
for x in range(len(tender_ttl)):
print (tender_ttl[x].get_text())
tttl.append(tender_ttl[x].get_text())
SMALL APP- Find BMI
bmi = weight/(height*height)
print('\t\t\t BMI Calculator') while i == 'i':
print('\t\t\t this is a BMI Calculator') height = input('\nEnter height in inches(whole number) x to quit: ')
i= input('\nWhat units you want metric or imperial (m or i): ')
if height == 'x' :
while i == 'm': break
height = input(‘Enter your height input meters(decimals): ') else :
if height == 'x' : height = int(height)
break weight = int(input(‘Enter your weight input pounds(whole number):
else : '))
height = float(height) bmi = (weight*703)/(height*height)
weight = float(input('Please enter your weight input kg: '))
bmi = weight/(height*height) if bmi <= 18.5:
print('Your BMI is', bmi,'which means you are underweight.')
if bmi <= 18.5: elif bmi > 18.5 and bmi < 25:
print('Your BMI is', bmi,'which means you are underweight.') print('Your BMI is', bmi,'which means you are normal.')
elif bmi > 18.5 and bmi < 25: elif bmi > 25 and bmi < 30:
print('Your BMI is', bmi,'which means you are normal.') print('Your BMI is', bmi,'which means you are overweight')
elif bmi > 25 and bmi < 30: elif bmi > 30:
print('your BMI is', bmi,'overweight.') print('Your BMI is', bmi,'which means you are obese.')
elif bmi > 30: else:
print('Your BMI is', bmi,'which means you are obese.') print('There is an error with your input')
else: print('Please check you have entered whole numbers\n'
print('There is an error with your input') 'and decimals were asked.')
print('Please check you have entered whole numbers\n'
'and decimals were asked.') input('\n\nPlease press enter to exit.')
HTML
HTML is the standard language for creating any Web pages
HTML : Hyper Text Markup Language
HTML describes the structure of Web pages using markups
HTML elements(TAGS) are the building blocks of HTML pages
Browsers do not display the HTML tags, but use them to render the
content of the page

<!DOCTYPE html> HTML-TAGS


<html>
<head> <!DOCTYPE html> : defines this document as HTML
<title>Page Title</title> <html> element is the root element of an HTML page
</head> <head> contains meta information about the document
<title> element specifies a title for the document
<body><h1>My First Heading</h1> <body> element contains the visible page content
<p>My first paragraph.</p> <h1> element defines a large heading
<p> element defines a paragraph
</body>
</html>
HTML & TAGS
HTML is the standard language for creating any Web pages

<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
</head>

<body><h1>My First Heading</h1>


<p>My first paragraph.</p>

</body>
</html>
HTML5- TAGS samp
script
section
li select
a dfn link small
abbr div main source
address dl map span
area dt mark strong
article em meta style
aside embed meter sub
audio fieldset nav sup
b figcaption noscript table
base figure object tbody
bdi footer ol td
bdo form optgroup template
blockquote h1 - h6 option textarea
body head output tfoot
br header p th
button hr param thead
canvas html pre time
caption i progress title
cite iframe q tr
code img rb track
col input rp u
colgroup ins rt ul
data kbd rtc var
datalist keygen ruby video
dd label s wbr
del legend
RightClick+INSPECT or F12
Parsing a page with BeautifulSoup

import requests
from bs4 import BeautifulSoup

myurl =
requests.get('https://en.wikipedia.org/wiki/Python_(progra
mming_language)')
soup = BeautifulSoup(myurl.text, "lxml")
#Soup is a HTML Object
Parsing a page with BeautifulSoup
Parsing a page with BeautifulSoup
Parsing a page with BeautifulSoup
Parsing a page with BeautifulSoup
Automate web browser interaction from Python

from selenium import webdriver


from bs4 import BeautifulSoup
import time
browser = webdriver.Chrome(executable_path=r"D:\04-Download\\chromedriver.exe")
# above is path to chromedriver, replace it with your own.
browser.maximize_window()
browser.get('https://www.bloomberg.com/quote/SPX:IND')
time.sleep(5) # wait 5 seconds for the page to load the js
pageSource = browser.page_source
soup = BeautifulSoup(pageSource, 'html.parser')
prices = soup.find_all(class_='priceText__1853e8a5')
price = prices[0].text
print(price)
infograph
it’s about creating the tools so people take action

t i t l e h e r e
entrepreneurial activities
differ substantially
t i t l e h e r e depending on the type of
entrepreneurial activities
differ substantially
depending on the type of

t i t l e h e r e
entrepreneurial activities
differ substantially
depending on the type of
t i t l e h e r e
entrepreneurial activities
differ substantially
depending on the type of

SLIDE 57