Lab 5: Function Types, Lists and Dictionaries, Sorting. Ling 1330/2330: Computational Linguistics Na-Rae Han

Size: px
Start display at page:

Download "Lab 5: Function Types, Lists and Dictionaries, Sorting. Ling 1330/2330: Computational Linguistics Na-Rae Han"

Transcription

1 Lab 5: Function Types, Lists and Dictionaries, Sorting Ling 1330/2330: Computational Linguistics Na-Rae Han

2 Objectives Assignment review Pig Latin Tokenization function Two types of function: returning vs. void Building a list, list methods Dictionary, dict methods Counting with dict Sorting a sequence with sorted() 9/11/2018 2

3 Pig Latin def vowelindex(wd) : def getinitialcs(wd) : return wd[:vowelindex(wd)] def gettherest(wd) : return wd[vowelindex(wd):] Showcases strength of functions. A fairly complex behavior has been modeled in a neatly modular fashion. def piglatinword(wd) : if wd[0] in 'aeiou' : return wd + 'way' else : return gettherest(wd) + getinitialcs(wd) + 'ay' def piglatinsent(sent) : piglatinword('') Traceback (most recent call last): if wd[0] in 'aeiou': IndexError: string index out of range The function has a critical flaw. What? 9/11/2018 3

4 Pig Latin: more robust def vowelindex(wd) : def getinitialcs(wd) : return wd[:vowelindex(wd)] def gettherest(wd) : return wd[vowelindex(wd):] def piglatinword(wd) : if len(wd) == 0 : return '' elif wd[0] in 'aeiou' : return wd + 'way' else : return gettherest(wd) + getinitialcs(wd) + 'ay' def piglatinsent(sent) : Addresses fringe cases. Function is more robust. piglatinword('') '' Any other improvements? 9/11/2018 4

5 Pig Latin: 'y' is a vowel sometimes piglatinword('yellow') 'ellowyay' piglatinword('ploy') 'oyplay' Good. 'y' is a consonant Also good. 'y' is a part of a diphthong piglatinword('python') 'onpythay' vowelindex('python') 4 getinitialcs('python') 'pyth' Simply adding 'y' in 'aeiou' will not work. (WHY?) Not good. 'y' is a vowel here but not treated as one. To properly handle words with 'y' as the initial vowel, vowelindex() function must be further refined. 9/11/2018 5

6 Better tokenization sent = 'rose is a rose is a rose is a rose.' sent.split() ['rose', 'is', 'a', 'rose', 'is', 'a', 'rose', '.'] sent = 'Rose is a rose is a rose is a rose.' sent.split() ['Rose', 'is', 'a', 'rose', 'is', 'a', 'rose.'] joke = "Knock knock, who's there?" joke.split() ['Knock', 'knock,', "who's", 'there?'].split() is too simple as a tokenizer. We need a better tokenizer: - folds case - separates out symbols 9/11/2018 6

7 Lower, space out symbols, then split "Knock knock, who's there?".lower().replace().split() "knock knock, who's there?" "knock knock, who ' s there? " ['knock', 'knock', ',', 'who', "'", 's', 'there', '?'] 9/11/2018 7

8 Tokenizer function, first try A function that tokenizes a sentence: def gettokens(sent) : new = sent.lower() new = new.replace(",", ", ").replace("'", " ' ").replace("?", "? ") return new.split().replace("'", " ' ") inserts a space before and after ' joke = "Knock knock, who's there?" gettokens(joke) ['knock', 'knock', ',', 'who', "'", 's', 'there', '?'] Why " ' " instead of just " '"? Success! '?' is its own word. 9/11/2018 8

9 Tokenizer function, first try A function that tokenizes a sentence: def gettokens(sent) : new = sent.lower() new = new.replace(",", ", ").replace("'", " ' ").replace("?", "? ") return new.split() But there are so many more symbols:. : # $! joke = "Knock knock, who's there?" gettokens(joke) ['knock', 'knock', ',', 'who', "'", 's', 'there', '?'] This replace line is about to become a mile long! 9/11/2018 9

10 Tokenizer function, second try A function that tokenizes a sentence: def gettokens(sent) : new = sent.lower() for s in ",.!?':;#$" : new = new.replace(s, " "+s+" ") return new.split().replace(s, " "+s+" ") inserts a space before and after each symbol s joke = "Knock knock, who's there?" gettokens(joke) ['knock', 'knock', ',', 'who', "'", 's', 'there', '?'] pal = "A man, a plan, a canal: Panama." gettokens(pal) ['a', 'man', ',', 'a', 'plan', ',', 'a', 'canal', ':', 'panama', '.'] Looks good! 9/11/

11 Tokenizer function 2 minutes A function that tokenizes a sentence: def gettokens(sent) : new = sent.lower() for s in ",.!?':;#$" : new = new.replace(s, " "+s+" ") return new.split() joke = "Knock knock, who's there?" gettokens(joke) ['knock', 'knock', ',', 'who', "'", 's', 'there', '?'] pal = "A man, a plan, a canal: Panama." gettokens(pal) ['a', 'man', ',', 'a', 'plan', ',', 'a', 'canal', ':', 'panama', '.'] 9/11/

12 Value-returning functions vs. Void functions (aka "printing" functions) 9/11/

13 Two function types: returning vs. void def ahoyfy(word) : return word.replace('o', '-ahoy-') def ahoyprint(word) : print(word.replace('o', '-ahoy-')) return x print(x) ahoyfy('cola') 'c-ahoy-la' ahoyprint('cola') c-ahoy-la Seems to work similarly. What's the difference? 9/11/

14 Returning vs. printing def ahoyfy(word) : return word.replace('o', '-ahoy-') def ahoyprint(word) : print(word.replace('o', '-ahoy-')) return x print(x) ahoyfy('cola') 'c-ahoy-la' ahoyprint('cola') c-ahoy-la RETURNS a string (Note the quotes '') PRINTS a string 9/11/

15 Only returned value can be assigned def ahoyfy(word) : return word.replace('o', '-ahoy-') def ahoyprint(word) : print(word.replace('o', '-ahoy-')) return x print(x) foo = ahoyfy('cola') foo 'c-ahoy-la' foo = ahoyprint('cola') c-ahoy-la foo foo is assigned to the returned string Printing happens during assignment statement, and 9/11/

16 Void functions implicitly return None def ahoyfy(word) : return word.replace('o', '-ahoy-') def ahoyprint(word) : print(word.replace('o', '-ahoy-')) return None When there is no return statement, function implicitly returns None. foo = ahoyfy('cola') foo 'c-ahoy-la' foo = ahoyprint('cola') c-ahoy-la foo foo's value is nothing! 9/11/

17 Returned values can be reused def ahoyfy(word) : return word.replace('o', '-ahoy-') def ahoyprint(word) : print(word.replace('o', '-ahoy-')) ahoyfy('cola').upper() 'C-AHOY-LA' len(ahoyfy('cola')) 9 len(ahoyprint('cola')) ahoyfy returns string, can be fed into another function that takes string input c-ahoy-la Traceback (most recent call last): File "<pyshell#17>", line 1, in <module> len(ahoyprint('cola')) TypeError: object of type 'NoneType' has no len() ahoyprint returns None, which has no length! 9/11/

