You are on page 1of 19

Introduction to Data Science

March 2015

Python fundamentals

Luís A. Nunes Amaral

Amaral Lab 0
Data Types
Type Values Operations
None None
Boolean True, False and, or, in, not, …
Number Integer, float, fraction, complex *, +, -, %, //, **
Tuple Ordered immutable sequence of Create
values of any type
List Ordered sequence of values of any append, index, pop, …
type
Set Unordered “bag” of unique add, update, union,
immutable values intersection, …
Dictionary Unordered “bag” of key-value pairs update, pop, …
String Sequences of Unicode characters Concatenation, removal, …
Byte and Byte Binary value or array of values
array (such as a PNG image file)

Amaral Lab 1
Boolean type
Beware: None, 0 from any numerical type, and empty
set/list/string/dictionary all default to False.

Beware: Not has higher priority than and and or (i.e., it is performed first).

and False True or False True


False False False False False True
True False True True True True

not False True in a c


True False [a, b] True False

Comparison Smaller than Smaller than Equal Not equal Object


or equal identity
Syntax < <= == != is

Amaral Lab 2
Number type
Beware: Operations with mixed types convert to a more “complex” type.

Operation Syntax Order of operations


Add & subtract + - ()
Multiply & divide * / **
Integer division // * and /
Integer division remainder % //
Raise to power ** %
Make integer int() + and -
Make float float()
Make complex complex(a, b)
Make fraction Fraction(a, b)

Amaral Lab 3
Tuples
Tuples are immutable ordered sequences of data accessible by
index.

a_tuple = ( 1, 5, “hello!”, True )  Cannot be changed after it is created!!

a_tuple[2] returns 5

a_tuple[1:3] returns ( 5, “hello!” )

a_tuple[:2] returns ( 1, 5 )

a_tuple[-1] returns True

a_tuple[2:] returns ( “hello!”, True )


a_tuple[::-1] returns reverted order tuple
len( a_tuple ) returns the number of indices in a_tuple
Amaral Lab 4
Lists
Lists are mutable ordered sequences of data accessible by index.

a_list = [ 1, “1”, Fraction(1, 3), ( 1, 5, “hello!”, True ) ]

a_list[2] returns Fraction(1, 3)


a_list[1:3] returns [1, Fraction(1, 3) ]
a_list[:2] returns [ 1, “1” ]
a_list[-1] returns [ 1, 5, “hello!”, True ]
a_list[2:] returns [ Fraction(1, 3), ( 1, 5, “hello!”, True ) ]
a_list[::-1] returns reverted order list
len( a_list ) returns the number of indices in a_list

Amaral Lab 5
Lists
Lists are mutable ordered sequences of data accessible by index.

a_list = [ 1, “1”, Fraction(1, 3), ( 1, 5, “hello!”, True ) ]

a_list.append(“3”) returns None


a_list now returns [ 1, “1”, Fraction(1, 3), ( 1, 5, “hello!”, True ), “3” ]
a_list.remove(1) returns None
a_list now returns [ “1”, Fraction(1, 3), ( 1, 5, “hello!”, True ), “3” ]

a_list.pop() returns “3”


a_list now returns [ “1”, Fraction(1, 3), ( 1, 5, “hello!”, True ) ]
a_list.pop(0) returns “1”
a_list now returns [ Fraction(1, 3), ( 1, 5, “hello!”, True ) ]
del a_list[0] returns None
a_list now returns [ ( 1, 5, “hello!”, True ) ]
Amaral Lab 6
Lists
Lists are mutable ordered sequences of data accessible by index.

b_list = [ 1, “1”, ( 1, 5, “hello!”, True ) ]


c_list = [ complex(1 , 3), 1 ]

b_list + c_list returns [ 1, “1”, ( 1, 5, “hello!”, True ), complex(1 , 3), 1 ]


b_list.extend( c_list ) returns [ 1, “1”, ( 1, 5, “hello!”, True ), complex(1 ,
3), 1 ]

b_list.index(1) returns 0
b_list.index( “3” ) raises a ValueError exception

Amaral Lab 7
Sets
Sets are unordered “bags” of unique immutable “keys”.

a_set = { 1, “1”, Fraction(1, 3), ( 1, 5, “hello!”, True ) }


b_set = { complex(1 , 3), 1 }

a_set.add(“3”)
a_set now returns { 1, Fraction(1, 3), “3”, ( 1, 5, “hello!”, True ), “1” }
a_set.update( b_set )
a_set now returns { Fraction(1, 3), ( 1, 5, “hello!”, True ), 1, “1”,
complex(1 , 3), “3” }
a_set.pop() returns, for example, 1  randomly selected!!!
a_set now returns { “1”, Fraction(1, 3), ( 1, 5, “hello!”, True ), complex(1 ,
3) }

