Python Ckan
Python Ckan
Python Ckan
com/353/
Python Program
Python
Applications
Interpreter
Operating System
>>> 42 + 2 >>> 42 % 4
44 2
>>> 42 - 2 >>> 3 ** 4
40 81
Precedence Operator
Highest **
-
*, /, //, %
Lowest +, -
Variables and Computer Memory
>>> meaning_of_life = 42 # assignment
>>> difference
76.0
Assignment Statement
<<variable>> = <<expression>>
Memory Model
id1:int
meaning_of_life id1 42
id2:float
id2:int
double id2 84
Memory Model (cont’)
id1:int
>>> meaning_of_life = 42
meaning_of_life id3 42
>>> double = meaning_of_life * 2
double id2 84
id3:float
5.5
Something Went Wrong!
>>> 42 + foo
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name "foo" is not defined
>>> 1 +
File "<stdin>", line 1
2 +
^
SyntaxError: can't assign to literal
Types
Type Syntax example Type
category
bool True False
Text str
bytes b'Some ASCII'
bytes([119, 105, 107, 105]) Numeric int, float, complex
>>> pow(2, 4)
16
Functions That Python Provides (cont’)
abs(x, /)
Return the absolute value of the argument.
>>> help(dir)
Help on built-in function dir in module builtins:
dir(...)
dir([object]) -> list of strings
>>> convert_to_celsius(78.8)
26.0
>>> convert_to_celsius(10.4)
-12.0
Defining Our Own Functions (cont’)
>>> def convert_to_celsius(fahrenheit):
… return (fahrenheit - 32) * 5 / 9
…
>>> convert_to_celsius(80)
26.666666666666668
def <<function_name>>(<<parameters>>):
<<block>>
Using Local Variables
>>> def quadratic(a, b, c, x): >>> first
… first = a * x ** 2 Traceback (most recent call last):
… second = b * x File "<stdin>", line 1, in <module>
… third = c NameError: name 'first' is not defined
… return first + second + third
… >>> a
Traceback (most recent call last):
>>> quadratic(2, 3, 4, 0.5) File "<stdin>", line 1, in <module>
6.0 NameError: name 'a' is not defined
Working with Text
>>> 'slowpoke' >>> len('slowpoke')
>>> "psyduck" 8
>>> "Barry Allen' # SyntaxError >>> len("psyduck")
7
>>> '''This is >>> "psyduck" + " golduck"
… multi-line 'psyduck golduck'
… string'''
>>> """Me >>> len("""Me
… …
… Too!""" … Too!""") # What is the result?
True False
Boolean Operators
>>> not True Relational Operators
False > → Greater than
>>> not False < → Less than
True >= → Greater than or equal to
<= → Less than or equal to
>>> True and True == → Equal to
True != → Not equal to
If <<condition>>:
<<block>>
What if . . .
>>> ph = float(input('Enter the pH level: >>> ph = float(input('Enter the pH level:
')) '))
Enter the pH level: 6.0 Enter the pH level: 8.5
>>> if ph < 7.0: >>> if ph < 7.0:
… print(ph, "is acidic.") … print(ph, "is acidic.")
… … elif ph > 7.0:
6.0 is acidic. … print(ph, "is basic.")
… else:
… print(ph, "is neutral")
8.5 is basic.
Nested if
value = input('Enter the pH level: ') Enter the pH level: 6.0
ph 6.0 is basic
if len(value) > 0:
ph = float(value) Enter the pH level: 8.7
if ph < 7.0: ph 8.7 is basic
print(ph, "is acidic.")
elif ph > 7.0: Enter the ph level:
print(ph, "is basic.") No pH was given!
else:
print(ph, "is neutral.")
else:
print("No pH value was given!")
A Modular Approach to Program Organization
>>> help(math)
>>> 'slowpoke'.capitalize()
'Slowpoke'
>>> "Ever since my baby went away It's been the
blackest day, it's been the blackest
day".count('y')
5
Chaining Method Calls
>>> 'Computer Science'.swapcase().endswith('ENCE')
True
Using Methods
<<expression>>.<<method_name>>(<<arguments>>)
Lists
# list store sequences >>> my_list[0]
>>> my_list = [] # empty list 1
>>> your_list = [3, 4, 5] >>> my_list[-1]
>>> my_list.append(1) 3
>>> my_list.append(2) >>> my_list[4] # will Raise IndexError
>>> my_list.append(4) >>> my_list[1:3]
>>> my_list.append(3) [2, 4, 3]
>>> my_list.pop() >>> my_list[::2]
>>> my_list.append(3) [1, 4]
>>> my_list[::-1]
>>> krypton = ['Krypton', 'Kr', -157.2,
-153.4]
>>> krypton[1]
'Kr'
Modifying Lists
>>> nobles = ['helium', 'none', argon', 'krypton',
'xenon', 'radon']
>>> celegans_markers[0:4]
["Emb", "Him", "Unc", "Lon"]
>>> usefule_makers = celegans_markers[0:4]
>>> colors.append("purple")
>>> colors
["red", "orange", "green", "black, "blue", "purple"]
>>> colors.insert(2, "yellow")
>>> colors
["red", "orange", "yellow", "green", "black", "blue", "purple"]
>>> colors.remove("black")
>>> colors
["red", "orange", "yellow", "green", "blue", "purple"]
List of Lists
>>> elements = [["Copper", "Cu"], ["Tellurium", "Te"]]
>>> elements[0]
["Copper", "Cu"]
>>> elements[1]
["Tellurium", "Te"]
>>> len(elements)
2
Create a new member named name, with home address and email address.
"""
self.name = name
self.address = address
self.email = email
def hello(self):
print("Hello {}".format(self.name))
Inheritance (cont’d)
class Student(Member):
"""A student member at a university."""
Create a new student named name, with home address and email address,
student ID student_id, an empty list of courses taken, and an
empty list of current courses.
"""
https://github.com/ckan/ckan/blob/master/requirements.txt
Flask - Extensions
● flask-sqlalchemy: Adds SQLAlchemy support to Flask
● Flask-Migrate: SQLAlchemy database migrations for Flask applications.
● flask-wtf: Simple integration of Flask and WTForms, including CSRF, file upload and Recaptcha
integration.
● Flask-SocketIO: Socket.IO integration for Flask applications.
● flask-login: Flask user session management.
● flask-babel: i18n and l10n support for Flask based on Babel and pytz.
Flask - Quick start
from flask import Flask
app = Flask(__name__)
@app.route('/')
def hello():
return "Hello World"
app.run()
http://greenteapress.com/wp/think-python-2e/ http://www.diveintopython3.net/
Free Flask online resource
● The Flask mega tutorial
● Flask Quickstart
Thank You
Questions?
73