18 Python data types int: integer float: floating point number 'Bart' 'Hello, world!' str: string (a piece of text) ['cat', 'dog', 'fox', 'hippo'] list ('gold', 'silver', 'bronze') tuple {'Homer':36, 'Marge':36, 'Bart':10, 'Lisa':8, 'Maggie':1} dict: (dictionary) maps a value to an object 9/11/

19 Changing list entry li = [1,2,3] li [1, 2, 3] li[2] = 10 li [1, 2, 10]?? ani = ['fox', 'owl', 'dog'] ani ['fox', 'owl', 'dog']?? ani[1] = 'bat' ani ['fox', 'bat', 'dog'] 9/11/

20 Changing list entry li = [1,2,3] li [1, 2, 3] li[2] = 10 li [1, 2, 10] ani = ['fox', 'owl', 'dog'] ani ['fox', 'owl', 'dog'] ani[1] = 'bat' ani ['fox', 'bat', 'dog'] A new assignment statement updates an existing list entry 9/11/

21 Adding to a list li = [1,2,3] li [1, 2, 3]?? li.append(4) li [1, 2, 3, 4] ani = ['fox', 'owl', 'dog'] ani ['fox', 'owl', 'dog']?? ani.append('cat') ani ['fox', 'owl', 'dog', 'cat'] 9/11/

22 Adding to a list li = [1,2,3] li [1, 2, 3] li.append(4) li [1, 2, 3, 4] ani = ['fox', 'owl', 'dog'] ani ['fox', 'owl', 'dog'] ani.append('cat') ani ['fox', 'owl', 'dog', 'cat'].append(x) adds a single item at the end 9/11/

23 .append() syntax li = [1,2,3] li [1, 2, 3] li.append(4) li [1, 2, 3, 4] ani = ['fox', 'owl', 'dog'] ani ['fox', 'owl', 'dog'] ani.append('cat') ani ['fox', 'owl', 'dog', 'cat'] Note the syntax!! li.append(4) This part is never, ever necessary for.append() li = li.append(4) 9/11/

24 Pig Latin sentence translator def piglatinsent(sent) : """Takes a sentence, returns its Pig Latin translation. """ tran = [] for w in sent.lower().replace('.', '').split(): tran.append(piglatinword(w)) return ' '.join(tran).capitalize() + '.' 9/11/

25 Adding to a list li = [1,2,3] li [1, 2, 3] li.append(4) li [1, 2, 3, 4]???? li.extend([5,6,7]) li [1, 2, 3, 4, 5, 6, 7]?? li.insert(1, 1.5) li [1, 1.5, 2, 3, 4, 5, 6, 7] 9/11/

26 Adding to a list li = [1,2,3] li [1, 2, 3] li.append(4) li [1, 2, 3, 4] li.extend([5,6,7]) li [1, 2, 3, 4, 5, 6, 7] li.insert(1, 1.5) li [1, 1.5, 2, 3, 4, 5, 6, 7].append(x) adds a single item at the end.extend(list) adds a list of items at the end.insert(i,x) inserts an item at index i 9/11/

27 .append() vs..extend() li = [1, 2] li.append(3) li [1, 2, 3] li.extend([4,5]) li [1, 2, 3, 4, 5] li.append([6,7]) li [1, 2, 3, 4, 5, [6, 7]] len(li) 6 List inside a list! [6,7] is appended as a single element. li has length 6 9/11/

28 .extend() vs. + li = [1, 2, 3] li.extend([4, 5, 6]) li [1, 2, 3, 4, 5, 6] li + [7, 8, 9] [1, 2, 3, 4, 5, 6, 7, 8, 9] li [1, 2, 3, 4, 5, 6] + also extends a list, but it creates and returns a NEW list. li is NOT affected. 9/11/

29 More list methods.index().count().remove().pop() No time to cover in class. You should learn them on your own. Study the Python Tutorials, etc. 9/11/

30 dict: a dictionary data type {'Homer':36, 'Marge':36, 'Bart':10, 'Lisa':8, 'Maggie':1} A dictionary of the Simpson family members' age {'go':'went', 'eat':'ate', 'see':'saw', 'say':'said'} A dictionary of verb past tense Dictionaries store a mapping between a set of keys and a set of values. Keys can be any immutable type: string, integer, tuple Values can be any type (can also be mixed types) There is no inherent order (unlike lists and tuples) You can define, modify, view, lookup, and delete the key-value pairs in the dictionary. 9/11/

31 No order, dictionary lookup en2es = {'cat':'gato', 'dog':'perro', 'tiger':'tigre'} en2es {'cat': 'gato', 'dog': 'perro', 'tiger': 'tigre'} en2es['cat'] 'gato' en2es['dog'] 'perro' Looking up is done through key Don't be fooled! There is no real order. 9/11/

32 Dictionary lookup errors en2es = {'cat':'gato', 'dog':'perro', 'tiger':'tigre'} en2es {'cat': 'gato', 'dog': 'perro', 'tiger': 'tigre'} en2es['platypus'] Traceback (most recent call last): File "<pyshell#31>", line 1, in <module> en2es['platypus'] KeyError: 'platypus' en2es['gato'] Traceback (most recent call last): File "<pyshell#32>", line 1, in <module> en2es['gato'] KeyError: 'gato' Key does not exist in dictionary Dictionary is one way. Cannot look up based on the value. Mapping can be many-to-one 9/11/

33 Checking if something's in a dictionary en2es {'cat': 'gato', 'dog': 'perro', 'tiger': 'tigre'} 'platypus' in en2es False 'cat' in en2es True "in" tests if a key is in a dictionary 'gato' in en2es False "in" does not work with value 9/11/

34 Practice: getplural() 2 minutes Write a "pluralizer" function plu = {'man':'men', 'goose':'geese', 'mouse':'mice', 'child':'children'} def getplural(noun) : if noun in plu : return plu[noun] else: return noun + 's'?? getplural('cat') 'cats' getplural('goose') 'geese' 9/11/

35 Practice: getplural() Write a "pluralizer" function plu = {'man':'men', 'goose':'geese', 'mouse':'mice', 'child':'children'} def getplural(noun) : if noun in plu : return plu[noun] else : return noun + 's' If noun is in the irregular pl noun dictionary, return the dict value getplural('cat') 'cats' getplural('goose') 'geese' 9/11/

36 Updating vs. adding new entry 35 {'Homer': 36, 'Marge': 36, 'Bart': 10, 'Lisa': 8} {'Homer': 36, 'Marge': 36, 'Bart': 10, 'Lisa': 8, 'Maggie': 1} sim = {'Homer':36, 'Marge':35, 'Bart':10, 'Lisa':8} sim['marge'] sim['marge'] = 36 sim sim['maggie'] = 1 sim key does not exist! Creates a new key and gives value key already exists. Updates its value. 9/11/

37 Deleting entry {'Homer': 36, 'Marge': 36, 'Bart': 10, 'Lisa': 8, 'Maggie': 1} {'Homer': 36, 'Marge': 36, 'Lisa': 8, 'Maggie': 1} sim del sim['bart'] sim del deletes a key and its value from a dictionary 9/11/

