0% found this document useful (0 votes)
18 views

Lesson 1_DA

Uploaded by

tuyet phamthianh
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
18 views

Lesson 1_DA

Uploaded by

tuyet phamthianh
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 33

INTRODUCTION TO PYTHON

DA – LEVEL 3

17 April 2023
HISTORY AND
ENVIRONMENT

2
Brief History of Python
• Invented in the Netherlands, early 90s by Guido van
Rossum
• Named after Monty Python
• Considered a scripting language, but is much more
• Scalable, object oriented and functional from the beginning
• Used by Google from the beginning
• Advantage: Extensive libraries in Data Science
• Disadvantage: Slower execution time, but not a big problem.
(PyPy runs faster as an implementation of Python)
3
Setting up environment
• Python 2 versus Python 3?
Python 2 is widely used in the industry → companies aren't keen on updating their systems.
The majority of the most widely used libraries have been ported to Python 3 → safe to start a project
in Python 3 for most cases.

• How to run a Python Program – Practice with Mentor:


- Running on a server (Tip: Running at a certain time on a server)
- Running Python interactive shell: Typed on the command line
python of console or IDLE (Integrated DeveLopment
Environment).
- Running the Jupyter Notebook with Anaconda or Miniconda

4
OBJECT ORIENTED
PROGRAMMING

5
OBJECT ORIENTED
• An object is a collection of data and associated behaviors.
Python supports many different kinds of data:
1234
3.14159
"Hello"
[1, 5, 7, 11, 13]
{"CA": "California", "MA": "Massachusetts"}

• Oriented: Directed toward.


• Object-oriented: Directed towards modeling objects.
• Software Development Phase: Object Oriented Analysis
(OOA), Object-oriented design (OOD), Object-oriented
programming (OOP) 6
OBJECT ORIENTED
• Object-oriented Analysis phase (WHAT needs to be done):
System requirements are determined -> classes are identified and
the relationships among classes are identified using Object
Modelling, Dynamic Modelling, Functional Modelling
• Object-oriented Design phase (HOW the system is to be built
on concrete technologies): The model is developed further into
an object-oriented model using object-oriented design (OOD).
The technology-independent concepts in the analysis model are
mapped onto implementing classes, constraints are identified,
and interfaces are designed.
▪ The stages for object–oriented design can be identified:
▪ Define the context of the system
▪ Designing architecture
▪ Identify objects
▪ Construct design models 7
OBJECT-ORIENTED PROGRAMMING
• Object-oriented programming (OOP): The process of
converting this defined design into a working program.
• How do we differentiate between types of objects?
• Examples: We have 4 kinds of objects – Apples, Oranges,
Baskets, Barrels
UML diagram

In OOP, the term used for kinds of objects = Class.


We have 4 classes of objects
8
OBJECT-ORIENTED PROGRAMMING
• Example: A specific orange = an instance of the general
class of oranges.
• Objects are instances of classes that can be associated with
each other.
• A class can define specific sets of characteristics that are
shared by all objects of that class.
• An object instance is a specific object with its own set of
data and behaviors.

9
OOP: DATA DESCRIBES OBJECTS
• Example: Three oranges on the table could each
weigh a different amount.
• All instances of the orange class have a weight
attribute, but each orange has a different value
for this attribute.
• Attributes don't have to be unique. Any two
oranges may weigh the same amount
• Other attributes: what orchard the orange came
from, when it was picked, and how much it
weighs, where each basket is stored (location).
• Apples: a color attribute. Barrels might come in
different sizes.
• Specify the type for each attribute such as
integer, floating-point number, string, byte,
Boolean, lists, trees, or graphs, other classes.
10
OOP: BEHAVIORS ARE ACTIONS
• Example: Pick places the orange in a basket by updating the basket
attribute of the orange, and by adding the orange to the oranges list on
the Basket→ giving the Pick method a Basket parameter.
• Add a squeeze method to Orange, return the amount of juice retrieved,
while also removing the Orange from the basket it was in.
• Sell
• Discard: Oranges might go bad before we can sell them.

