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

Week 1 2 Python Fundamentals

The document discusses a lecture on Python installation, fundamentals, and programming concepts. It covers downloading and installing Anaconda and Python, creating Jupyter notebooks, variable types, arithmetic and string operations, data structures like lists, tuples, dictionaries and sets, defining functions, and control flows like conditionals, loops, exceptions handling using break, continue, and try-except blocks. The lecture aims to provide students with foundational knowledge of Python programming.

Uploaded by

Jiaqi MEI
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
58 views

Week 1 2 Python Fundamentals

The document discusses a lecture on Python installation, fundamentals, and programming concepts. It covers downloading and installing Anaconda and Python, creating Jupyter notebooks, variable types, arithmetic and string operations, data structures like lists, tuples, dictionaries and sets, defining functions, and control flows like conditionals, loops, exceptions handling using break, continue, and try-except blocks. The lecture aims to provide students with foundational knowledge of Python programming.

Uploaded by

Jiaqi MEI
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 43

IDAT7215

Computer Programming for


Product Development and
Applications

Lecture 1-2: Python Installation and


Python Fundamentals

Dr. Zulfiqar Ali


Python Installation
Python Installation

▪ Download and Install Anaconda


– https://www.anaconda.com/products/individual
– Choose your OS system, Recommend the 64-bit version
– Install with the default configuration
Launch Jupyter Notebook ▪ Open Anaconda Navigator.
Launch Jupyter Notebook
Create your first notebook
Create your first notebook

Code Cell
Set Your Script Name
Python fundamentals
Outline

▪ Variables and Types in Python

▪ Data Structures in Python

▪ Python Functions

▪ Control Flows
Variables and Types

▪ Variable
– Specific, case-sensitive name
– Call up value through variable name

▪ In Python, we do not have to explicitly


declaim the type of the variable (e.g.,
‘dog_name’) in any way.

▪ Python automatically detected the type


of a variable.

Rules of Variable Name: https://www.w3schools.com/python/python_variables.asp


Python Types

▪ The type of a variable can be


queried by using the built-in function
type.

▪ The type of a variable is not fixed.


Basic data types in Python

▪ Basic data types


– int (integers)
– float (floating-point number)
– str (string)
– bool (boolean: True or False)
– …
▪ The name of types act as conversion
operators between types
Arithmetic Operations in Python

▪ Python supports the following basic arithmetic operations:


Operator Operation Example
= Assign a value to a variable >>> a = 2 #a=2
+ Addition >>> a = 199 + 201 # a = 400
- Subtraction >>> a = 200 – 300 # a = -100
* Multiplication >>> a = 15.2 * 3 # a = 45.6
/ Division (Remark: it always returns a float) >>> a = 15 / 2 # a = 7.5
// Floor division (or integer division) >>> a = 15 // 2 #a=7
** Power >>> a = 4 ** 3 # a = 64
% Remainder >>> a = 15 % 2 #a=1
String Operations in Python

▪ Create a string
– A string is a sequence of characters.
– The characters are specified either between single (‘)
or double (“) quotes
– E.g., a = “abc” or a = ‘abc’

▪ Concatenate strings
– ‘+’ operator
– join
String Operations in Python

▪ Repeat a string

▪ Tokenize a string

▪ Replace
Data Structures In Python

▪ Lists

▪ Tuples

▪ Dictionaries

▪ Sets
Lists

▪ Probably the most fundamental data


structure in Python.
▪ A list contains arbitrary number of
elements that stored in sequential order.
▪ The elements are separated by commas
and written between square brackets.
▪ Indexing begins from 0
▪ The elements don’t need to be of the
same type.
▪ The elements of a list can be any type,
including “List” itself.
▪ List is mutable.
Common Operations on List

▪ Get or set the i-th element in a list by


indexing with square brackets

▪ Get or set elements in a list by slicing


with square brackets
– General format for slicing:
a[first:last:step]

inclusive not inclusive


Common Operations on List

▪ Sorting sequences
– sort: it modifies the original list
– sorted: it returns a new sorted list and
leaves the original list unchanged.
– The parameter reverse=True (both to
sort and sorted) can be given to get
descending order of elements
Common Operations on List

