Python For Architects 1
Python For Architects 1
Python For Architects 1
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
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 ?
JAV
A
C#, C++
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”
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
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("___________")
SLIDE 19
what is a - FUNCTION
https://docs.python.org/3/library/functions.html
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"]
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
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
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")
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
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()
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
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
page = requests.get("https://www.gebiz.gov.sg/ptn/opportunity/BOListing.xhtml?origin=search")
# print(page.content)
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>
<head>
<title>Page Title</title>
</head>
</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
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