a_set.discard(1) returns None


a_set.remove(1) raises a KeyError exception

Amaral Lab 8
Sets
Sets are unordered “bags” of unique immutable “keys”.

set() creates an empty set


a_set.clear() returns set()

len( a_set ) returns the number of keys in a_set

a_set.union( b_set )
a_set.intersection( b_set )
a_set.difference( b_set )
a_set.symmetric_difference( b_set )

a_set.issubset( b_set )
a_set.issuperset( b_set )

Amaral Lab 9
Dictionaries
Dictionaries are unordered “bags” of pairs of key/value. Keys
must be unique immutable data, i.e., form a set.

a_dict = { 1: “1”, “two”: Fraction(1, 3), “3”: [ 1, 5, “hello!”, True ] }

a_dict[“four”] = “3”  add new key/value pair


a_dict now returns { 1: “1”, “3”: [ 1, 5, “hello!”, True ], “four”: “3”,
“two”: Fraction(1, 3) }

a_dict[“four”] = “4”  re-writes value if key exists


a_dict now returns { “two”: Fraction(1, 3), “3”: ( 1, 5, “hello!”, True ),
“four”: “4”, 1: “1” }

len( a_dict ) returns the number of keys in a_dict

Amaral Lab 10
Dictionaries
Dictionaries are unordered “bags” of pairs of key/value. Keys
must be unique immutable data, i.e., form a set.

a_dict = { 1: “1”, “two”: Fraction(1, 3), “3”: [ 1, 5, “hello!”, True ] }


b_dict = { “b”: [ complex(1 , 3), 1 ] }

a_dict.update( b_dict ) returns None


a_dict now returns { 1: “1”, “two”: Fraction(1, 3), “3”: [ 1, 5, “hello!”,
True ] , “b”: [ complex(1 , 3), 1 ] }

a_dict.pop(“b”) returns [ complex(1 , 3), 1 ]


a_dict is now { 1: “1”, “two”: Fraction(1, 3), “3”: [ 1, 5, “hello!”, True ] }

Amaral Lab 11
Strings
Strings are immutable sequences of Unicode characters.

Human-readable characters are encoded as computer-readable binary


words. There are many possible encodings!

Unicode was developed to solve the multiple encoding problem. Unicode


represents every letter, number, and ideogram as a 4-byte word.

a_string = “two”
b_string = ‘hello’

a_string + b_string returns “twohello”

a_string[2] returns “o”


b_string[2:] returns “llo”

len( a_string ) returns the number of characters in a_string

Amaral Lab 12
Strings
Strings are immutable sequences of Unicode characters.

a_string = “two”
b_string = ‘hello’

a_string.capitalize() returns “Two”


a_string.lowercase() returns “two”
a_string.uppercase() returns “TWO”

b_string.replace(“o”, “”) returns “hell”

b_string.split(“e”) returns [ “h”, “ll” ]


“hey you”.split() returns [“hey”, “you” ]

“ hey you ”.strip() returns “hey you”

Amaral Lab 13
Strings
Strings are immutable sequences of Unicode characters.

We can use strings to format output.

first_name = “Luis”
last_name = “Amaral”
“My name is {0} {1}.\n”.format( first_name, last_name )

name = [ first_name, last_name ]


“My name is {0}[0] {0}[1] \n.\n”.format( name )

“I’m {0:.0f} years old.\n”.format( 46.7 )

Amaral Lab 14
Flow control
Command Type
for x in a_list: Loop
commands
while ( expression is True ): Conditional loop
commands
break Breaks out of lowest
enclosing loop
continue Interrupts lowest
enclosing loop and
continues with next
iteration
pass Syntax

Amaral Lab 15
Flow control
Command Type
if expression1 is True : Condition
commands
elif expression2 is True :
commands
else:
commands
try: Exception handling
commands
except exception_type:
commands
raise exception_type( a_string ) Exception raising
with command as object: Ensuring execution of
commands paired commands

Amaral Lab 16
Flow control
Command Type
def function_name( arguments ): Function
””” String with information on function””” (if something is
whitespace or return
commands is missing it returns
return something None)
lambda arguments: expression
new_list = [ expression for x in a_list for y in b_list List comprehension
if condition ]
new_list = { expression for x in a_list for y in b_list Set comprehension
if condition } (removes repeats)

Amaral Lab 17
Exception handling
Exception Type Type
SyntaxError Syntax
IndentationError Syntax
NameError Access Calling object that has not been created
AttributeError Access Attribute does not exist in object
KeyError Access Key does not exist in dictionary or set
IndexError Access Index does not exist in list or tuple
ZeroDivisionError Operation
TypeError Operation Types cannot be operated together
ValueError Operation Value cannot be operated upon

Amaral Lab 18

You might also like