02 Python Basics
02 Python Basics
2
Outline
• Quick Python Syntax • Defining and Using
• Variables and Objects Functions
• Operators • Objects and Classes
• Built-In Types: Simple Values • Errors and Exceptions
• Built-In Data Structures • Iterators
• Control Flow • List Comprehensions
• Generators
3
Quick Python Syntax
• Comments are marked by #.
# Comments
• Quotation marks (" ') can
also be used to enter """
Multi-line comment often
comments. used in documentation
"""
• Use \ to extend a statement
"Single-line Comment"
on the next line.
• Semicolon ; can optionally
terminate a statement.
4
Quick Python Syntax
• In Python, code blocks
are denoted by
indentation.
• Four spaces are usually
used.
• Which code snippet
always prints x?
5
Quick Python Syntax
• Parentheses are for:
• Grouping
• Calling
6
Outline
• Quick Python Syntax • Defining and Using
• Variables and Objects Functions
• Operators • Objects and Classes
• Built-In Types: Simple Values • Errors and Exceptions
• Built-In Data Structures • Iterators
• Control Flow • List Comprehensions
• Generators
7
Variables and Objects
• Python variables are pointers
to objects.
8
Variables and Objects
• If we have two
variable names
pointing to the
same mutable
object, then
changing one will
change the other
as well!
9
Variables and Objects
• Numbers, strings, and other simple types are immutable.
10
Variables and Objects
• Everything is an object
11
Outline
• Quick Python Syntax • Defining and Using
• Variables and Objects Functions
• Operators • Objects and Classes
• Built-In Types: Simple Values • Errors and Exceptions
• Built-In Data Structures • Iterators
• Control Flow • List Comprehensions
• Generators
12
Arithmetic Operators
13
Bitwise Operators
14
Comparison Operators
15
Assignment Operators
• Assignment is evaluated from
right to left.
• There is an augmented
assignment operator
corresponding to each of the
binary arithmetic and bitwise
operators.
16
Boolean Operators
• The Boolean operators
operate on Boolean values:
• and
• or
• not
• Can be used to construct
complex comparisons.
17
Identity and Membership Operators
18
Outline
• Quick Python Syntax • Defining and Using
• Variables and Objects Functions
• Operators • Objects and Classes
• Built-In Types: Simple Values • Errors and Exceptions
• Built-In Data Structures • Iterators
• Control Flow • List Comprehensions
• Generators
19
Python Scalar Types
20
Integers and Floats
• Integers are variable-precision, no overflow is possible.
21
Strings
• Strings in Python are created with single or double quotes.
• The built-in function len() returns the string length.
• Any character in the string can be accessed through its index.
22
None and Boolean
• Functions that do not return value return None.
• None variables are evaluated to False.
23
Outline
• Quick Python Syntax • Defining and Using
• Variables and Objects Functions
• Operators • Objects and Classes
• Built-In Types: Simple Values • Errors and Exceptions
• Built-In Data Structures • Iterators
• Control Flow • List Comprehensions
• Generators
24
Built-In Data Structures
• There are four built in Python data structures.
25
Lists
• List are ordered and mutable.
• A list can hold objects of any
type.
• Python uses zero-based
indexing.
• Elements at the end of the list
can be accessed with negative
numbers, starting from -1.
26
Lists
• Slicing is a means of accessing
multiple values in sub-lists.
[start : end+1 : inc]
• Negative step reverses the list.
• Both indexing and slicing can be used
to set elements as well as access
them.
27
Tuples
• Tuples are similar to lists, but are immutable.
• Can be defined with or without parentheses ().
• Functions return multiple values as tuples.
28
Dictionaries
• Dictionaries are flexible mappings of keys to values.
• They can be created via a comma-separated list of
key:value pairs within curly braces.
29
Sets
• Sets are unordered collections of unique items.
• They are defined using curly brackets { }.
• Set operations include union, intersection, difference and
symmetric difference.
30
Outline
• Quick Python Syntax • Defining and Using
• Variables and Objects Functions
• Operators • Objects and Classes
• Built-In Types: Simple Values • Errors and Exceptions
• Built-In Data Structures • Iterators
• Control Flow • List Comprehensions
• Generators
31
Conditional Statements: if, elif, and
else
• if statements in Python have optional elif and else
parts.
32
for Loops
• The for loop is repeated for each index returned by the
iterator after in.
33
for Loops
• The range(start, end+1, inc) has default zero start and
unit increment.
34
while Loops
• The while loop iterates as long as the condition is met.
35
break and continue: Fine-Tuning Your
Loops
• The continue statement skips the remainder of the current
loop, and goes to the next iteration.
Prints odd
numbers
36
break and continue: Fine-Tuning Your
Loops
• The break statement breaks out of the loop entirely.
37
Outline
• Quick Python Syntax • Defining and Using
• Variables and Objects Functions
• Operators • Objects and Classes
• Built-In Types: Simple Values • Errors and Exceptions
• Built-In Data Structures • Iterators
• Control Flow • List Comprehensions
• Generators
38
Defining Functions
• Functions are defined with the def statement.
• The following function returns a list of the first N Fibonacci
numbers.
• Calling it:
39
Default Argument Values
• You can have default values for arguments.
40
*args and **kwargs: Flexible Arguments
• Functions can be defined using *args and **kwargs to
capture variable numbers of arguments and keyword
arguments.
Tuple
Dictionary
41
Outline
• Quick Python Syntax • Defining and Using
• Variables and Objects Functions
• Operators • Objects and Classes
• Built-In Types: Simple Values • Errors and Exceptions
• Built-In Data Structures • Iterators
• Control Flow • List Comprehensions
• Generators
42
Objects and Classes
• Python is object-oriented programming language.
• Objects bundle together data and functions.
• Each Python object has a type, or class.
• An object is an instance of a class.
• Accessing instance data:
object.attribute_name
• Accessing instance methods:
object.method_name(parameters)
43
String Objects
• String objects are instances of class str.
45
String Objects
s = 'The cat\'s tail \n is \t long.'
print(s)
• Accept the escape character
The cat's tail
\. is long.
s = ''بايثون
print(s)
s_utf8 = s.encode('utf-8')
print(s_utf8)
b'\xd8\xa8\xd8\xa7\xd9\x8a\xd8\xab\xd9
\x88\xd9\x86'
46
Date and Time Objects
from datetime import datetime, date, time
• The built-in Python dt = datetime(1999, 8, 16, 8, 30, 0)
print(dt.day)
datetime module provides
datetime, date, and time 16
types. dt2 = datetime(2000, 8, 16, 8, 30, 0)
• Such objects can be delta = dt2 - dt
dt3 = dt2 + delta
formatted and accept - and print(dt3.strftime('%d/%m/%Y %H:%M'))
+ operands.
17/08/2001 08:30
47
File Objects
• Files can be opened for read, write or append.
f = open('myfile.txt', 'w')
f.write('Line 1\n')
f.write('Line 2\n')
f.close()
f = open('myfile.txt', 'r')
for line in f:
print(line.strip()) Line 1
Line 2
f.close()
48
Classes
• New class types can be defined using class keyword.
class Animal(object):
def __init__(self, name='Animal'): # Constructor
print('Constructing an animal!')
self.name = name
if name == 'Cat':
self.meows = True # Attribute
else:
self.meows = False
super(Animal, self).__init__()
50
Runtime Errors
1. Referencing an undefined
variable
2. Unsupported operation
3. Division by zero
52
try…except…else…finally
• Python also support else and finally
53
Outline
• Quick Python Syntax • Defining and Using
• Variables and Objects Functions
• Operators • Objects and Classes
• Built-In Types: Simple Values • Errors and Exceptions
• Built-In Data Structures • Iterators
• Control Flow • List Comprehensions
• Generators
54
Iterators
• Iterators are used in for loops and can be used using
next()
55
Iterators
• The range iterator
• enumerate iterator
L=[2,4,6,8,10]
list(enumerate(L)
56
Outline
• Quick Python Syntax • Defining and Using
• Variables and Objects Functions
• Operators • Objects and Classes
• Built-In Types: Simple Values • Errors and Exceptions
• Built-In Data Structures • Iterators
• Control Flow • List Comprehensions
• Generators
57
List Comprehensions
• A way to compress a list-building for loop into a single short,
readable line.
• Syntax: [expr for var in iterable]
58
List Comprehensions
• Lists comprehensions can be used to construct sets with no
duplicates.
• Or dictionaries
59
Outline
• Quick Python Syntax • Defining and Using
• Variables and Objects Functions
• Operators • Objects and Classes
• Built-In Types: Simple Values • Errors and Exceptions
• Built-In Data Structures • Iterators
• Control Flow • List Comprehensions
• Generators
60
Generators
• A list is a collection of values, while a generator expression is
a recipe for producing values.
61
Generators
• A generator function uses yield to yield a sequence of
values.
62
Homework 2
• Solve the homework on Python Basic Programming
63
Summary
• Quick Python Syntax • Defining and Using
• Variables and Objects Functions
• Operators • Objects and Classes
• Built-In Types: Simple Values • Errors and Exceptions
• Built-In Data Structures • Iterators
• Control Flow • List Comprehensions
• Generators
64