11
OOP: BEHAVIORS ARE ACTIONS
• Behaviors are actions that can occur on an object.
• The behaviors that can be performed on a specific class of objects are
called methods.
• At the programming level, methods are like functions in structured
programming, but they have access to all data associated with this
object.
• Like functions, methods can also accept parameters and return
values.
• Parameters to a method are a list of objects that need to be passed
into the Method. The objects that are passed in from the calling object
are usually referred to as arguments.

12
FUNCTIONS
Functions are declared with the keyword. A function contains a
block of code def with an optional use of the keyword return
def my_function(x, y):
return x + y

Python has support for so-called anonymous or lambda functions, which are a way
of writing functions consisting of a single statement. They are defined with the
lambda keyword.
def short_function(x):
return x * 2

anon = lambda x: x * 2
13
PRINCIPLES OF OBJECT-ORIENTED
PROGRAMMING
• Encapsulation (Information hiding):
Object-oriented design is to determine the public interface
Do not need to access the internal workings of the object.
Example: Television. Our interface to the television is the remote control. Each button on the
remote control represents a method that can be called on television object.
People (as the calling object) access these methods, we do not know if the television is
getting its signal from an antenna, a cable connection, or a satellite dish.

• Abstraction:
Ignore irrelevant details. Abstraction is another object-oriented concept related to
encapsulation and information hiding. Abstraction: extracting a public interface from the
inner details.
Example: A driver of a car needs to interact with steering, gas pedal, and brakes. The
workings of the motor, drive train, and brake subsystem don't matter to the driver. But a
mechanic works at a different level of abstraction: tuning the engine and bleeding the
brakes.
Abstraction is the process of encapsulating information with separate public and private
interfaces. The private interfaces can be subject to information hiding.

14
PRINCIPLES OF OBJECT-ORIENTED
PROGRAMMING
• Inheritance: Like a family tree. One class can
inherit attributes and methods from another
class
All of these classes of piece have properties: Color
and Chess set.
The hollow arrows indicate that the individual
classes of pieces inherit from the Piece class.
All subclasses automatically have a Chess_set and
Color attribute inherited from the base class.
Also have unique shapes and make different moves.
• Polymorphism: The ability to treat a class
differently depending on which subclass is
implemented.
Board object can accept a move from the player and
call the ‘move’ function on the piece. The board does
not need what type of piece it is dealing 15
MODULES AND PACKAGES
• Big project: Become difficult to find a class that needs to be
edited among the many classes.
→ Modules are simply Python files
• Package:
o A collection of modules in a folder
o __init__.py → If we forget this file, we won't be able to import
modules from that folder

16
PYTHON PROJECT STRUCTURE
Core package: sample/. Helpers.py: Assist in providing some functionality, which isn't the main goal
of the application or class.
README.rst: reStructuredText for textual data used primarily in the Python programming language
community for technical documentation.
LICENSE: Full license text claim
setup.py: Placed at the root of the Python project directory. package name, version, author, license,
minimal dependencies, entry points, data files. It serves as the command line interface via which
packaging commands may be executed. https://www.educative.io/answers/what-is-setuppy
from distutils.core import setup

setup(name='Distutils',
version='1.0',
description='Python Distribution Utilities',
author='Greg Ward',
author_email='[email protected]',
url='https://www.python.org/sigs/distutils-sig/',
packages=['distutils', 'distutils.command'],
)
https://docs.python-guide.org/writing/structure/
requirements.txt: Dependencies
docs: Writing Python documentation https://www.sphinx-doc.org/en/master/usage/quickstart.html
test: Import your packaged module to test

17
BUILT-IN DATA
STRUCTURES

