Introduction First Steps Data Structures Programming Exercises

Introduction to Python

Dr. Ronald B¨ock,Olga Egorow

Otto-von-Guericke-Universit¨atMagdeburg, Fakult¨atf¨urElektrotechnik und Informationstechnik, Institut f¨urInformations- und Kommunikationstechnik, Lehrstuhl f¨urKognitive Systeme

1 / 26 Introduction First Steps Data Structures Programming Exercises

• Based on the AI course of the University of California, Berkeley • http://ai.berkeley.edu/project_overview.html

2 / 26 Introduction First Steps Data Structures Programming Exercises

What is Python?

• General-purpose, high-level programming language • Supports multiple programming paradigms (imperative, object-oriented and functional) • Developed in the late 80s/early 90s by Guido van Rossum

3 / 26 Introduction First Steps Data Structures Programming Exercises

First Steps

• Python can be either interpreted or compiled • Start on unix systems: type python on the command prompt • IDEs: IDLE, Gedit, NetBeans, Spyder...

4 / 26 Introduction First Steps Data Structures Programming Exercises

First Steps (cont.)

• Short explanation of different data types • int: “normal” integer numbers (from approx. -2,000,000,000 to 2,000,000,000, long for bigger numbers) • float: floats (from approx. −3.4 · 1038 to 3.4 · 1038, double for more precise numbers) • string: chains of characters • boolean: true or false

5 / 26 Introduction First Steps Data Structures Programming Exercises

First Steps (cont.)

• Operators: • 2 + 3 = 5; 2 - 3 = -1; 2 * 3 = 6; 2 / 3 = 0; 2.0 / 3.0 = 0.6666; 2 % 3 = 2; 2 ** 3 = 8 • 2 == 3 = False; 2 !=(<>) 3 = True; 2 > 3 = False; 2 <= 3 = True • c = a + b; c += a is equivalent to c = c + a (also possible: -=, *= etc.) • Strings: • ’artificial’ + ”intelligence” = ’artificialintelligence’ • ’HELP’.lower = ’help’, ’help’.UPPER = ’HELP’, len(’Help’) = 4

6 / 26 Introduction First Steps Data Structures Programming Exercises

First Steps (cont.)

• Getting help: >>> s = ’ abc ’ >>> d i ( s ) [’ a d d ’,’ c l a s s ’,...’ s t r ’, ’capitalize’, ’center’, ... ’zfill’] >>> help ( s . f i n d ) f i n d ( . . . ) S.find(sub [,start [,end]]) −> i n t Return the lowest index in S where substring sub i s found, such that sub i s contained within s[start ,end]. ... >>> s.find(’b’) 1

7 / 26 Introduction First Steps Data Structures Programming Exercises

Data Structures: Lists

• lists store a sequence of mutable items: >>> fruits = [’apple’,’orange’,’pear’, ’ banana ’ ] >>> f r u i t s [ 0 ] ’ a p p l e ’

• + for concatenation >>> otherFruits = [’kiwi’,’strawberry’] >>> fruits + otherFruits >>> [’apple’,’orange’,’pear’, ’banana’,’kiwi ’,’strawberry ’]

8 / 26 Introduction First Steps Data Structures Programming Exercises

Data Structures: Lists (cont.)

>>> fruits = [’apple’,’orange’,’pear’, ’ banana ’ ] >>> f r u i t s [ −2] ’ pear ’ >>> fruits .pop() ’ banana ’ >>> f r u i t s [’apple’,’orange’,’pear’] >>> fruits .append(’grapefruit ’) >>> f r u i t s [’apple’,’orange’,’pear’,’grapefruit ’] >>> f r u i t s [ −1] = ’pineapple’ >>> f r u i t s [’apple’,’orange’,’pear’,’pineapple’]

9 / 26 Introduction First Steps Data Structures Programming Exercises

Data Structures: Lists (cont.)

>>> fruits = [’apple’,’orange’,’pear’, ’pineapple ’] >>> fruits [0:2] [ ’apple’,’orange’] >>> f r u i t s [ : 3 ] [’apple’,’orange’,’pear’] >>> f r u i t s [ 2 : ] [’pear’,’pineapple’] >>> len ( f r u i t s ) 4

10 / 26 Introduction First Steps Data Structures Programming Exercises

