Introduction to Python! Lecture 2

Size: px
Start display at page:

Download "Introduction to Python! Lecture 2"

Transcription

1 .. Introduction to Python Lecture 2

2 Summary Summary: Lists Sets Tuples Variables while loop for loop Functions Names and values Passing parameters to functions

3 Lists Characteristics of the Python lists ordered collections of arbitrary objects accessible by offset variable-length, heterogenous and arbitrary nestable they represent mutable sequences Examples of lists L = [] #empty list L= [1,2,3,4] #list of numbers L = [1, [2,3], four ] #heterogenous list

4 Basic list operations List concatenation l1 = [1, 2, 3] l2 = [4, 5, 6] l3 = l1 + l2 print(id(l1)) print(id(l2)) print(id(l3)) print(l3) [1, 2, 3, 4, 5, 6] List multiplication l1 = ["Python"] l2 = 3 * l1 print(l2) ['Python', 'Python', 'Python'] List membership l = ["Monty", "Python", "and", "the", "Holy", "Grail"] m = "Python" in l print(m) True

5 Indexing and slicing lists Indexing lists l = ["Monty", "Python", "and", "the", "Holy", "Grail"] print(l[1]) print(l[-1]) Python Grail Slicing lists l = ["Monty", "Python", "and", "the", "Holy", "Grail"] print(l[1:]) ['Python', 'and', 'the', 'Holy', 'Grail'] l = ["Monty", "Python", "and", "the", "Holy", "Grail"] print(l[2:4]) ['and', 'the']

6 Operations with list elements Extending a list l = ["Monty", "Python"] q = ["and", "the", "Holy", "Grail"] print(l) l.extend(q) ['Monty', 'Python', 'and', 'the', 'Holy', 'Grail'] Reversing a list l = ["Monty", Python, "and", "the", "Holy", "Grail"] l.reverse() print(l) ['Grail', 'Holy', 'the', 'and', 'Python', 'Monty'] Deleting the last element in a list l = ["Monty", Python, "and", "the", "Holy", "Grail"] l.pop() print(l) ['Monty', 'Python', 'and', 'the', 'Holy']

7 Deleting elements in lists Deleting the i-th element in a list l = ["Monty", Python, "and", "the", "Holy", "Grail"] l.pop(2) print(l) ['Monty', 'Python', 'the', Holy, Grail ] Deleting an element of a list, by value l = ["Monty", Python, "and", "the", "Holy", "Grail"] l.remove( Python') print(l) ['Monty', 'and', 'the', 'Holy', 'Grail'] Deleting an element of a list using del statement l = ['Monty', 'Python', 'and', 'the', 'Holy', 'Grail'] del l[2] print(l) ['Monty', 'Python', 'the', 'Holy', 'Grail']

8 Matrix representation Matrixes representation (multidimensional lists) m = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] print(m[0][2]) print(m[1][1]) 3 5

9 Changing lists in place Changing by indexing l = ["Monty", "Python"] print(l) l[0] = "Snake" print(l) ['Monty', 'Python'] ['Snake', 'Python'] Changing by slicing l = ["Monty", "Python", "and", "the", "Holy", "Grail"] l[2:4] = ["has", "the"] print(l) ['Monty', 'Python', 'has', 'the', 'Holy', 'Grail'] Slicing is performed in two steps: deletion of range insertion in the place of deletion Be careful when lists are shared references

10 List appending and sorting Appending a list l = ["Monty", "Python"] l.append(["and", "the", "Holy", "Grail"]) print(l) Sorting a list ['Monty', 'Python', ['and', 'the', 'Holy', 'Grail']] l = ["Monty", "Python", "and", "the", "Holy", "Grail"] l.sort() print(l) ['Grail', 'Holy', 'Monty', 'Python', 'and', 'the'] sort() uses Python standard comparison tests. If other sorting order is needed, a new comparison function should be passed to sort() l = ["Monty", "Python", "and", "the", "Holy", "Grail"] l.sort(key=str.lower) print(l) ['and', 'Grail', 'Holy', 'Monty', 'Python', 'the']

11 Differences in changing lists Changing a list by appending l = ["Monty"] print(id(l)) l.append(["python"]) print(id(l)) Changing a list by concatenation q = ["Monty"] print(id(q)) q = q + ["Python"] print(id(q)) Important: when changing a list by appending (and generally speaking, by any method allowing in-place changing) the list remains the same. When changing using concatenation, a new list is built.

12 Sets Definition: A set is a well defined collection of objects. Sets manipulate unordered collections of unique elements Common use: membership testing removing duplicates from a sequence computing standard math operations on sets such as intersection, union, difference, and symmetric difference. Supported operations: membership testing determining the size of a set iterating through the set Being an unordered collection, set does not support indexing

13 Operations on sets Creating a set: s = set() print(type(s)) <class 'set'> Adding an element to a set: s = set() s.add("python") print(s) {'Python'} Updating a set: s = set() s.add("python") print(s) new_element = [ Monty ] s.update(new_element) print(s) {'Python'} {'Monty', 'Python'} Update takes an iterable collection as argument, here a list