18
TUPLE: IMMUTABLE
• An ordered sequence of elements can mix element types
• Fixed-length
• Immutable sequence (cannot change element values)
• The immutability of tuples means they are faster than lists.
• Example:
t = (2,"mindx",4)
t[0]
(2,"mindx",4) + (6,8)
t[1:2]
t[1:3]
[ : ] makes a copy of an entire sequence
len(t)
t[1] = 5 19
LIST: MUTABLE
• Ordered sequence of information by index
• Denoted by square brackets[]
• A list contains elements
- usually homogeneous (ie: all integers)
- can contain mixed types (not common)
• Mutable: List elements can be changed
assigning to an element at an index changes the value
L = [2, 1, 3]
L[1] = 5
→ L = [2, 5, 3]
20
OPERATIONS
The + operator: Create a concatenation
>>> (1, 2, 3) + (4, 5, 6)
(1, 2, 3, 4, 5, 6)

>>> [1, 2, 3] + [4, 5, 6]


[1, 2, 3, 4, 5, 6]

21
OPERATIONS

• The * operator: Create original “repeats”

>>> (1, 2, 3) * 3

>>> [1, 2, 3] * 3
OPERATIONS ON LISTS ONLY
>>> t = [1, 2, 3, 4, 5]

>>> t.append(‘a’)
>>> t

>>> t.insert(2, ‘b’)


>>> t

>>> t.extend([9, 8, 7])


>>> t

>>> t.append([9, 8, 7])


>>> t

• extend takes a list as an argument


• append takes a singleton as an argument
OPERATIONS ON LISTS ONLY
Lists have many methods, including index, count, remove, reverse, sort
>>> t = [‘a’, ‘b’, ‘c’, ‘b’]
>>> t.index(‘b’) # index of 1st occurrence

>>> t.count(‘b’) # number of occurrences

>>> t.remove(‘b’) # remove 1st occurrence


>>> t

>>> t = [5, 2, 6, 8]
>>> t.reverse() # reverse the list

>>> t.sort() # sort the list


DICTIONARIES: MUTABLE
• Dictionaries: Pairs of keys and values (key:value)
>>> t = {"a": “mindx", "b": [1, 2, 3, 4]}
>>> t[7] = "an integer“
>>> t
>>> t[‘b’]

25
ITERATIONS/
CONTROL FLOW

26
CONTROL FLOW: IF,ELIF,ELSE
if x < 0:
print("It's negative")
elif x == 0:
print("Equal to zero")
elif 0 < x < 3:
print("Positive but smaller than 5")
else:
print("Positive and larger than or equal to 5")

27
CONTROL FLOW:WHILE
while <condition>:
<expression>

• <condition> evaluates to a Boolean.


• If <condition> is True, all steps inside the while code block will be
done.
• Then check <condition> again.
• Repeat until <condition> is False
n = 4
while n > 0:
print(n)
n = n – 1
print(‘Done')
print(n)
CONTROL FLOW: FOR
• Each time <variable> takes a value through the loop.
• First time, <variable> starts at the smallest value.
• Then next time, <variable> gets the previous value + 1.

for variable in collection:


<expression>

29
BREAK
Skips remaining expressions in code block.
Terminate only innermost loop. Any outer
for loops will continue to run!
for i in range(3):
for j in range(3):
if j > i:
break
print((i, j))

30
CONTINUE
Skips the remainder of the block.
sequence = [1, 2, None, 4, None, 5]
total = 0
for value in sequence:
if value is None:
continue
total += value
(Sums up integers in a list and skips None values)

31
Practice with Mentor
• Install Ubuntu on WSL2 Windows.
• Install Python on Windows, OSX, Linux (Ubuntu).
• Install Anaconda or Miniconda to run Jupyter Notebook
• Practice with file Lesson 1_Mentor.ipynb
• Homework: Lesson 1_homework_no solution.ipynb with
Getter and Setter methods

32
THANK YOU !

You might also like