Data Structures: Lists (cont.)

• the stored items can be of any data type >>> lstOfLsts = [[’a’,’b’,’c’],[1,2,3], [’one’,’two’,’three’]] >>> lstOfLsts [1][2] 3 >>> lstOfLsts [0].pop() ’ c ’ >>> l s t O f L s t s [[’a’, ’b’],[1, 2, 3],[’one’, ’two’, ’three’]]

11 / 26 Introduction First Steps Data Structures Programming Exercises

Data Structures: Tuples

• similar to list, but immutable after creation • surrounded with parentheses and not square brackets >>> p a i r = ( 3 , 5 ) >>> p a i r [ 0 ] 3 >>> x , y = p a i r >>> x 3 >>> y 5 >>> p a i r [ 1 ] = 6 TypeError : object does not s u p p o r t item assignment

12 / 26 Introduction First Steps Data Structures Programming Exercises

Data Structures: Sets

• unsorted data structure with no duplicate items • important: the objects are unordered, no access to an element via number >>> shapes = [’circle ’,’square’, ’triangle’,’circle ’] >>> setOfShapes = set ( shapes ) >>> setOfShapes set ([’circle ’,’square’,’triangle’]) >>> setOfShapes.add( ’polygon ’) >>> setOfShapes set ([’circle ’,’square’,’triangle’, ’polygon ’]) >>> ’ c i r c l e ’ in setOfShapes True >>> ’ rhombus ’ in setOfShapes F a l s e 13 / 26 Introduction First Steps Data Structures Programming Exercises

Data Structures: Sets (cont.)

>>> favoriteShapes = [’circle ’,’triangle’, ’ hexagon ’ ] >>> setOfFavoriteShapes = set (favoriteShapes) >>> setOfShapes − setOfFavoriteShapes set ([ ’square’,’polygon’]) >>> setOfShapes & setOfFavoriteShapes set ([’circle ’,’triangle’]) >>> setOfShapes | setOfFavoriteShapes set ([’circle ’,’square’,’triangle ’,’polygon’, ’hexagon ’])

14 / 26 Introduction First Steps Data Structures Programming Exercises

Data Structures: Dictionaries

• store maps from one type of object (the key) to another (the value) • the key must be an immutable type (string, number, tuple) • the keys are not ordered >>> studentIds = { ’knuth’: 42.0, ’turing’: 56.0, ’nash’: 92.0 } >>> studentIds[ ’turing ’] 56.0 >>> studentIds[’nash’] = ’ninety −two ’ >>> s t u d e n t I d s { ’knuth’: 42.0, ’turing’: 56.0, ’nash’: ’ninety −two ’ } >>> del studentIds[ ’knuth’] >>> s t u d e n t I d s { ’turing’: 56.0,’nash’: ’ninety −two ’ } 15 / 26 Introduction First Steps Data Structures Programming Exercises

Data Structures: Dictionaries (cont.)

>>> studentIds[’knuth’] = [42.0,’forty −two ’ ] >>> s t u d e n t I d s { ’knuth’: [42.0, ’forty −two ’ ] , ’turing’: 56.0, ’nash’: ’ninety −two ’ } >>> studentIds.keys() [’knuth’, ’turing’, ’nash’] >>> studentIds.values() [[42.0, ’forty −two’], 56.0, ’ninety −two ’ ] >>> studentIds.items() [(’knuth’ ,[42.0, ’forty −two ’ ] ) , (’turing ’ ,56.0),( ’nash’,’ninety −two ’ ) ] >>> len (studentIds) 3

16 / 26 Introduction First Steps Data Structures Programming Exercises

Programming: Writing Scripts

• s. foreach.py • important: indentation (tabs vs. spaces) # This is what a comment looks like fruits = [’apples’,’oranges’,’pears’, ’ bananas ’ ] f o r f r u i t in f r u i t s : p r i n t f r u i t + ’ f o r s a l e ’ fruitPrices = { ’apples’: 2.00, ’oranges’: 1.50, ’pears’: 1.75} f o r fruit , price in fruitPrices.items(): i f p r i c e < 2 . 0 0 : p r i n t ’%s c o s t %f a pound ’ % (fruit , price) e l s e : p r i n t f r u i t + ’ a r e too expensive! ’ 17 / 26 Introduction First Steps Data Structures Programming Exercises

