0% found this document useful (0 votes)
2 views42 pages

EE2108 Week 1 Python Basics

The document outlines the course EE2108: Data Structures and Algorithms in Python, focusing on Python basics and object-oriented programming. It provides contact information for the instructor, course content, and an overview of Python's features, including its data types, operators, and programming constructs. Additionally, it includes instructions for installing Python and using Jupyter Notebook for coding.

Uploaded by

T28kumar
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)
2 views42 pages

EE2108 Week 1 Python Basics

The document outlines the course EE2108: Data Structures and Algorithms in Python, focusing on Python basics and object-oriented programming. It provides contact information for the instructor, course content, and an overview of Python's features, including its data types, operators, and programming constructs. Additionally, it includes instructions for installing Python and using Jupyter Notebook for coding.

Uploaded by

T28kumar
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/ 42

EE2108: Data Structures and

Algorithms in Python
Week 1: Python Basics
Wang Lipo
[email protected]

EE2108 / 0
Contact Information: Wang Lipo

School of EEE
Office: S1-B1C-98
Office Phone: 6790 6372
Email: [email protected]

EE2108 / 1 1
Consultation

Email

Or make an appointment

Or just drop by at any time

Your suggestions/comments
are always welcome!

EE2108 / 2 2
Course Content
Topics

Week 1 Introduction to Object-Oriented Programming


A/P Wang Lipo Using Python
([email protected])
S1-B1c-98 / 6790-6372
Weeks 2 – 7 Overview on Data Structures and Algorithms.
A/P Li Kwok Hung Growth Rates of Functions. Recurrences.
([email protected]) Elementary Data Structures. Abstract Data
S1-B1b-63 / 6790-5028 types. Stacks and Queues. Trees. Heaps.
Binary Search Trees. Sorting Algorithms.

Weeks 8 – 13 Binary Search. Graph Basics. Breadth-First


A/P Wang Lipo Search. Depth-First Search. Kruskal’s
([email protected]) Algorithm. Dijkstra’s Algorithm. Web Search
S1-B1c-98 / 6790-6372 & Text Classification.
The covered topics for each teaching week can be found in the file
Weekly Study Guide.
EE2108 / 3 3
What is Python? Why Python?
❑ Python is a popular high-level programming language
Closer to human language than low-level
programming languages, e.g., Assembly, that directly
interact with hardware
“Easy” to learn
❑ Powerful
Numerous, all-encompassing libraries
Enormously popular in artificial intelligence
❑ Free! (forever?)
Unlike MATLAB, etc
❑ Python basics in 1.5 hours!
More examples in tutorial no.1

EE2108 / 4
Python Types and Operators

EE2108 / 5
The Python Interpreter

❑ Python is an interpreted language


 No need to compile first and then run like C++
❑ Commands are executed through the Python
interpreter
 The interpreter runs the command and reports the result of the
command
 Similar to DOS/UNIX before Windows – back to simplicity!
❑ A programmer defines a series of commands in
advance and saves those commands in a text file
known as source code or a script (a Python program)
❑ Source code is conventionally stored in a file named
with the .py suffix (e.g., demo.py) or in a Jupyter
Notebook file *.ipynb

EE2108 / 6
An Example Python Program

EE2108 / 7
Object-Oriented Programming: Class

A class in Python is a software construct that includes:

❑ fields (also called data fields): to provide data


specification, and/or
❑ methods: functions operating on data

This combining of data and operations is called


encapsulation

Classes correspond to concepts with common


properties and common behavior

An object is an instance of a class, corresponds to


actualization of general concepts

EE2108 / 8
Classes vs Objects: an Example

Country class: Country object:

• name
Map of Poland

• population
• area
• loan
• compute population
density
• get international loan

EE2108 / 9
Identifiers
❑ For identifying a variable, function, class, etc.
❑ Identifiers in Python are case-sensitive, so temperature
and Temperature are distinct names
❑ Identifiers can be composed of almost any
combination of letters, numerals, and underscore
characters
❑ An identifier cannot begin with a numeral
❑ There are 33 specially reserved words that cannot be
used as identifiers:

EE2108 / 10
Python’s built-in Classes

❑ int: integers
❑ float: floating-point values
❑ bool: Boolean values
❑ list: a sequence of objects
❑ str: character strings
❑ set: an unordered set of distinct objects
❑ dict: dictionary (aka associative mapping)

EE2108 / 11
The int Class

❑ The int class represents integer values


❑ int( )
◼ int( ) = 0
◼ int(3.14) = 3; int(-3.9) = -3 (truncated)
◼ int(‘137’) = 137

EE2108 / 12
The float Class

❑ The float class represents floating-point values


 The floating-point equivalent of an integral number 2 is 2.0
 6.022e23 represents the mathematical value 6.022×1023
❑ float( )
 float( ) = 0.0
 float(2) = 2.0
 float(‘3.14’) = 3.14

EE2108 / 13
The bool Class

❑ The bool class represents logical (Boolean)


values, with only two instances:
◼ True
◼ False
❑ bool( )
◼ bool( ) = False
◼ bool(x) = False if x=0 or [ ], bool(x) = True if x != 0 or [ ]

EE2108 / 14
The list Class: a sequence of objects