▪ Concatenate lists
– +: return a new list. The original list is unchanged
– extend: modify a list in place
– append: add a single element to the end of a list
➢ If append another list onto a list, it will treat another list
as a single object
Tuples

▪ Tuples are lists’ immutable cousins.

▪ Pretty much anything you can do to a


list that doesn’t involve modifying it,
you can do to a tuple.

▪ Tuples are defined by using


parentheses (or nothing) instead of
square brackets.
Tuples

▪ Tuples are a convenient way to return


multiple values from functions
Dictionaries

▪ Dictionary associates values with


keys.

▪ Dictionary can be created by listing


the comma separated key-value
pairs in curly brackets. Keys and
values are separated by a colon.

▪ Dictionary allows to quickly retrieve


the value corresponding to a given
key using square brackets.
Sets

▪ Set represents a collection of unique


elements.

▪ Set can be created by listing its elements


between curly brackets.

▪ Set can also be created by using set()


itself
Sets

▪ Sets are used for two main


reasons:
– Very fast membership checking
(in is a very fast operation on
sets
– Find the unique items in a
collections

▪ Sets are used less frequently


than lists and dictionaries
Data Structures In Python

Can we change the Are the items in the


Type Example Description content within this collection ordered
collection? stored?
List: an mutable,
list [1, 2, 3] Yes – mutable Yes – ordered
ordered collection
Tuple: an immutable,
tuple (1, 2, 3) No – immutable Yes – ordered
ordered collection
Set: Unordered
set {1, 2, 3} collection of unique Yes – mutable No – unordered
values
Dictionary: Unordered
dict {'a':1, 'b':2, 'c':3} Yes – mutable No – unordered
(key, value) mapping
Python Functions

▪ A function is a rule for taking zero or more


inputs and returning a corresponding out
by performing a sequence of operations.

▪ When you define a function, you specify


the name and the sequence of operations.

▪ Later, you can “call” the function by name.

▪ In Python, a function is defined with def


statement.
Python Functions

function name input parameter


def statement
docstring documents the purpose of the function

return statement
return value
Python Functions

▪ Function parameter can also be given default values.


Python Functions

▪ In addition to positional arguments we have seen so far, a function call can


also have named arguments.

▪ Note that the named arguments didn’t need to be in the same order as in the
function definition. The named arguments must come after the positional
arguments.
Control Flows in Python

▪ With control flow, you can execute certain code blocks conditionally and/or
repeatedly: these basic building blocks can be combined to create
sophisticated programs.

▪ Three different categories for control flows


– Loops for repetitive tasks (while, for)
– Decision making with the if-else statement
– Exception-Handling (break, continue, try-except)
Loops for repetitive tasks

▪ In Python we have two kinds of loops: while and for

▪ While loop is used to execute a block of statements repeatedly until a


given condition is satisfied.
Loops for repetitive tasks

▪ For loop are used for sequential traversal.

▪ At each iteration, the variable i refers to another value from the list in order.
Decision making with the if statement

▪ The if-else statement is used to decide whether a certain statement or


block of statements will be executed or not.
– if a certain condition is true then a block of statement is executed otherwise not.
General form of an if-else statements
Exception handling

▪ Sometimes, you will find that you will need to handle for exceptions.

▪ The exceptions could be invalid operations (e.g., divide by 0 or compute the


square root of a negative number) or a class of values that you simply are not
interested in.

▪ To handle these exceptions, you can use


– Break
– Continue
– Try-except
Break

▪ break statement is only allowed inside a loop body.

▪ When break executes, the loop terminates.

▪ In practical use, a break statement is usually used with if statement to


break a loop conditionally.
Break

▪ Breaking the loop, when the wanted element is found


Continue

▪ Continue statement is only allowed inside a loop body.

▪ When continue executes, the current iteration of the loop terminates, and
the execution continues with next iteration of the loop.

▪ In practical use, a continue statement is usually used with if statement to


executes conditionally.
Continue

▪ Stopping current iteration and continuing to the next one (do not break the
loop).
Try-except

▪ Unhandled exceptions will cause your program to crash. You can handle
them using try and except statement
▪ If the code in the try block works, the except block is skipped.
▪ If the code in the try block fails, it jumps to the except section.

Without the try block, the


program will crash and raise
an error.
Try-except
https://www.w3schools.com/python/default.asp

You might also like