14 Updating a set s1 = set(['monty', 'Python']) print(s1) s2 = set(['monty', 'Holy', 'Grail']) print(s2) s1.update(s2) print(s1) {'Monty', 'Python'} {'Monty', 'Grail', 'Holy'} {'Monty', 'Grail', 'Python', 'Holy'} Update a set with another set It works like an union operation. Keep in mind that sets do not support duplicates. One can see that the Monty string occurs only once in the final set

15 Updating a set (2) Updating a set: s = set() s.add("python") print(s) new_element = Monttty s.update(new_element) print(s) adding an element when the element we update with is not a set, but a string, for example, Python will treat it like a set EQUIVALENT {'Python'} {'y', 'n', 'M', 'Python', 't', 'o'} s = set() s.add("python") print(s) new_element = [ M,'o','n','t', t,'t','y'] s.update(new_element) print(s) One can see that a single t letter was allowed

16 Other set functons Cardinality of a set (number of elements): s = set([1, 2, 3, 9, 10]) l = len(s) print(l) 5 Checking for membership in a set: s = set([1, 2, 3, 9]) m = 1 in s print(m) True Iterating in a set: s = set([1, 2, 3, 9]) for x in s: print(x)

17 Tuples What is a tuple? A tuple is a sequence of immutable objects. They are somehow similar with lists, but tuples cannot be changed. As notation, they use parentheses () whereas the lists use square brackets []. Creating a tuple t = 1, 2, 3 print(type(t)) print(t) u = (1, 2, 3) print(type(u)) print(u) <class 'tuple'> (1, 2, 3) <class 'tuple'> (1, 2, 3) Tuples are immutable. t = 1, 2, 3 t[0] = 9 print(t) Traceback (most recent call last): File "caller-pkg.py", line 404, in <module> t[0] = 9 TypeError: 'tuple' object does not support item assignment

18 Tuples Tuples can be nested t = (1, 2, 3, (4, (5, 6, 7), 8), 9) print(t) (1, 2, 3, (4, (5, 6, 7), 8), 9) 1 2 Determine the size of a tuple t = (1, 2, 3, (4, (5, 6, 7), 8), 9) print(t) print(len(t)) (1, 2, 3, (4, (5, 6, 7), 8), 9) 5 3 Concatenation of tuples t = (1, 2, 3, (4, (5, 6, 7), 8), 9) print(t) print(len(t)) (1, 2, 3, (4, (5, 6, 7), 8), 9, 10, 11, 12)

19 Operations on tuples Determine the number of items in a tuple t = (1, 2, 3, (4, (5, 6, 7), 8), 9) print(t) print(len(t)) (1, 2, 3, (4, (5, 6, 7), 8), 9) 5 Search for an item of a tuple t = (1, 2, 3, (4, (5, 6, 7), 8), 9) i = t.index(3) print(i) 2 But how do we search for a nested item of a tuple? t = (1, 2, 3, (4, (5, 6, 7), 8), 9) i = t[3][1].index(6) print(i) 1 Count the occurrence of an item of a tuple t = (1, 2, 11, 111, 22, 3, 1, 3, 4, 5, 5) c = t.count(1) print(c) 2

20 print function redirect printing to a file print(value,..., sep=' ', end='\n', file=sys.stdout, flush=false) Method 1 (temporary redirection) print("hello world", file=open("/tmp/log.txt", "a")) Method 2 (globally redirection) import sys tmp = sys.stdout sys.stdout = open( /tmp/log.txt", "a") print("hello world") sys.stdout = tmp # restored print("hello world ) # console again

21 Variables Naming variables: (underscore or letter) + (any number of letters, digits or underscores) ex: _counter, counter, counter_21_ Variables are case sensitive: _counter is different from _Counter Do not use reserved words as variable names (Python 3 reserved words) False class finally is return None continue for lambda try True def from nonlocal while and del global not with as elif if or yield assert else import pass break except in raise

22 Variable names conventions Naming conventions: Avoid patterns like name Names beginning with a single underscore _X are not imported by a from module import * Names having two leading and trailing underscores X are system defined, having special meaning to the interpreter Names having only two leading underscores X are mangled to enclosing classes (e.g. a variable called X inside a Spam class will be expanded to _Spam X) Python does not have access modifiers (private, protected, public) By convention, a variable name starting with one underscore _X is considered private in the module scope and starting with two underscores X in the class scope.

23 Variables Variable creation A variable (and by variable we understand name) is created at the moment in which it is assigned with a value. Future assignments only change the value of an already created name. Variable types A variable does not have ANY information about its type associated with it. The type lives with the OBJECT not with name. Variable use When a variable appears in an expression, it is immediately replaced with the object that is currently refers to. All variables must be explicitly assigned before they can be used. Trying to use an unassigned variable leads to errors.

24 scope of the variables Functions define a local scope while modules define a global scope module -> file The global scope spans a single file only. There is no notion about global allencompassing file-based scope in Python LEGB scope rule

25 example of variables scope x = 69 def func(y): z = x + y return z print(func(1)) x has a global scope. It is assigned at the top of the level of the module y and z have local scope. They are both assigned values in the function definition 70 x = 69 def func(y): x = 99 z = x + y return z print(func(1)) print(x) We have two variables named x, one defined at the top level, the other one is defined inside the function