❑ Elements of a list may be arbitrary objects (including the None


object)
❑ Lists are array-based sequences and a list of length n has
elements indexed from 0 to n−1 inclusive
❑ Lists have the ability to dynamically expand and contract their
capacities as needed
❑ Python uses the characters [ ] as delimiters for a list
[ ] is an empty list
[‘red’, ‘green’, ‘blue’] is a list containing three string
instances
❑ list( )
list( ) = [ ]
list(‘hello’) = [‘h’, ‘e’, ‘l’, ‘l’, ‘o’]

EE2108 / 15
The str Class

❑ Strings can be expressed with single quotes, as


in ‘hello’, or double quotes, as in "hello"
❑ A string can also begin and end with 3 single or
double quotes, if it contains newlines

EE2108 / 16
The set Class: an unordered collection

❑ Python uses curly braces { and } as delimiters for a set


 For example, {17}, {‘red’, ‘green’, ‘blue’}
 { } does not represent an empty set! The set contains a space
 {} is an empty set
 set( ) returns an empty set (spaces inside function calls are
ignored)

EE2108 / 17
The dict Class

❑ dict class represents a dictionary, or mapping,


from a set of distinct keys to associated values
❑ A nonempty dictionary is expressed using a
comma-separated series of key:value pairs
 For example, the dictionary {‘sg’ : ‘Singapore’, ‘de’ :
‘Germany’} associates ‘sg’ to ‘Singapore’ and ‘de’ to
‘Germany’
 { } is an empty dict

EE2108 / 18
Calling Methods
❑ Methods (also known as member functions) are
invoked on a specific instance of a class using
the dot (“.”) operator
❑ For example, Python’s list class has a method
named sort that can be invoked with a syntax
such as data.sort( ), which rearranges the
contents of the list data so that they are sorted

EE2108 / 19
The Assignment Statement

❑E.g., temperature = 98.6

EE2108 / 20
Expressions and Operators

❑ Existing values can be combined into


expressions using special symbols and keywords
known as operators
❑ The semantics of an operator depends upon the
type of its operands. For example,
 when a and b are numbers, the syntax a + b indicates
addition of a and b
 while if a and b are strings, the syntax a + b indicates
concatenation of a and b

EE2108 / 21
Logical Operators

EE2108 / 22
Equality Operators

❑ Python supports the following operators to test


two notions of equality:

EE2108 / 23
Comparison Operators

❑ Data types may define a natural order via the


following operators:

❑ These operators defined for both numeric types


and lexicographically (case-sensitive)

EE2108 / 24
Arithmetic Operators

❑ For addition, subtraction, and multiplication, if both


operands have type int, then the result is an int; if
one or both operands have type float, the result is a
float
❑ True division is always of type float, integer division
is always int (with the result truncated)

EE2108 / 25
Sequence Operators

❑ Each of Python’s built-in sequence types (e.g., str


and list) support the following operator syntaxes:

EE2108 / 26
Sequence Comparisons

❑Sequences define comparison operations


based on lexicographic order, performing an
element by element comparison until the first
difference is found
For example, [5, 6, 9] < [5, 7] because of the entries
at index 1 (the 2nd elements)

EE2108 / 27
Python Functions and Control Flow

EE2108 / 28
Conditionals

EE2108 / 29
While Loops

EE2108 / 30
For Loops

EE2108 / 31
Continue

❑ continue causes the current loop iteration to stop, but


with subsequent passes of the loop proceeding as
expected
❑ If nested loops, only the inner most loop in which continue
resides, e.g., only the second (inner) for loop below:

EE2108 / 32
Break

❑ break immediately terminates a while or for loop

EE2108 / 33
Functions

❑ Functions are defined using the keyword def


❑ The return statement returns the value for this function
and terminates its processing

EE2108 / 34
Input
❑ Displays a prompt and then waits until the user enters
some sequence of characters followed by the return
key
❑ The return value of the function is the string of
characters that were entered before the return key

EE2108 / 35
Files

❑ Files are opened with a built-in function, open, that


returns an object for the underlying file
❑ For example, the command, fp = open(‘sample.txt’),
attempts to open a file named sample.txt

EE2108 / 36
Python Installation and Usage

EE2108 / 37
Python Installation on Windows
❑Step 1: Install Anaconda
▪ https://www.anaconda.com/
▪ If you are now learning to code in Python, you can download the
latest version of Python
▪ You would need older versions of Python only if you wish to use some existing
Python programs that require older versions of Python
▪ Download the installation file for your particular computer (e.g., 64-
bit or 32-bit). The installation may take a few minutes.

❑Step 2: Start Anaconda Navigator from


Windows Start Menu or Desktop
▪ The first time starting Anaconda Navigator may take a little while,
with possible window disappearances and reappearances.

EE2108 / 38
Use Jupyter Notebook
❑ Step 3: Start Jupyter Notebook in Anaconda
This will open Jupyter Notebook in your default web
browser:

EE2108 / 39
Python Coding with Jupyter Notebook
1. Click the "New" button on the right and select "Python 3" to create a new
Jupyter Notebook.

2. Type the following Python code in a cell:

3. To run the code, press Shift + Enter or click the "Run" button in the toolbar
You should see the following output:

EE2108 / 40
Python Coding with Jupyter Notebook
4. To download the code that you wrote into a file for later use, click File and
select Download, then “as Notebook”. You should see your new Jupyter
Notebook file in “Download” directory:

5. To upload an existing Jupyter Notebook file, click Upload, select your file, and
then click upload. You should be able to find your newly uploaded file in the file
list below. Click the file name to open the file.

Happy Programming!

EE2108 / 41

You might also like