Programming: Writing Functions

fruitPrices = { ’apples ’:2.00, ’oranges’:1.50,’pears’: 1.75}

def buyFruit(fruit , numPounds): i f f r u i t not in fruitPrices: p r i n t ”We don ’ t have %s” % (fruit) e l s e : cost = fruitPrices[fruit] ∗ numPounds p r i n t ”That ’ l l be %f please” % (cost)

# Main Function i f name == ’ m a i n ’: buyFruit(’apples ’ ,2.4) buyFruit(’coconuts ’ ,2) 18 / 26 Introduction First Steps Data Structures Programming Exercises

Programming: Writing Classes

• an object encapsulates data and provides functions for interacting with that data • encapsulating the data prevents it from being altered or used inappropriately • abstraction provided by objects makes it easier to write general-purpose code • s. shop.py def i n i t (self , name, fruitPrices): self.fruitPrices = fruitPrices self .name = name p r i n t ’ Welcome to the %s shop’ % (name)

19 / 26 Introduction First Steps Data Structures Programming Exercises

Programming: Using Objects

• import the class and create objects import shop shopName = ’My Bowl ’ fruitPrices = { ’apples’: 1.00, ’oranges’:1.50, ’pears’: 1.75} myShop = shop.FruitShop(shopName, fruitPrices) applePrice = myShop.getCostPerPound( ’apples ’) p r i n t a p p l e P r i c e p r i n t ( ’ Apples c o s t $%.2 f at %s . ’ % (applePrice , shopName))

20 / 26 Introduction First Steps Data Structures Programming Exercises

Programming: Using Objects (cont.)

• create personclass.py c l a s s Person : population = 0 def i n i t (self , myAge): self .age = myAge Person.population += 1 def g e t population(self ): return Person. population def g e t a g e ( s e l f ) : return s e l f . age

21 / 26 Introduction First Steps Data Structures Programming Exercises

Programming: Using Objects (cont.)

• Static vs. Instance Variables >>> import p e r s o n c l a s s >>> p1 = p e r s o n class .Person(12) >>> p1 . g e t population() 1 >>> p2 = p e r s o n class .Person(63) >>> p1 . g e t population() 2 >>> p2 . g e t population() 2 >>> p1 . g e t a g e ( ) 12 >>> p2 . g e t a g e ( ) 63

22 / 26 Introduction First Steps Data Structures Programming Exercises

Cheat Sheet Python Execution

• Windows/Mac using python IDLE • open the py-file using python IDLE (right-click -¿ edit with IDLE) • go to run -¿ run script • using terminal • go to the folder containing the py-file • execute using python cd /home/.../ project −0/ t u t o r i a l python myScript.py

23 / 26 Introduction First Steps Data Structures Programming Exercises

Now You: Question 1

• Look at addition.py def add ( a , b ) : ” Return the sum o f a and b” ”∗∗∗ YOUR CODE HERE ∗∗∗” return 0

• add your code • grade your code using autograder.py

24 / 26 Introduction First Steps Data Structures Programming Exercises

Now You: Question 2

• Look at buyLotsOfFruit.py • add a buyLotsOfFruit(oderList) function • takes a list of (fruit,pound) tuples • returns the cost of your list • if there is some fruit in the list that does not appear in fruitPrices, it should print an error message and return None Cost of [(’apples’, 2.0),(’pears’, 3.0), (’limes’, 4.0)] i s 12.25

• grade your code using autograder.py

25 / 26 Introduction First Steps Data Structures Programming Exercises

Now You: Question 3

• Look at shopSmart.py and shop.py • add a shopSmart(oders,shops) function • takes an orderList and a list of FruitShop • returns the FruitShop where your order costs the least amount in total orders1 = [( ’apples’ ,1.0),(’oranges’ ,3.0)] orders2 = [(’apples’ ,3.0)] d i r 1 = { ’apples’: 2.0, ’oranges’:1.0 } shop1 = shop.FruitShop(’shop1’,dir1) d i r 2 = { ’apples’: 1.0, ’oranges’: 5.0} shop2 = shop.FruitShop(’shop2’,dir2) shops = [shop1, shop2]

• grade your code using autograder.py

26 / 26