38 Finding out what's in sim = {'Lisa':8, 'Marge':35, 'Bart':10, 'Homer':36} sim.keys()?? dict_keys(['lisa', 'Marge', 'Bart', 'Homer']) sim.values()?? dict_values([8, 35, 10, 36]) 9/11/

39 Finding out what's in sim = {'Lisa':8, 'Marge':35, 'Bart':10, 'Homer':36} sim.keys() dict_keys(['lisa', 'Marge', 'Bart', 'Homer']) sim.values() dict_values([8, 35, 10, 36]).keys() returns a quasi-list of keys,.values() returns a quasi-list of values. The orders match! 9/11/

40 .keys().values(): list-like, but not quite sim.keys() dict_keys(['lisa', 'Marge', 'Bart', 'Homer']) dict_values([8, 35, 10, 36]) sim = {'Lisa':8, 'Marge':35, 'Bart':10, 'Homer':36} sim.values() for v in sim.values() : print(v) len(sim.keys()) sum(sim.values()) Quasi-lists: These behave very much like a list, but not always sim.keys()[2] Traceback (most recent call last): File "<pyshell#56>", line 1, in <module> sim.values()[2] TypeError: 'dict_keys' object does not support indexing 9/11/

41 .items() to reference (key, value) pairs sim {'Lisa': 8, 'Marge': 35, 'Bart': 10, 'Homer': 36} sim.items() dict_items([('lisa', 8), ('Marge', 35), ('Bart', 10), ('Homer', 36)]).items() returns a quasi-list of (key, value) pairs 9/11/

42 Iterating through (key, value) pairs sim {'Lisa': 8, 'Marge': 35, 'Bart': 10, 'Homer': 36} sim.items() dict_items([('lisa', 8), ('Marge', 35), ('Bart', 10), ('Homer', 36)]) for (k, v) in sim.items() : print(k, 'is', v, 'years old.') Lisa is 8 years old. Marge is 35 years old. Bart is 10 years old. Homer is 36 years old..items() lets you reference key and its value side by side as (k, v) in a for loop! 9/11/

43 Iterating through keys sim {'Lisa': 8, 'Marge': 35, 'Bart': 10, 'Homer': 36} for k in sim : print(k, 'is', sim[k], 'years old.') Lisa is 8 years old. Marge is 35 years old. Bart is 10 years old. Homer is 36 years old. Looping through keys then accessing value through dict[key]. Does the same thing! 9/11/

44 Common dict application: counting 3 tally = {'gold':1, 'bronze':3} tally['bronze'] newmedals = ['bronze', 'silver', 'gold', 'gold', 'silver'] for m in newmedals : tally[m] += 1 Traceback (most recent call last): File "<pyshell#80>", line 2, in <module> tally[m] += 1 KeyError: 'silver' Error: 'silver' is not yet in the dictionary as a key 9/11/

45 Initial key created, value set to 1 3 tally = {'gold':1, 'bronze':3} tally['bronze'] newmedals = ['bronze', 'silver', 'gold', 'gold', 'silver'] for m in newmedals : if m not in tally : else : tally[m] = 1 tally[m] += 1 Make sure to account for the initial key creation & assignment tally {'bronze': 4, 'gold': 3, 'silver': 2} 9/11/

46 Dictionary of frequency count chars = list('abracadabra') chars ['a', 'b', 'r', 'a', 'c', 'a', 'd', 'a', 'b', 'r', 'a'] freq = {} for c in chars: if c in freq: freq[c] += 1 else: freq[c] = 1 freq {'r': 2, 'a': 5, 'b': 2, 'c': 1, 'd': 1} Initialize an empty dictionary For loop through list, tally up the counts 9/11/

47 Try it out 2 minutes chars = list('abracadabra') chars ['a', 'b', 'r', 'a', 'c', 'a', 'd', 'a', 'b', 'r', 'a'] freq = {} for c in chars: if c in freq: freq[c] += 1 else: freq[c] = 1 freq {'r': 2, 'a': 5, 'b': 2, 'c': 1, 'd': 1} for (k, v) in freq.items(): print(k, v) for k in freq: print(k, freq[k]) also try 9/11/

48 Sorting a list with sorted() sorted(list) li = [2, 3, 1, 4] sorted(li) [1, 2, 3, 4] li [2, 3, 1, 4] ani = ['fox', 'owl', 'dog', 'cat'] sorted(ani) ['cat', 'dog', 'fox', 'owl'] ani ['fox', 'owl', 'dog', 'cat'] 9/11/

49 Sorting a list with sorted() sorted(list) li = [2, 3, 1, 4] sorted(li) [1, 2, 3, 4] li [2, 3, 1, 4] Creates and returns a new sorted list li is not changed 9/11/

50 Sorting a list with sorted() sorted(list) Creates and returns a new alphabetically sorted list ani = ['fox', 'owl', 'dog', 'cat'] sorted(ani) ['cat', 'dog', 'fox', 'owl'] ani ['fox', 'owl', 'dog', 'cat'] ani is unchanged 9/11/

51 Sorting anything with sorted() sorted() is a general function: it works on any sequence types (strings & tuples) and dictionaries. No matter the input type, it returns a list. seasons = ('spring', 'summer', 'fall', 'winter') sorted(seasons, reverse=true) ['winter', 'summer', 'spring', 'fall'] takes a tuple, returns a sorted list sorted('python') ['h', 'n', 'o', 'p', 't', 'y'] takes a string, returns a sorted list of characters sim = {'Homer':36, 'Marge':35, 'Bart':10, 'Lisa':8} sorted(sim) ['Bart', 'Homer', 'Lisa', 'Marge'] takes a dictionary, returns a sorted list of *keys* 9/11/

52 Teaching yourself new tricks Python built-in helper functions dir() help() Python IDLE tool tips Online references Python 3 Quick Reference: ython3-v1.0.5a-english.pdf 9/11/