26 global statement Is it possible to change the scope of a variable in Python? x = 99 def func(): global x x = 100 func() print(x) changes the scope of a variable, making it to be module-scope One can notice here that after exiting the body of the function, the value of x remains changed, is not 99 anymore 100 Don t use it unless is absolutely necessary

27 while loop while loop repeatedly executes a block of statements as long as the test in the top is evaluated as True while <test>: <statements1> else: <statements2> example i = 2 while 0 < i < 3: print(i) i -= 1 else: print("while false condition") 2 1 while false condition

28 break statement break jumps out of the closest enclosing loop s = 'python' found = False i = 0 while not found: if s[i] == 'y': found = True print( we've found it") break else: i += 1

29 continue statement continue jumps to the top of the closest enclosing loop s = 'python' found = False i = 0 while not found: if s[i] = 'y': i += 1 continue else: print( we've found it ") found = True

30 pass statement pass does nothing at all, it is an empty statement placeholder Sometime the syntax requires a statement but there isn t anything useful to say s = 'python' i = 0 while i <len(s): if s[i] == 'h': pass else: print(s[i]) i += 1 p y t o n

31 for loop (I) for loop is a generic sequence iterator in Python, it steps through the items of any ordered sequence object. for <target> in <object>: <statements> else: <statements> example (iteration over a list) for i in ['python', 'is', 'the', 'best']: print(i) python is the best

32 for loop (II) example (iteration over a tuple) for i in ('python', 'is', 'the', 'best'): print(i) nested for loops l1 = ["Python", "is", "a", "snake"] l2 = ["Monty", "Python", "and", "the", "Holy", "Grail"] for i in l1: for j in l2: if i == j: print("we have found a duplicate " + j); we have found a duplicate Python

33 loop coding techniques for loop is usually simpler to code and faster to run than the while loop What if we need to iterate every second item in a list? range() method returns a list of successively higher integers which could be used as indexes in a for loop range(5) -> [0,1,2,3,4] range(2,5) -> [2,3,4] range(0,10,2) -> [0,2,4,6,8] example for i in range(0,10,2): print(i)

34 Functions FUNCTIONS Why use functions? Maximising code reuse Minimising redundancy Procedural decomposition Improving code clarity Information hiding

35 def statements def statements def <name>(arg1, arg2,, argn): <statements> def <name>(arg1, arg2,, argn): <statements> return <value> def is executable code def creates an object and assigns it to a name return sends a result object to the caller arguments are passed by assignment (object reference) (we ll see later how)

36 Where to define functions? One can declare a function: inside a module inside a class inside another function Functions defined inside a class are called methods

37 examples of function definition Many ways to define a function in Python module level function level class level def module_func(): print("i am a module level function") module_func() def outer_func(): def inner_func(): print("i am in the inner_func") inner_func() out = outer_func() class Debug(object): def init (self, dbg): self.dbg = dbg def debug(self, message): if self.dbg: print(message) dbg = Debug(True); dbg.debug("hello world")

38 Functions are objects Functions in Python are objects so they can be manipulated like any other objects. They are called first-class citizens. def func(): """Example of python function""" print("hello from func") print(isinstance(func, object)) print(id(func)) print(func. doc ) print(func. name ) OUTPUT: True Example of python function func

39 names and values x = 69 x 69 Python assignment statement associates a symbolic name on the left-hand side with a value, on the right-hand side. We say that names refer to values, or a name is a reference to a value x y x = 69 y = x 69 Many names can refer to the same value. Neither x or y is the real name. They refer to the value equally, exactly in the same way. x = 96 x 96 Assigning a new value to x will create another reference. y 69

40 assignment never copies data Assigning does not copy data. Ever. x y x = 69 y = x 69 We have only one value and two names.

41 modifying an immutable type What happens if we modify a value? x = 69 y = x x = x + 1 After the first assignment, x is an integer variable. But integers are immutable. So they cannot be modified. This means a new value is created. x y 69 x y x = 1 y = x print("x = " + str(x)) print("y = " + str(y)) print("x address : " + hex(id(x))) print("y address : " + hex(id(y))) x = x + 1 print("x = " + str(x)) print("y = " + str(y)) print("x address after assignment : " + hex(id(x))) print("y address after assignment : " + hex(id(y))) x = 1 y = 1 x address : 0x10b9e09e0 y address : 0x10b9e09e0 x = 2 y = 1 x address after assignment : 0x10b9e0a00 y address after assignment : 0x10b9e09e0

42 assigning for complex python types What happens with the more complex types? loto = [1, 6, 9, 12, 43, 47] loto prono = loto loto prono

43 Mutable types What happens if we modify a mutable type? loto.append(49) loto prono loto = [1, 6, 9, 12, 43, 47] prono = loto print(loto) print(prono) print(hex(id(loto))) print(hex(id(prono))) loto.append(49) print(loto) print(prono) print(hex(id(loto))) print(hex(id(prono))) [1, 6, 9, 12, 43, 47] [1, 6, 9, 12, 43, 47] 0x10cd32f48 0x10cd32f48 [1, 6, 9, 12, 43, 47, 49] [1, 6, 9, 12, 43, 47, 49] 0x10cd32f48 0x10cd32f48

44 garbage collection Values live until nothing references them. There is a mechanism called garbage collection which takes care of cleaning all the values which are no more referenced. One of the garbage collection components is reference counting. x = 69 y = 96 x = y x 69 y 96 x 69 y 96

45 passing parameters to functions When passed to a function, x and y arguments are assigned to a value as like any other name to value assignment def addition(x, y): return (x + y) print(addition(33, 66)) The names x and y are local to the addition function, so when the function ends, the names go away.

46 passing arguments to a function What if the parameter passed to a function has its value referenced by another name? def change_list(l, val): l.append(val) my_list = [2, 4, 6] change_list(my_list, 8) print(my_list)

47 def change_list(l, val): l = l + [val] my_list = [2, 4, 6] change_list(my_list, 8) print(my_list) passing arguments to a function

48 Default parameters for functions Python has the ability to handle default parameters for functions. For the languages that do not support default parameters, the trick is to create multiple functions with multiple parameters and call them appropriately. Example 1 def log(message=""): if message: print(message) log() log("hello World") Hello World Notice that for the call with empty params, nothing was displayed

49 Default parameters for functions Example 2 def bad_default(val, l=[]): l.append(val) return l print(bad_default(3)) print(bad_default(4)) Expected [3] [4] Real [3] [3, 4] Why? A new list is created ONCE when the function is defined, then the same list is used in each call. Python s default arguments are evaluated only ONCE, when the function is defined and not each time the function is called. So, if a mutable default argument is used and change it, it will be used for all the future calls of that function.

50 Default parameters for functions Solution def good_default(val, l=none): if l is None: l = [] l.append(val) return l print(good_default(3)) print(good_default(4)) Expected [3] [4] Real [3] [4] Instead of using a mutable argument for the placeholder, use the special type None. This will signal Python that no argument was provided and create a new object every time the function is called.

51 Conclusions Conclusions Lists are a very important type in Python Variables have a name convention and they belong to different scopes Looping is assured by while and for statements Functions are building blocks of a Python program Names and values are strongly tided in Python Passing arguments to functions is made by-assignment Python supports default parameters for functions

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

Python: Short Overview and Recap

Python: Short Overview and Recap Python: Short Overview and Recap Benjamin Roth CIS LMU Benjamin Roth (CIS LMU) Python: Short Overview and Recap 1 / 39 Data Types Object type Example creation Numbers (int, float) 123, 3.14 Strings this

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

\n is used in a string to indicate the newline character. An expression produces data. The simplest expression

\n is used in a string to indicate the newline character. An expression produces data. The simplest expression 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

ENGR 101 Engineering Design Workshop

ENGR 101 Engineering Design Workshop ENGR 101 Engineering Design Workshop Lecture 2: Variables, Statements/Expressions, if-else Edgardo Molina City College of New York Literals, Variables, Data Types, Statements and Expressions Python as

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

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

Sequences and iteration in Python

Sequences and iteration in Python GC3: Grid Computing Competence Center Sequences and iteration in Python GC3: Grid Computing Competence Center, University of Zurich Sep. 11 12, 2013 Sequences Python provides a few built-in sequence classes:

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

Here n is a variable name. The value of that variable is 176.

Here n is a variable name. The value of that variable is 176. UNIT II DATA, EXPRESSIONS, STATEMENTS 9 Python interpreter and interactive mode; values and types: int, float, boolean, string, and list; variables, expressions, statements, tuple assignment, precedence

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

Basic Syntax - First Program 1

Basic Syntax - First Program 1 Python Basic Syntax Basic Syntax - First Program 1 All python files will have extension.py put the following source code in a test.py file. print "Hello, Python!";#hello world program run this program

More information

Lecture 27. Lecture 27: Regular Expressions and Python Identifiers

Lecture 27. Lecture 27: Regular Expressions and Python Identifiers Lecture 27 Lecture 27: Regular Expressions and Python Identifiers Python Syntax Python syntax makes very few restrictions on the ways that we can name our variables, functions, and classes. Variables names

More information

The Dynamic Typing Interlude

The Dynamic Typing Interlude CHAPTER 6 The Dynamic Typing Interlude In the prior chapter, we began exploring Python s core object types in depth with a look at Python numbers. We ll resume our object type tour in the next chapter,

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

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

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

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

Programming in Python

Programming in Python 3. Sequences: Strings, Tuples, Lists 15.10.2009 Comments and hello.py hello.py # Our code examples are starting to get larger. # I will display "real" programs like this, not as a # dialog with the Python

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

Try and Error. Python debugging and beautification

Try and Error. Python debugging and beautification Try and Error Python debugging and beautification What happens when something goes wrong Catching exceptions In order to handle errors, you can set up exception handling blocks in your code. The keywords

More information

Introduction to programming using Python

Introduction to programming using Python Introduction to programming using Python Matthieu Choplin matthieu.choplin@city.ac.uk http://moodle.city.ac.uk/ Session 4 1 Objectives To come back on the notion of object and type. To introduce to the

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

Lecture 7: Python s Built-in. in Types and Basic Statements

Lecture 7: Python s Built-in. in Types and Basic Statements The University of North Carolina at Chapel Hill Spring 2002 Lecture 7: Python s Built-in in Types and Basic Statements Jan 25 1 Built-in in Data Structures: Lists A list is an ordered collection of objects

More information

Python Evaluation Rules

Python Evaluation Rules Python Evaluation Rules UW CSE 160 https://courses.cs.washington.edu/courses/cse160/15sp/ Michael Ernst and Isaac Reynolds mernst@cs.washington.edu April 1, 2015 Contents 1 Introduction 2 1.1 The Structure

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 debugging and beautification

Python debugging and beautification Python debugging and beautification #!/usr/bin/env python # # # THIS CODE DOES NOT WORK import sys def read(a): myfile = open(a,'r'): for i in myfile: yield i myfile.close() def count_chars(a): sum = 0

More information

Python in 10 (50) minutes

Python in 10 (50) minutes Python in 10 (50) minutes https://www.stavros.io/tutorials/python/ Python for Microcontrollers Getting started with MicroPython Donald Norris, McGrawHill (2017) Python is strongly typed (i.e. types are

More information

Loops and Conditionals. HORT Lecture 11 Instructor: Kranthi Varala

Loops and Conditionals. HORT Lecture 11 Instructor: Kranthi Varala Loops and Conditionals HORT 59000 Lecture 11 Instructor: Kranthi Varala Relational Operators These operators compare the value of two expressions and returns a Boolean value. Beware of comparing across

More information

CSc 110, Spring Lecture 24: print revisited, tuples cont.

CSc 110, Spring Lecture 24: print revisited, tuples cont. CSc 110, Spring 2017 Lecture 24: print revisited, tuples cont. 1 print 2 print revisited We often convert to strings when printing variables: print("the sum is " + str(sum)) This is not always necessary.

More information

Play with Python: An intro to Data Science

Play with Python: An intro to Data Science Play with Python: An intro to Data Science Ignacio Larrú Instituto de Empresa Who am I? Passionate about Technology From Iphone apps to algorithmic programming I love innovative technology Former Entrepreneur:

More information

Unit 2. Srinidhi H Asst Professor

Unit 2. Srinidhi H Asst Professor Unit 2 Srinidhi H Asst Professor 1 Iterations 2 Python for Loop Statements for iterating_var in sequence: statements(s) 3 Python for While Statements while «expression»: «block» 4 The Collatz 3n + 1 sequence

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

MEIN 50010: Python Data Structures

MEIN 50010: Python Data Structures : Python Data Structures Fabian Sievers Higgins Lab, Conway Institute University College Dublin Wednesday, 2017-10-18 Data Structures Stacks, Queues & Deques Structures Data structures are a way of storing

More information

Data type built into Python. Dictionaries are sometimes found in other languages as associative memories or associative arrays.

Data type built into Python. Dictionaries are sometimes found in other languages as associative memories or associative arrays. NETB 329 Lecture 4 Data Structures in Python Dictionaries Data type built into Python. Dictionaries are sometimes found in other languages as associative memories or associative arrays. 1 of 70 Unlike

More information

python 01 September 16, 2016

python 01 September 16, 2016 python 01 September 16, 2016 1 Introduction to Python adapted from Steve Phelps lectures - (http://sphelps.net) 2 Python is interpreted Python is an interpreted language (Java and C are not). In [1]: 7

More information

COMP519 Web Programming Lecture 20: Python (Part 4) Handouts

COMP519 Web Programming Lecture 20: Python (Part 4) Handouts COMP519 Web Programming Lecture 20: Python (Part 4) Handouts Ullrich Hustadt Department of Computer Science School of Electrical Engineering, Electronics, and Computer Science University of Liverpool Contents

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

CIS192: Python Programming Data Types & Comprehensions Harry Smith University of Pennsylvania September 6, 2017 Harry Smith (University of Pennsylvani

CIS192: Python Programming Data Types & Comprehensions Harry Smith University of Pennsylvania September 6, 2017 Harry Smith (University of Pennsylvani CIS192: Python Programming Data Types & Comprehensions Harry Smith University of Pennsylvania September 6, 2017 Harry Smith (University of Pennsylvania) CIS 192 Fall Lecture 2 September 6, 2017 1 / 34

More information

STEAM Clown & Productions Copyright 2017 STEAM Clown. Page 1

STEAM Clown & Productions Copyright 2017 STEAM Clown. Page 1 What to add next time you are updating these slides Update slides to have more animation in the bullet lists Verify that each slide has stand alone speaker notes Page 1 Python 3 Running The Python Interpreter

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

CHAPTER 2: Introduction to Python COMPUTER PROGRAMMING SKILLS

CHAPTER 2: Introduction to Python COMPUTER PROGRAMMING SKILLS CHAPTER 2: Introduction to Python COMPUTER PROGRAMMING SKILLS 1439-1440 1 Outline 1. Introduction 2. Why Python? 3. Compiler and Interpreter 4. The first program 5. Comments and Docstrings 6. Python Indentations

More information

Review Sheet for Midterm #1 COMPSCI 119 Professor William T. Verts

Review Sheet for Midterm #1 COMPSCI 119 Professor William T. Verts Review Sheet for Midterm #1 COMPSCI 119 Professor William T. Verts Simple Data Types There are a number of data types that are considered primitive in that they contain only a single value. These data

More information

Script language: Python Data structures

Script language: Python Data structures Script language: Python Data structures Cédric Saule Technische Fakultät Universität Bielefeld 3. Februar 2015 Immutable vs. Mutable Previously known types: int and string. Both are Immutable but what

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

Module 04: Lists. Topics: Lists and their methods Mutating lists Abstract list functions Readings: ThinkP 8, 10. CS116 Fall : Lists

Module 04: Lists. Topics: Lists and their methods Mutating lists Abstract list functions Readings: ThinkP 8, 10. CS116 Fall : Lists Module 04: Lists Topics: Lists and their methods Mutating lists Abstract list functions Readings: ThinkP 8, 10 1 Consider the string method split >>> name = "Harry James Potter" >>> name.split() ['Harry',

More information

Basic Concepts. Computer Science. Programming history Algorithms Pseudo code. Computer - Science Andrew Case 2

Basic Concepts. Computer Science. Programming history Algorithms Pseudo code. Computer - Science Andrew Case 2 Basic Concepts Computer Science Computer - Science - Programming history Algorithms Pseudo code 2013 Andrew Case 2 Basic Concepts Computer Science Computer a machine for performing calculations Science

More information

John Perry. Fall 2009

John Perry. Fall 2009 Lecture 5: Sage University of Southern Mississippi Fall 2009 Outline 1 2 3 4 You should be in worksheet mode to repeat the examples. Collections? Collection: group of objects identified as single object

More information

CMSC 201 Computer Science I for Majors

CMSC 201 Computer Science I for Majors CMSC 201 Computer Science I for Majors Lecture 02 Intro to Python Syllabus Last Class We Covered Grading scheme Academic Integrity Policy (Collaboration Policy) Getting Help Office hours Programming Mindset

More information

CS S-02 Python 1. Most python references use examples involving spam, parrots (deceased), silly walks, and the like

CS S-02 Python 1. Most python references use examples involving spam, parrots (deceased), silly walks, and the like CS662-2013S-02 Python 1 02-0: Python Name python comes from Monte Python s Flying Circus Most python references use examples involving spam, parrots (deceased), silly walks, and the like Interpreted language

More information

STATS 507 Data Analysis in Python. Lecture 2: Functions, Conditionals, Recursion and Iteration

STATS 507 Data Analysis in Python. Lecture 2: Functions, Conditionals, Recursion and Iteration STATS 507 Data Analysis in Python Lecture 2: Functions, Conditionals, Recursion and Iteration Functions in Python We ve already seen examples of functions: e.g., type()and print() Function calls take the

More information

MITOCW watch?v=rvrkt-jxvko

MITOCW watch?v=rvrkt-jxvko MITOCW watch?v=rvrkt-jxvko The following content is provided under a Creative Commons license. Your support will help MIT OpenCourseWare continue to offer high quality educational resources for free. To

More information

Worksheet 6: Basic Methods Methods The Format Method Formatting Floats Formatting Different Types Formatting Keywords

Worksheet 6: Basic Methods Methods The Format Method Formatting Floats Formatting Different Types Formatting Keywords Worksheet 1: Introductory Exercises Turtle Programming Calculations The Print Function Comments Syntax Semantics Strings Concatenation Quotation Marks Types Variables Restrictions on Variable Names Long

More information

Chapter 2 Writing Simple Programs

Chapter 2 Writing Simple Programs Chapter 2 Writing Simple Programs Charles Severance Textbook: Python Programming: An Introduction to Computer Science, John Zelle (www.si182.com) Software Development Process Figure out the problem - for

More information

Assignment 7: functions and closure conversion (part 1)

Assignment 7: functions and closure conversion (part 1) Assignment 7: functions and closure conversion (part 1) ECEN 4553 & 5013, CSCI 4555 & 5525 Prof. Jeremy G. Siek November 12, 2008 The main ideas for this week are: first-class functions lexical scoping

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

Execution order. main()

Execution order. main() Functions Execution order When you load and run a Python module (file), the statements and definitions in the file are executed in the order in which they occur Executing a def defines a function, it doesn

More information

egrapher Language Reference Manual

egrapher Language Reference Manual egrapher Language Reference Manual Long Long: ll3078@columbia.edu Xinli Jia: xj2191@columbia.edu Jiefu Ying: jy2799@columbia.edu Linnan Wang: lw2645@columbia.edu Darren Chen: dsc2155@columbia.edu 1. Introduction

More information

Dictionaries. Looking up English words in the dictionary. Python sequences and collections. Properties of sequences and collections

Dictionaries. Looking up English words in the dictionary. Python sequences and collections. Properties of sequences and collections Looking up English words in the dictionary Comparing sequences to collections. Sequence : a group of things that come one after the other Collection : a group of (interesting) things brought together for

More information

LECTURE 4 Python Basics Part 3

LECTURE 4 Python Basics Part 3 LECTURE 4 Python Basics Part 3 INPUT We ve already seen two useful functions for grabbing input from a user: raw_input() Asks the user for a string of input, and returns the string. If you provide an argument,

More information

XQ: An XML Query Language Language Reference Manual

XQ: An XML Query Language Language Reference Manual XQ: An XML Query Language Language Reference Manual Kin Ng kn2006@columbia.edu 1. Introduction XQ is a query language for XML documents. This language enables programmers to express queries in a few simple

More information

Compound Data Types 2

Compound Data Types 2 Compound Data Types 2 Chapters 10, 11, 12 Prof. Mauro Gaspari: gaspari@cs.unibo.it Objects and Values We know that a and b both refer to a string, but we don t know whether they refer to the same string.

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

Python Tutorial. Day 2

Python Tutorial. Day 2 Python Tutorial Day 2 1 Control: Whitespace in perl and C, blocking is controlled by curly-braces in shell, by matching block delimiters, if...then...fi in Python, blocking is controlled by indentation

More information

FILE HANDLING AND EXCEPTIONS

FILE HANDLING AND EXCEPTIONS FILE HANDLING AND EXCEPTIONS INPUT We ve already seen how to use the input function for grabbing input from a user: input() >>> print(input('what is your name? ')) What is your name? Spongebob Spongebob

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

COMP519 Web Programming Lecture 21: Python (Part 5) Handouts

COMP519 Web Programming Lecture 21: Python (Part 5) Handouts COMP519 Web Programming Lecture 21: Python (Part 5) Handouts Ullrich Hustadt Department of Computer Science School of Electrical Engineering, Electronics, and Computer Science University of Liverpool Functions

More information

Jarek Szlichta

Jarek Szlichta Jarek Szlichta http://data.science.uoit.ca/ Python is a straightforward language very simple syntax It encourages programmers to program without boilerplate (prepared) code 2 Python is completely object

More information

Statements 2. a operator= b a = a operator b

Statements 2. a operator= b a = a operator b Statements 2 Outline Note: i=i+1 is a valid statement. Don t confuse it with an equation i==i+1 which is always false for normal numbers. The statement i=i+1 is a very common idiom: it just increments

More information

Algorithms and Programming

Algorithms and Programming Algorithms and Programming Lecture 2 Procedural Programming Camelia Chira Last time Programming process What is programming? Basic elements of Python Python programs Data types: string, number Variables

More information

S206E Lecture 19, 5/24/2016, Python an overview

S206E Lecture 19, 5/24/2016, Python an overview S206E057 Spring 2016 Copyright 2016, Chiu-Shui Chan. All Rights Reserved. Global and local variables: differences between the two Global variable is usually declared at the start of the program, their

More information

LISTS WITH PYTHON. José M. Garrido Department of Computer Science. May College of Computing and Software Engineering Kennesaw State University

LISTS WITH PYTHON. José M. Garrido Department of Computer Science. May College of Computing and Software Engineering Kennesaw State University LISTS WITH PYTHON José M. Garrido Department of Computer Science May 2015 College of Computing and Software Engineering Kennesaw State University c 2015, J. M. Garrido Lists with Python 2 Lists with Python

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

COMP 204: Sets, Commenting & Exceptions

COMP 204: Sets, Commenting & Exceptions COMP 204: Sets, Commenting & Exceptions Yue Li based on material from Mathieu Blanchette, Carlos Oliver Gonzalez and Christopher Cameron 1/29 Outline Quiz 14 review Set Commenting code Bugs 2/29 Quiz 15

More information

Assignment 7: functions and closure conversion

Assignment 7: functions and closure conversion Assignment 7: functions and closure conversion ECEN 4553 & 5013, CSCI 4555 & 5525 Prof. Jeremy G. Siek October 20, 2007 The main ideas for this week are: first-class functions lexical scoping of variables

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

COMP 204: Sets, Commenting & Exceptions

COMP 204: Sets, Commenting & Exceptions COMP 204: Sets, Commenting & Exceptions Material from Carlos G. Oliver, Christopher J.F. Cameron October 12, 2018 1/31 Reminder CSUS is holding a midterm review session on Monday, October 15th, from 6-9pm.

More information

Python a modern scripting PL. Python

Python a modern scripting PL. Python Python a modern scripting PL Basic statements Basic data types & their operations Strings, lists, tuples, dictionaries, files Functions Strings Dictionaries Many examples originally from O Reilly Learning

More information

Introduction to Python (All the Basic Stuff)

Introduction to Python (All the Basic Stuff) Introduction to Python (All the Basic Stuff) 1 Learning Objectives Python program development Command line, IDEs, file editing Language fundamentals Types & variables Expressions I/O Control flow Functions

More information

AI Programming CS S-02 Python

AI Programming CS S-02 Python AI Programming CS662-2013S-02 Python David Galles Department of Computer Science University of San Francisco 02-0: Python Name python comes from Monte Python s Flying Circus Most python references use

More information

The PCAT Programming Language Reference Manual

The PCAT Programming Language Reference Manual The PCAT Programming Language Reference Manual Andrew Tolmach and Jingke Li Dept. of Computer Science Portland State University September 27, 1995 (revised October 15, 2002) 1 Introduction The PCAT language

More information

Modern Programming Languages. Lecture LISP Programming Language An Introduction

Modern Programming Languages. Lecture LISP Programming Language An Introduction Modern Programming Languages Lecture 18-21 LISP Programming Language An Introduction 72 Functional Programming Paradigm and LISP Functional programming is a style of programming that emphasizes the evaluation

More information

Programming I. Course 9 Introduction to programming

Programming I. Course 9 Introduction to programming Programming I Course 9 Introduction to programming What we talked about? Modules List Comprehension Generators Recursive Functions Files What we talk today? Object Oriented Programming Classes Objects

More information

LECTURE 8: SETS. Software Engineering Mike Wooldridge

LECTURE 8: SETS. Software Engineering Mike Wooldridge LECTURE 8: SETS Mike Wooldridge 1 What is a Set? The concept of a set is used throughout mathematics; its formal definition matches closely our intuitive understanding of the word. Definition: A set is

More information

Course May 18, Advanced Computational Physics. Course Hartmut Ruhl, LMU, Munich. People involved. SP in Python: 3 basic points

Course May 18, Advanced Computational Physics. Course Hartmut Ruhl, LMU, Munich. People involved. SP in Python: 3 basic points May 18, 2017 3 I/O 3 I/O 3 I/O 3 ASC, room A 238, phone 089-21804210, email hartmut.ruhl@lmu.de Patrick Böhl, ASC, room A205, phone 089-21804640, email patrick.boehl@physik.uni-muenchen.de. I/O Scientific

More information

CSC326 Python Sequences i. CSC326 Python Sequences

CSC326 Python Sequences i. CSC326 Python Sequences i CSC326 Python Sequences ii REVISION HISTORY NUMBER DATE DESCRIPTION NAME 1.0 2011-09 JZ iii Contents 1 Agenda 1 2 while Statement 1 3 Sequence Overview 2 4 String 2 5 Lists 4 6 Dictionary 5 7 Tuples

More information

List of squares. Program to generate a list containing squares of n integers starting from 0. list. Example. n = 12

List of squares. Program to generate a list containing squares of n integers starting from 0. list. Example. n = 12 List of squares Program to generate a list containing squares of n integers starting from 0 Example list n = 12 squares = [] for i in range(n): squares.append(i**2) print(squares) $ python3 squares.py

More information

Functions, Scope & Arguments. HORT Lecture 12 Instructor: Kranthi Varala

Functions, Scope & Arguments. HORT Lecture 12 Instructor: Kranthi Varala Functions, Scope & Arguments HORT 59000 Lecture 12 Instructor: Kranthi Varala Functions Functions are logical groupings of statements to achieve a task. For example, a function to calculate the average

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

Iterators & Generators

Iterators & Generators Iterators & Generators Sequences A sequence is something that you can: Index into Get the length of What are some examples of sequences? Sequences We ve been working with sequences all semester! Examples:

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

CMPT 120 Lists and Strings. Summer 2012 Instructor: Hassan Khosravi

CMPT 120 Lists and Strings. Summer 2012 Instructor: Hassan Khosravi CMPT 120 Lists and Strings Summer 2012 Instructor: Hassan Khosravi All of the variables that we have used have held a single item One integer, floating point value, or string often you find that you want

More information

Abstract Data Types. CS 234, Fall Types, Data Types Abstraction Abstract Data Types Preconditions, Postconditions ADT Examples

Abstract Data Types. CS 234, Fall Types, Data Types Abstraction Abstract Data Types Preconditions, Postconditions ADT Examples Abstract Data Types CS 234, Fall 2017 Types, Data Types Abstraction Abstract Data Types Preconditions, Postconditions ADT Examples Data Types Data is stored in a computer as a sequence of binary digits:

More information

Jython. secondary. memory

Jython. secondary. memory 2 Jython secondary memory Jython processor Jython (main) memory 3 Jython secondary memory Jython processor foo: if Jython a

More information

Intro. Scheme Basics. scm> 5 5. scm>

Intro. Scheme Basics. scm> 5 5. scm> Intro Let s take some time to talk about LISP. It stands for LISt Processing a way of coding using only lists! It sounds pretty radical, and it is. There are lots of cool things to know about LISP; if

More information

CIS192 Python Programming

CIS192 Python Programming CIS192 Python Programming Data Types Joseph Cappadona University of Pennsylvania September 03, 2015 Joseph Cappadona (University of Pennsylvania) CIS 192 September 03, 2015 1 / 32 Outline 1 Data Types

More information

Data Science Python. Anaconda. Python 3.x. Includes ALL major Python data science packages. Sci-kit learn. Pandas.

Data Science Python. Anaconda.  Python 3.x. Includes ALL major Python data science packages. Sci-kit learn. Pandas. Data Science Python Anaconda Python 3.x Includes ALL major Python data science packages Sci-kit learn Pandas PlotPy Jupyter Notebooks www.anaconda.com Python - simple commands Python is an interactive

More information

Python Compact. 1 Python Compact. 2 What do we cover in this introduction lecture? February 7, What is also interesting to know?

Python Compact. 1 Python Compact. 2 What do we cover in this introduction lecture? February 7, What is also interesting to know? Python Compact February 7, 2018 1 Python Compact 1.0.1 Claus Führer, Lund University Short introduction to Python for participants of the course ** Numerical Methods - Review and Training ** Volvo Cars,

More information

Python: common syntax

Python: common syntax Lab 09 Python! Python Intro Main Differences from C++: True and False are capitals Python floors (always down) with int division (matters with negatives): -3 / 2 = -2 No variable data types or variable

More information

61A Lecture 2. Friday, August 28, 2015

61A Lecture 2. Friday, August 28, 2015 61A Lecture 2 Friday, August 28, 2015 Names, Assignment, and User-Defined Functions (Demo) Types of Expressions Primitive expressions: 2 add 'hello' Number or Numeral Name String Call expressions: max

More information