53 dir() and help() dir(str) [' add ', ' class ', ' contains ', ' delattr ',... ' subclasshook ', '_formatter_field_name_split', 'capitalize', 'center', 'count', 'decode', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'index', 'isalnum', 'isalpha', 'isdigit', 'islower', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'partition', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill'] dir(obj) Returns a list of attributes ( xyz ) and methods that are available for the given object. 9/11/

54 dir() and help() dir(str) [' add ', ' class ', ' contains ', ' delattr ',... ' subclasshook ', '_formatter_field_name_split', 'capitalize', 'center', 'count', 'decode', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'index', 'isalnum', 'isalpha', 'isdigit', 'islower', 'isspace', 'istitle', help(str.find) 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'partition', Help method_descriptor: 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', find(...) 'strip', 'swapcase', 'title', 'translate', 'upper', S.find(sub 'zfill'] [,start [,end]]) -> int Return the lowest index in S where substring sub is found, such that sub is contained within S[start:end]. Optional arguments start and end are interpreted as in slice notation. Return -1 on failure. help(obj.method) prints out information on the object's method 9/11/

55 Wrap-up Next class: Language and Computers, Ch.2 Writer's aids: spell checkers Exercise 4 Due Thu, 4pm 9/11/

Lab 6: Data Types, Mutability, Sorting. Ling 1330/2330: Computational Linguistics Na-Rae Han

Lab 6: Data Types, Mutability, Sorting. Ling 1330/2330: Computational Linguistics Na-Rae Han Lab 6: Data Types, Mutability, Sorting Ling 1330/2330: Computational Linguistics Na-Rae Han Objectives Data types and conversion Tuple Mutability Sorting: additional parameters Text processing overview

More information

Lesson 4: Type Conversion, Mutability, Sequence Indexing. Fundamentals of Text Processing for Linguists Na-Rae Han

Lesson 4: Type Conversion, Mutability, Sequence Indexing. Fundamentals of Text Processing for Linguists Na-Rae Han Lesson 4: Type Conversion, Mutability, Sequence Indexing Fundamentals of Text Processing for Linguists Na-Rae Han Objectives Python data types Mutable vs. immutable object types How variable assignment

More information

Python Tutorial. Day 1

Python Tutorial. Day 1 Python Tutorial Day 1 1 Why Python high level language interpreted and interactive real data structures (structures, objects) object oriented all the way down rich library support 2 The First Program #!/usr/bin/env

More information

Introductory Linux Course. Python I. Martin Dahlö UPPMAX. Author: Nina Fischer. Dept. for Cell and Molecular Biology, Uppsala University

Introductory Linux Course. Python I. Martin Dahlö UPPMAX. Author: Nina Fischer. Dept. for Cell and Molecular Biology, Uppsala University Introductory Linux Course Martin Dahlö UPPMAX Author: Nina Fischer Dept. for Cell and Molecular Biology, Uppsala University August, 2018 Outline Python basics get started with Python Data types Control

More information

IPSL python tutorial: some exercises for beginners

IPSL python tutorial: some exercises for beginners 1 of 9 10/22/2013 03:55 PM IPSL python tutorial: some exercises for beginners WARNING! WARNING! This is the FULL version of the tutorial (including the solutions) WARNING! Jean-Yves Peterschmitt - LSCE

More information

Introductory Linux Course. Python I. Pavlin Mitev UPPMAX. Author: Nina Fischer Dept. for Cell and Molecular Biology, Uppsala University

Introductory Linux Course. Python I. Pavlin Mitev UPPMAX. Author: Nina Fischer Dept. for Cell and Molecular Biology, Uppsala University Introductory Linux Course Python I Pavlin Mitev UPPMAX Author: Nina Fischer Dept. for Cell and Molecular Biology, Uppsala University August, 2017 Outline Python introduction Python basics get started with

More information

Python - 2. Jim Eng

Python - 2. Jim Eng Python - 2 Jim Eng jimeng@umich.edu Lists Dictionaries Try... except Methods and Functions Classes and Objects Midterm Review Overview Patterns in programming - 1 Sequential steps Conditional steps Repeated

More information

Introduction to Python for Plone developers

Introduction to Python for Plone developers Plone Conference, October 15, 2003 Introduction to Python for Plone developers Jim Roepcke Tyrell Software Corporation What we will learn Python language basics Where you can use Python in Plone Examples

More information

Strings. Chapter 6. Python for Everybody

Strings. Chapter 6. Python for Everybody Strings Chapter 6 Python for Everybody www.py4e.com String Data Type A string is a sequence of characters A string literal uses quotes 'Hello' or "Hello" For strings, + means concatenate When a string

More information

Introductory Linux Course. Python I. Nina Fischer Dept. for Cell and Molecular Biology, Uppsala University

Introductory Linux Course. Python I. Nina Fischer Dept. for Cell and Molecular Biology, Uppsala University Introductory Linux Course Python I Nina Fischer Dept. for Cell and Molecular Biology, Uppsala University nina.fischer@icm.uu.se August 26, 2016 Outline q Python introducjon q Python basics get started

More information

Introductory Linux Course. Python I. Nina Fischer Dept. for Cell and Molecular Biology, Uppsala University

Introductory Linux Course. Python I. Nina Fischer Dept. for Cell and Molecular Biology, Uppsala University Introductory Linux Course Python I Nina Fischer Dept. for Cell and Molecular Biology, Uppsala University nina.fischer@icm.uu.se January 12, 2017 Outline q Python introducjon q Python basics get started

More information

SI Networked Computing: Storage, Communication, and Processing, Winter 2009

SI Networked Computing: Storage, Communication, and Processing, Winter 2009 University of Michigan Deep Blue deepblue.lib.umich.edu 2009-01 SI 502 - Networked Computing: Storage, Communication, and Processing, Winter 2009 Severance, Charles Severance, C. (2008, December 19). Networked

More information

Python Objects. Charles Severance. Python for Everybody

Python Objects. Charles Severance. Python for Everybody Python Objects Charles Severance Python for Everybody www.py4e.com Warning This lecture is very much about definitions and mechanics for objects This lecture is a lot more about how it works and less about

More information

Module 3: Strings and Input/Output

Module 3: Strings and Input/Output Module 3: Strings and Input/Output Topics: Strings and their methods Printing to standard output Reading from standard input Readings: ThinkP 8, 10 1 Strings in Python: combining strings in interesting

More information

Strings. Looping. dna = 'ATGTAGC' print(dna) In [1]: ATGTAGC. You can loop over the characters of a string using a for loop, as we saw on Tuesday:

Strings. Looping. dna = 'ATGTAGC' print(dna) In [1]: ATGTAGC. You can loop over the characters of a string using a for loop, as we saw on Tuesday: Strings A string is simply a sequence of characters. From a biological perspective, this is quite useful, as a DNA sequence is simply a string composed of only 4 letters, and thus easily manipulated in

More information

Duration: Six Weeks Faculty : Mr Sai Kumar, Having 10+ Yrs Experience in IT

Duration: Six Weeks Faculty : Mr Sai Kumar, Having 10+ Yrs Experience in IT Duration: Six Weeks Faculty : Mr Sai Kumar, Having 10+ Yrs Experience in IT Online Classes are also available Recorded class will be given if you miss any day interview tips and quiz at end of every module

More information

Lab 3: for and while Loops, Indexing. Ling 1330/2330: Computational Linguistics Na-Rae Han

Lab 3: for and while Loops, Indexing. Ling 1330/2330: Computational Linguistics Na-Rae Han Lab 3: for and while Loops, Indexing Ling 1330/2330: Computational Linguistics Na-Rae Han Objectives Split vs. join Loops for loop while loop Indexing List and string indexing & slicing Tips How to program

More information

(IUCAA, Pune) kaustubh[at]iucaa[dot]ernet[dot]in.

(IUCAA, Pune)   kaustubh[at]iucaa[dot]ernet[dot]in. Basics of Python by Kaustubh Vaghmare (IUCAA, Pune) E-mail: kaustubh[at]iucaa[dot]ernet[dot]in 1 of 29 Thursday 13 February 2014 11:59 AM Topics to be Covered (Not in any specific order.) Basic I/O in

More information

Chapter 8: More About Strings. COSC 1436, Summer 2018 Dr. Zhang 7/10/2018

Chapter 8: More About Strings. COSC 1436, Summer 2018 Dr. Zhang 7/10/2018 Chapter 8: More About Strings COSC 1436, Summer 2018 Dr. Zhang 7/10/2018 Creating Strings The str Class s1 = str() # Create an empty string s2 = str("welcome") # Create a string Welcome Python provides

More information

Strings. Upsorn Praphamontripong. Note: for reference when we practice loop. We ll discuss Strings in detail after Spring break

Strings. Upsorn Praphamontripong. Note: for reference when we practice loop. We ll discuss Strings in detail after Spring break Note: for reference when we practice loop. We ll discuss Strings in detail after Spring break Strings Upsorn Praphamontripong CS 1111 Introduction to Programming Spring 2018 Strings Sequence of characters

More information

Python I. Some material adapted from Upenn cmpe391 slides and other sources

Python I. Some material adapted from Upenn cmpe391 slides and other sources Python I Some material adapted from Upenn cmpe391 slides and other sources Overview Names & Assignment Data types Sequences types: Lists, Tuples, and Strings Mutability Understanding Reference Semantics

More information

COMP 364: Classes, Objects, and Names

COMP 364: Classes, Objects, and Names COMP 364: Classes, Objects, and Names Carlos G. Oliver, Christopher Cameron September 13, 2017 1/26 Outline 1. 202 vs 364 2. Development Environment Recap 3. Basic Data Types 4. Variables 2/26 Your Development

More information

Working with Sequences: Section 8.1 and 8.2. Bonita Sharif

Working with Sequences: Section 8.1 and 8.2. Bonita Sharif Chapter 8 Working with Sequences: Strings and Lists Section 8.1 and 8.2 Bonita Sharif 1 Sequences A sequence is an object that consists of multiple data items These items are stored consecutively Examples

More information

String Processing CS 1111 Introduction to Programming Fall 2018

String Processing CS 1111 Introduction to Programming Fall 2018 String Processing CS 1111 Introduction to Programming Fall 2018 [The Coder s Apprentice, 10] 1 Collections Ordered, Dup allow List Range String Tuple Unordered, No Dup Dict collection[index] Access an

More information

Programming environments. Introduction to Python. Adrian Copie, Ph.D.

Programming environments. Introduction to Python. Adrian Copie, Ph.D. Programming environments Introduction to Python Adrian Copie, Ph.D.! email: adrian.copie@info.uvt.ro, adrian.copie@e-uvt.ro UVT: room 050B 1 2 Bibliography 3 Mark Lutz - Learning Python (O Reilly) Leaning

More information

Strings are actually 'objects' Strings

Strings are actually 'objects' Strings Strings are actually 'objects' Strings What is an object?! An object is a concept that we can encapsulate data along with the functions that might need to access or manipulate that data. What is an object?!

More information

Introduction to String Manipulation

Introduction to String Manipulation Introduction to Computer Programming Introduction to String Manipulation CSCI-UA.0002 What is a String? A String is a data type in the Python programming language A String can be described as a "sequence

More information

(IUCAA, Pune) kaustubh[at]iucaa[dot]ernet[dot]in 1 of 29 Thursday 16 October :50 PM

(IUCAA, Pune)   kaustubh[at]iucaa[dot]ernet[dot]in 1 of 29 Thursday 16 October :50 PM Basics of Python by Kaustubh Vaghmare (IUCAA, Pune) E-mail: kaustubh[at]iucaa[dot]ernet[dot]in 1 of 29 Thursday 16 October 2014 03:50 PM Topics to be Covered (Not in any specific order.) Basic I/O in Python

More information

Python Programming. Lecture 1. January 25 th. University of Pennsylvania 2010, Adam Aviv CIS 192 Spring

Python Programming. Lecture 1. January 25 th. University of Pennsylvania 2010, Adam Aviv CIS 192 Spring Python Programming Lecture 1 January 25 th 2010, Adam Aviv CIS 192 Spring 2010 1 Welcome Where are you? Levine 100, Wu & Chen Auditorium 2/8 we will be in Heilmeir Hall (Towne 100) Who am I? Adam Aviv,

More information

Lab 1: Course Intro, Getting Started with Python IDLE. Ling 1330/2330 Computational Linguistics Na-Rae Han

Lab 1: Course Intro, Getting Started with Python IDLE. Ling 1330/2330 Computational Linguistics Na-Rae Han Lab 1: Course Intro, Getting Started with Python IDLE Ling 1330/2330 Computational Linguistics Na-Rae Han Objectives Course Introduction http://www.pitt.edu/~naraehan/ling1330/index.html Student survey

More information

Handling Strings and Bytes

Handling Strings and Bytes Chapter 9 Handling Strings and Bytes In this chapter, we present some of the most used methods in strings and bytes objects. Strings are extremely useful to manage most of the output generated from programs,

More information

Python for Informatics

Python for Informatics Python for Informatics Exploring Information Version 0.0.6 Charles Severance Chapter 6 Strings 6.1 A string is a sequence A string is a sequence of characters. You can access the characters one at a time

More information

Lab 8: File I/O, Mutability vs. Assignment. Ling 1330/2330: Intro to Computational Linguistics Na-Rae Han

Lab 8: File I/O, Mutability vs. Assignment. Ling 1330/2330: Intro to Computational Linguistics Na-Rae Han Lab 8: File I/O, Mutability vs. Assignment Ling 1330/2330: Intro to Computational Linguistics Na-Rae Han Objectives File I/O Writing to a file File I/O pitfalls File reference and absolute path Mutability

More information

Introduction to: Computers & Programming: Strings and Other Sequences

Introduction to: Computers & Programming: Strings and Other Sequences Introduction to: Computers & Programming: Strings and Other Sequences in Python Part I Adam Meyers New York University Outline What is a Data Structure? What is a Sequence? Sequences in Python All About

More information

Topic 7: Lists, Dictionaries and Strings

Topic 7: Lists, Dictionaries and Strings Topic 7: Lists, Dictionaries and Strings The human animal differs from the lesser primates in his passion for lists of Ten Best H. Allen Smith 1 Textbook Strongly Recommended Exercises The Python Workbook:

More information

Lab 2: input(), if else, String Operations, Variable Assignment. Ling 1330/2330: Computational Linguistics Na-Rae Han

Lab 2: input(), if else, String Operations, Variable Assignment. Ling 1330/2330: Computational Linguistics Na-Rae Han Lab 2: input(), if else, String Operations, Variable Assignment Ling 1330/2330: Computational Linguistics Na-Rae Han Objectives Learn Python basics Taking input from keyboard with input() Commenting Comparison

More information

Part IV. More on Python. Tobias Neckel: Scripting with Bash and Python Compact Max-Planck, February 16-26,

Part IV. More on Python. Tobias Neckel: Scripting with Bash and Python Compact Max-Planck, February 16-26, Part IV More on Python Compact Course @ Max-Planck, February 16-26, 2015 36 More on Strings Special string methods (excerpt) s = " Frodo and Sam and Bilbo " s. islower () s. isupper () s. startswith ("

More information

Student Number: Comments are not required except where indicated, although they may help us mark your answers.

Student Number: Comments are not required except where indicated, although they may help us mark your answers. CSC 108H5 F 2018 Midterm Test Duration 90 minutes Aids allowed: none Student Number: utorid: Last Name: First Name: Do not turn this page until you have received the signal to start. (Please fill out the

More information

Lists, loops and decisions

Lists, loops and decisions Caltech/LEAD Summer 2012 Computer Science Lecture 4: July 11, 2012 Lists, loops and decisions Lists Today Looping with the for statement Making decisions with the if statement Lists A list is a sequence

More information

COLLEGE OF ENGINEERING, NASHIK-4

COLLEGE OF ENGINEERING, NASHIK-4 Pune Vidyarthi Griha s COLLEGE OF ENGINEERING, NASHIK-4 DEPARTMENT OF COMPUTER ENGINEERING Important PYTHON Questions 1. What is Python? Python is a high-level, interpreted, interactive and object-oriented

More information

UNIT-III. All expressions involving relational and logical operators will evaluate to either true or false

UNIT-III. All expressions involving relational and logical operators will evaluate to either true or false UNIT-III BOOLEAN VALUES AND OPERATORS: A boolean expression is an expression that is either true or false. The following examples use the operator ==, which compares two operands and produces if they are

More information

Chapter 1 Summary. Chapter 2 Summary. end of a string, in which case the string can span multiple lines.

Chapter 1 Summary. Chapter 2 Summary. end of a string, in which case the string can span multiple lines. Chapter 1 Summary Comments are indicated by a hash sign # (also known as the pound or number sign). Text to the right of the hash sign is ignored. (But, hash loses its special meaning if it is part of

More information

Princeton University COS 333: Advanced Programming Techniques A Subset of Python 2.7

Princeton University COS 333: Advanced Programming Techniques A Subset of Python 2.7 Princeton University COS 333: Advanced Programming Techniques A Subset of Python 2.7 Program Structure # Print "hello world" to stdout. print 'hello, world' # Print "hello world" to stdout. def f(): print

More information

Advanced Python. Executive Summary, Session 1

Advanced Python. Executive Summary, Session 1 Advanced Python Executive Summary, Session 1 OBJECT: a unit of data of a particular type with characteristic functionality (i.e., methods and/or use with operators). Everything in Python is an object.

More information

18.1. CS 102 Unit 18. Python. Mark Redekopp

18.1. CS 102 Unit 18. Python. Mark Redekopp 18.1 CS 102 Unit 18 Python Mark Redekopp 18.2 Credits Many of the examples below are taken from the online Python tutorial at: http://docs.python.org/tutorial/introduction.html 18.3 Python in Context Two

More information

MUTABLE LISTS AND DICTIONARIES 4

MUTABLE LISTS AND DICTIONARIES 4 MUTABLE LISTS AND DICTIONARIES 4 COMPUTER SCIENCE 61A Sept. 24, 2012 1 Lists Lists are similar to tuples: the order of the data matters, their indices start at 0. The big difference is that lists are mutable

More information

UTORid: Lecture Section: (circle one): L0101 (MWF10) L0201 (MWF11) Instructor: Jacqueline Smith Jen Campbell

UTORid: Lecture Section: (circle one): L0101 (MWF10) L0201 (MWF11) Instructor: Jacqueline Smith Jen Campbell CSC 108H1 F 2017 Midterm Test Duration 50 minutes Aids allowed: none Last Name: UTORid: First Name: Lecture Section: (circle one): L0101 (MWF10) L0201 (MWF11) Instructor: Jacqueline Smith Jen Campbell

More information

Computer Sciences 368 Scripting for CHTC Day 3: Collections Suggested reading: Learning Python

Computer Sciences 368 Scripting for CHTC Day 3: Collections Suggested reading: Learning Python Day 3: Collections Suggested reading: Learning Python (3rd Ed.) Chapter 8: Lists and Dictionaries Chapter 9: Tuples, Files, and Everything Else Chapter 13: while and for Loops 1 Turn In Homework 2 Homework

More information

6. Data Types and Dynamic Typing (Cont.)

6. Data Types and Dynamic Typing (Cont.) 6. Data Types and Dynamic Typing (Cont.) 6.5 Strings Strings can be delimited by a pair of single quotes ('...'), double quotes ("..."), triple single quotes ('''...'''), or triple double quotes ("""...""").

More information

Types, lists & functions

Types, lists & functions Week 2 Types, lists & functions Data types If you want to write a program that allows the user to input something, you can use the command input: name = input (" What is your name? ") print (" Hello "+

More information

Data Structures. Lists, Tuples, Sets, Dictionaries

Data Structures. Lists, Tuples, Sets, Dictionaries Data Structures Lists, Tuples, Sets, Dictionaries Collections Programs work with simple values: integers, floats, booleans, strings Often, however, we need to work with collections of values (customers,

More information

Babu Madhav Institute of Information Technology, UTU 2015

Babu Madhav Institute of Information Technology, UTU 2015 Five years Integrated M.Sc.(IT)(Semester 5) Question Bank 060010502:Programming in Python Unit-1:Introduction To Python Q-1 Answer the following Questions in short. 1. Which operator is used for slicing?

More information

Part I. Wei Tianwen. A Brief Introduction to Python. Part I. Wei Tianwen. Basics. Object Oriented Programming

Part I. Wei Tianwen. A Brief Introduction to Python. Part I. Wei Tianwen. Basics. Object Oriented Programming 2017 Table of contents 1 2 Integers and floats Integer int and float float are elementary numeric types in. integer >>> a=1 >>> a 1 >>> type (a) Integers and floats Integer int and float

More information

Introduction to Text-Processing. Jim Notwell 23 January 2013

Introduction to Text-Processing. Jim Notwell 23 January 2013 Introduction to Text-Processing Jim Notwell 23 January 2013 1 Stanford UNIX Resources Host: cardinal.stanford.edu To connect from UNIX / Linux / Mac: ssh user@cardinal.stanford.edu To connect from Windows

More information

Collections. Lists, Tuples, Sets, Dictionaries

Collections. Lists, Tuples, Sets, Dictionaries Collections Lists, Tuples, Sets, Dictionaries Homework notes Homework 1 grades on canvas People mostly lost points for not reading the document carefully Didn t play again Didn t use Y/N for playing again

More information

Python Tutorial. CSE 3461: Computer Networking

Python Tutorial. CSE 3461: Computer Networking Python Tutorial CSE 3461: Computer Networking 1 Outline Introduction to Python CSE Environment Tips for Python Primitive Types Tips for Encoding/Decoding an IP Address 2 Intro to Python Dynamically typed,

More information

Lab 7: Reading Files, Importing, Bigram Function. Ling 1330/2330: Computational Linguistics Na-Rae Han

Lab 7: Reading Files, Importing, Bigram Function. Ling 1330/2330: Computational Linguistics Na-Rae Han Lab 7: Reading Files, Importing, Bigram Function Ling 1330/2330: Computational Linguistics Na-Rae Han Objectives Importing Reading text files range() Bigram function More sorting with sorted() sorted()

More information

Python allows variables to hold string values, just like any other type (Boolean, int, float). So, the following assignment statements are valid:

Python allows variables to hold string values, just like any other type (Boolean, int, float). So, the following assignment statements are valid: 1 STRINGS Objectives: How text data is internally represented as a string Accessing individual characters by a positive or negative index String slices Operations on strings: concatenation, comparison,

More information

Sequence types. str and bytes are sequence types Sequence types have several operations defined for them. Sequence Types. Python

Sequence types. str and bytes are sequence types Sequence types have several operations defined for them. Sequence Types. Python Python Sequence Types Sequence types str and bytes are sequence types Sequence types have several operations defined for them Indexing Python Sequence Types Each element in a sequence can be extracted

More information

Python. Executive Summary

Python. Executive Summary Python Executive Summary DEFINITIONS OBJECT: a unit of data of a particular type with characteristic functionality (i.e., methods and/or response to operators). Everything in Python is an object. "atomic"

More information

1 Four reasons for learning python 3. 2 Installing Python 4

1 Four reasons for learning python 3. 2 Installing Python 4 Contents 1 Four reasons for learning python 3 2 Installing Python 4 3 Language basics 7 3.1 Built-in types........................................ 7 3.2 Useful built-in functions..................................

More information

Some material adapted from Upenn cmpe391 slides and other sources

Some material adapted from Upenn cmpe391 slides and other sources Some material adapted from Upenn cmpe391 slides and other sources History Installing & Running Python Names & Assignment Sequences types: Lists, Tuples, and Strings Mutability Understanding Reference Semantics

More information

Midterm 1 Review. Important control structures. Important things to review. Functions Loops Conditionals

Midterm 1 Review. Important control structures. Important things to review. Functions Loops Conditionals Midterm 1 Review Important control structures Functions Loops Conditionals Important things to review Binary numbers Boolean operators (and, or, not) String operations: len, ord, +, *, slice, index List

More information

Table of Contents EVALUATION COPY

Table of Contents EVALUATION COPY Table of Contents Introduction... 1-2 A Brief History of Python... 1-3 Python Versions... 1-4 Installing Python... 1-5 Environment Variables... 1-6 Executing Python from the Command Line... 1-7 IDLE...

More information

Assignment 1: Getting Started with Python

Assignment 1: Getting Started with Python Assignment 1: Getting Started with Python This tutorial will cover the basics of working in the Unix environment for the USC aludra.usc.edu machines and a small Python tutorial. It assumes you already

More information

CSC148 Fall 2017 Ramp Up Session Reference

CSC148 Fall 2017 Ramp Up Session Reference Short Python function/method descriptions: builtins : input([prompt]) -> str Read a string from standard input. The trailing newline is stripped. The prompt string, if given, is printed without a trailing

More information

Python. Karin Lagesen.

Python. Karin Lagesen. Python Karin Lagesen karin.lagesen@bio.uio.no Plan for the day Basic data types data manipulation Flow control and file handling Functions Biopython package What is programming? Programming: ordered set

More information

DECODE SPECIAL OPERATOR, FORMAT OPERATOR CONTENTS TRIPLE QUOTES. IS a-to-z METHODS REPLACE L E N G T H E X P A N D T A B S ENC0D3

DECODE SPECIAL OPERATOR, FORMAT OPERATOR CONTENTS TRIPLE QUOTES. IS a-to-z METHODS REPLACE L E N G T H E X P A N D T A B S ENC0D3 The Game of Strings CONTENTS ACCESS, UPDATE, ESCAPE UNICODE STRINGS MAX MIN TRIPLE QUOTES E X P A N D T A B S ENC0D3 DECODE JUST LSTRIP METHODS IS a-to-z UNIC DE JOIN INDEX SPECIAL OPERATOR, FORMAT OPERATOR

More information

GIS 4653/5653: Spatial Programming and GIS. More Python: Statements, Types, Functions, Modules, Classes

GIS 4653/5653: Spatial Programming and GIS. More Python: Statements, Types, Functions, Modules, Classes GIS 4653/5653: Spatial Programming and GIS More Python: Statements, Types, Functions, Modules, Classes Statement Syntax The if-elif-else statement Indentation and and colons are important Parentheses and

More information

There are four numeric types: 1. Integers, represented as a 32 bit (or longer) quantity. Digits sequences (possibly) signed are integer literals:

There are four numeric types: 1. Integers, represented as a 32 bit (or longer) quantity. Digits sequences (possibly) signed are integer literals: Numeric Types There are four numeric types: 1. Integers, represented as a 32 bit (or longer) quantity. Digits sequences (possibly) signed are integer literals: 1-123 +456 2. Long integers, of unlimited

More information

University of Washington CSE 140 Introduction to Data Programming Winter Midterm exam. February 6, 2013

University of Washington CSE 140 Introduction to Data Programming Winter Midterm exam. February 6, 2013 University of Washington CSE 140 Introduction to Data Programming Winter 2013 Midterm exam February 6, 2013 Name: Solutions UW Net ID (username): This exam is closed book, closed notes. You have 50 minutes

More information

Python Intro GIS Week 1. Jake K. Carr

Python Intro GIS Week 1. Jake K. Carr GIS 5222 Week 1 Why Python It s simple and easy to learn It s free - open source! It s cross platform IT S expandable!! Why Python: Example Consider having to convert 1,000 shapefiles into feature classes

More information

Overview of List Syntax

Overview of List Syntax Lists and Sequences Overview of List Syntax x = [0, 0, 0, 0] Create list of length 4 with all zeroes x 4300112 x.append(2) 3 in x x[2] = 5 x[0] = 4 k = 3 Append 2 to end of list x (now length 5) Evaluates

More information

Question 1. Part (a) Part (b) December 2013 Final Examination Marking Scheme CSC 108 H1F. [13 marks] [4 marks] Consider this program:

Question 1. Part (a) Part (b) December 2013 Final Examination Marking Scheme CSC 108 H1F. [13 marks] [4 marks] Consider this program: Question 1. Part (a) [4 marks] Consider this program: [13 marks] def square(x): (number) -> number Write what this program prints, one line per box. There are more boxes than you need; leave unused ones

More information

Characters, c-strings, and the string Class. CS 1: Problem Solving & Program Design Using C++

Characters, c-strings, and the string Class. CS 1: Problem Solving & Program Design Using C++ Characters, c-strings, and the string Class CS 1: Problem Solving & Program Design Using C++ Objectives Perform character checks and conversions Knock down the C-string fundamentals Point at pointers and

More information

MULTIPLE CHOICE. Chapter Seven

MULTIPLE CHOICE. Chapter Seven Chapter Seven MULTIPLE CHOICE 1. Which of these is associated with a specific file and provides a way for the program to work with that file? a. Filename b. Extension c. File object d. File variable 2.

More information

Lists How lists are like strings

Lists How lists are like strings Lists How lists are like strings A Python list is a new type. Lists allow many of the same operations as strings. (See the table in Section 4.6 of the Python Standard Library Reference for operations supported

More information

Python and Bioinformatics. Pierre Parutto

Python and Bioinformatics. Pierre Parutto Python and Bioinformatics Pierre Parutto October 9, 2016 Contents 1 Common Data Structures 2 1.1 Sequences............................... 2 1.1.1 Manipulating Sequences................... 2 1.1.2 String.............................

More information

Introduction to Python

Introduction to Python Introduction to Python Reading assignment: Perkovic text, Ch. 1 and 2.1-2.5 Python Python is an interactive language. Java or C++: compile, run Also, a main function or method Python: type expressions

More information

Compound Data Types 1

Compound Data Types 1 Compound Data Types 1 Chapters 8, 10 Prof. Mauro Gaspari: mauro.gaspari@unibo.it Compound Data Types Strings are compound data types: they are sequences of characters. Int and float are scalar data types:

More information

Beyond Blocks: Python Session #1

Beyond Blocks: Python Session #1 Beyond Blocks: Session #1 CS10 Spring 2013 Thursday, April 30, 2013 Michael Ball Beyond Blocks : : Session #1 by Michael Ball adapted from Glenn Sugden is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike

More information

Functions that return lists

Functions that return lists 342 Chapter 23 Functions that return lists If you did exercises 22.5.15 or 22.5.16, you ve already written some functions that return lists, but only in a very simple way: adding one new element to the

More information

Comp Exam 1 Overview.

Comp Exam 1 Overview. Comp 170-400 Exam 1 Overview. Resources During the Exam The exam will be closed book, no calculators or computers, except as a word processor. In particular no Python interpreter running in a browser or

More information

CMSC 201 Fall 2016 Lab 09 Advanced Debugging

CMSC 201 Fall 2016 Lab 09 Advanced Debugging CMSC 201 Fall 2016 Lab 09 Advanced Debugging Assignment: Lab 09 Advanced Debugging Due Date: During discussion Value: 10 points Part 1: Introduction to Errors Throughout this semester, we have been working

More information

Interactive use. $ python. >>> print 'Hello, world!' Hello, world! >>> 3 $ Ctrl-D

Interactive use. $ python. >>> print 'Hello, world!' Hello, world! >>> 3 $ Ctrl-D 1/60 Interactive use $ python Python 2.7.5 (default, Mar 9 2014, 22:15:05) [GCC 4.2.1 Compatible Apple LLVM 5.0 (clang-500.0.68)] on darwin Type "help", "copyright", "credits" or "license" for more information.

More information

Analyzing Tweets: Introducing Text Analysis Entities, parsing, regular expressions, frequency analysis

Analyzing Tweets: Introducing Text Analysis Entities, parsing, regular expressions, frequency analysis Analyzing Tweets: Introducing Text Analysis Entities, parsing, regular expressions, frequency analysis Outline What are entities? Parsing text Simple parsing Regular expressions Frequency analysis Entities

More information

CS2304: Python for Java Programmers. CS2304: Sequences and Collections

CS2304: Python for Java Programmers. CS2304: Sequences and Collections CS2304: Sequences and Collections Sequences In Python A sequence type in python supports: The in membership operator. The len() function. Slicing like we saw with strings, s[1:3]. And is iterable (for

More information

DEBUGGING TIPS. 1 Introduction COMPUTER SCIENCE 61A

DEBUGGING TIPS. 1 Introduction COMPUTER SCIENCE 61A DEBUGGING TIPS COMPUTER SCIENCE 61A 1 Introduction Every time a function is called, Python creates what is called a stack frame for that specific function to hold local variables and other information.

More information

Essentials for Scientific Computing: Introduction to Python Day 11 & 12

Essentials for Scientific Computing: Introduction to Python Day 11 & 12 Essentials for Scientific Computing: Introduction to Python Day 11 & 12 Ershaad Ahamed TUE-CMS, JNCASR May 2012 1 Conditionals 1.1 if Construct In python blocks of code are created by indentation. That

More information

Python review. 1 Python basics. References. CS 234 Naomi Nishimura

Python review. 1 Python basics. References. CS 234 Naomi Nishimura Python review CS 234 Naomi Nishimura The sections below indicate Python material, the degree to which it will be used in the course, and various resources you can use to review the material. You are not

More information

Strings, Lists, and Sequences

Strings, Lists, and Sequences Strings, Lists, and Sequences It turns out that strings are really a special kind of sequence, so these operations also apply to sequences! >>> [1,2] + [3,4] [1, 2, 3, 4] >>> [1,2]*3 [1, 2, 1, 2, 1, 2]

More information

Programming to Python

Programming to Python Programming to Python Sept., 5 th Slides by M. Stepp, M. Goldstein, M. DiRamio, and S. Shah Compiling and interpreting Many languages require you to compile (translate) your program into a form that the

More information

CMSC 201 Fall 2015 Lab 12 Tuples and Dictionaries

CMSC 201 Fall 2015 Lab 12 Tuples and Dictionaries CMSC 201 Fall 2015 Lab 12 Tuples and Dictionaries Assignment: Lab 12 Tuples and Dictionaries Due Date: During discussion, November 30 th through December 3 rd Value: 1% of final grade Part 1: Data Types

More information

COMP1730/COMP6730 Programming for Scientists. Strings

COMP1730/COMP6730 Programming for Scientists. Strings COMP1730/COMP6730 Programming for Scientists Strings Lecture outline * Sequence Data Types * Character encoding & strings * Indexing & slicing * Iteration over sequences Sequences * A sequence contains

More information

Interactive use. $ python. >>> print 'Hello, world!' Hello, world! >>> 3 $ Ctrl-D

Interactive use. $ python. >>> print 'Hello, world!' Hello, world! >>> 3 $ Ctrl-D 1/58 Interactive use $ python Python 2.7.5 (default, Mar 9 2014, 22:15:05) [GCC 4.2.1 Compatible Apple LLVM 5.0 (clang-500.0.68)] on darwin Type "help", "copyright", "credits" or "license" for more information.

More information

Intro to Python. by Daniel Greenfeld

Intro to Python. by Daniel Greenfeld Intro to Python by Daniel Greenfeld Intro to Python a.k.a. 20 cool things you can do with Python Tons of content Please hold your questions until the end Latest slides will be made available Special thanks

More information

Outline. Simple types in Python Collections Processing collections Strings Tips. 1 On Python language. 2 How to use Python. 3 Syntax of Python

Outline. Simple types in Python Collections Processing collections Strings Tips. 1 On Python language. 2 How to use Python. 3 Syntax of Python Outline 1 On Python language 2 3 4 Marcin Młotkowski Object oriented programming 1 / 52 On Python language The beginnings of Pythons 90 CWI Amsterdam, Guido van Rossum Marcin Młotkowski Object oriented

More information

PLEASE HAND IN UNIVERSITY OF TORONTO Faculty of Arts and Science

PLEASE HAND IN UNIVERSITY OF TORONTO Faculty of Arts and Science PLEASE HAND IN UNIVERSITY OF TORONTO Faculty of Arts and Science DECEMBER 2013 EXAMINATIONS CSC 108 H1F Instructors: Craig and Gries Duration 3 hours PLEASE HAND IN Examination Aids: None Student Number:

More information

University of Washington CSE 140 Introduction to Data Programming Winter Midterm exam. February 6, 2013

University of Washington CSE 140 Introduction to Data Programming Winter Midterm exam. February 6, 2013 University of Washington CSE 140 Introduction to Data Programming Winter 2013 Midterm exam February 6, 2013 Name: UW Net ID (username): This exam is closed book, closed notes. You have 50 minutes to complete

More information

History Installing & Running Python Names & Assignment Sequences types: Lists, Tuples, and Strings Mutability

History Installing & Running Python Names & Assignment Sequences types: Lists, Tuples, and Strings Mutability History Installing & Running Python Names & Assignment Sequences types: Lists, Tuples, and Strings Mutability Some material adapted from Upenn cmpe391 slides and other sources Invented in the Netherlands,

More information