Fundamentals of Programming. Functions Redux. Event-based Programming. File and Web IO. November 4th, 2014

Size: px
Start display at page:

Download "Fundamentals of Programming. Functions Redux. Event-based Programming. File and Web IO. November 4th, 2014"

Transcription

1 Fundamentals of Programming Functions Redux. Event-based Programming. File and Web IO. November 4th, 2014

2 Today Briefly show file and web IO. Revisit functions. Learn a bit more about them. Event-based programming in Tkinter.

3 File and Web Input/Output

4 File I/O 3 Steps 1. Opening a file Associate file on hard disk with an object in your program. 2. Operations to manipulate the file object - read the information in the file - write new information to the file 3. Closing the file Any bookkeeping to maintain the interaction file on disk file object in program is ended.

5 File I/O reading and writing fin = open( funnyquotes.txt, r ) text = fin.read() fin.close() fout = open( funnyquotes.txt, w ) text = Laugh and the world laughs with you, snore and you sleep alone. fout.write(text) fout.close()

6 Functions for reading and writing def readfile(filename, mode="rt"): # rt = "read text" with open(filename, mode) as fin: return fin.read() text = readfile( funnyquotes.txt ) def writefile(filename, contents, mode="wt"): # wt = "write text" with open(filename, mode) as fout: fout.write(contents) s = Laugh and the world laughs with you, snore and you sleep alone. writefile( funnyquotes.txt, s) (open the file, then close it, even if an exception occurs)

7 Function for reading a webpage import urllib import contextlib def readwebpage(url): assert(url.startswith(" with contextlib.closing(urllib.urlopen(url)) as fin: return fin.read() html = readwebpage( ) html contains the HTML code for the webpage. You need to extract the information you want.

8 Functions Revisited

9 Functions: First class objects Functions are first-class citizens: Can use them like you use any other object. (in Python, pretty much everything is an object) - Can pass functions as arguments to other functions - Functions can be return values for other functions - Functions can be assigned to other variables, or can be stored in data structures (e.g. lists)

10 Functions: First class objects def f(x): return x g = f print g(5) print dir(f) [' call ', ' class ', ' closure ', ' code ', ' defaults ', ' delattr ', ' dict ', ' doc ', ' format ', ' get ', ' getattribute ', ' globals ', ' hash ', ' init ', ' module ', ' name ', ' new ', ' reduce ', ' reduce_ex ', ' repr ', ' setattr ', ' sizeof ', ' str ', ' subclasshook ', 'func_closure', 'func_code', 'func_defaults', 'func_dict', 'func_doc', 'func_globals', 'func_name']

11 Functions: First class objects def testsort(sortfn, n): a = [random.randint(0, 2**31) for i in xrange(n)] start = time.time() sortfn(a) end = time.time() return end - start sortfunctions = [selectionsort, bubblesort, mergesort] n = 2**12 for sortfn in sortfunctions: testsort(sortfn, n)

12 Functions: Default argument values def myprint(x, times=1): for i in xrange(times): print x myprint( Hello ) myprint( Hi, 5) Hello Hi Hi Hi Hi Hi

13 Functions: Default argument values print cmp( fred, wilma ) print cmp( wilma, fred ) print cmp( fred, fred ) # -1 # 1 # 0 names = [ fred, wilma, barney, betty, dino ] print sorted(names) # [ barney, betty, dino, fred, wilma ] # sorted uses the default cmp function as a default argument def comparelengths(a, b): return len(a) - len(b) print sorted(names, comparelengths) # [ fred, dino, wilma, betty, barney ]

14 Functions: Default argument values Need to be careful with default argument values. def f(x, a=[]): a.append(x) print a f(1) f(2) # expect: [1] # expect: [2] reality: [1] reality: [1, 2] Default argument is evaluated once when function is defined.

15 Functions: Default argument values Need to be careful with default argument values. def f(x, a=[]): a.append(x) print a f(1) f(2) # expect: [1] # expect: [2] reality: [1] reality: [1, 2] defaulta > [] if given as input, use that. if not given as input, use an alias of defaulta. Default argument is evaluated once when function is defined.

16 Functions: Keyword arguments def f(x, y, z): print x, y, z def f(x, y=0, z=0): print x, y, z f(1, 2, 3) f(1, z=3, y=2) canvas.create_rectangle(0, 0, 50, 50, fill= green, outline= red, width=3)

17 Functions: Variable length argument list def longestword(*args): * packs arguments into one tuple if (len(args) == 0): return None result = args[0] for word in args: if (len(word) > len(result)): result = word return result print longestword( this, is, really, nice ) args = ( this, is, really, nice )

18 Functions: Variable length argument list def longestword(*args): if (len(args) == 0): return None result = args[0] for word in args: if (len(word) > len(result)): result = word return result print longestword( this, is, really, nice ) words = ( this, is, really, nice ) print longestword(words) args = (( this, is, really, nice ), )

19 Functions: Variable length argument list def longestword(*args): if (len(args) == 0): return None result = args[0] for word in args: if (len(word) > len(result)): result = word return result print longestword( this, is, really, nice ) words = ( this, is, really, nice ) print longestword(words[0], words[1], words[2], words[3])

20 Functions: Variable length argument list def longestword(*args): if (len(args) == 0): return None result = args[0] for word in args: if (len(word) > len(result)): result = word return result print longestword( this, is, really, nice ) words = ( this, is, really, nice ) (a, b, c, d) = words print longestword(a, b, c, d)

21 Functions: Variable length argument list def longestword(*args): if (len(args) == 0): return None result = args[0] for word in args: if (len(word) > len(result)): result = word return result print longestword( this, is, really, nice ) words = ( this, is, really, nice ) print longestword(*words) * unpacks the tuple

22 Functions: Documentation string help(max) print max. doc max(iterable[, key=func]) -> value max(a, b, c,...[, key=func]) -> value With a single iterable argument, return its largest item. With two or more arguments, return the largest argument. print longestword. doc None

23 Functions: Documentation string def longestword(*args): Returns the longest argument if (len(args) == 0): return None result = args[0] for word in args: if (len(word) > len(result)): result = word return result print longestword. doc Returns the longest argument

24 Functions: Anonymous functions Motivational example: class Book(object): def init (self, title, author, year): self.title = title self.author = author self.year = year def getyear(book): return book.year b = Book( Hamlet, Shakespeare, 1603) Creates an object of type Book print getyear(book( It, Stephen King, 1986)) Didn t assign it to a variable first

25 Functions: Anonymous functions Motivational example: class Book(object): def init (self, title, author, year): self.title = title self.author = author self.year = year def getyear(book): return book.year b = Book( Hamlet, Shakespeare, 1603) Creates an object of type Book library = [] b.append(book( It, Stephen King, 1986))

26 Functions: Anonymous functions Can - sort of - create and use functions similarly with lambda expressions. f = lambda x,y: x+y Creates an object of type function

27 Functions: Anonymous functions Can - sort of - create and use functions similarly with lambda expressions. f = lambda x,y: x+y inputs Creates an object of type function

28 Functions: Anonymous functions Can - sort of - create and use functions similarly with lambda expressions. f = lambda x,y: x+y Creates an object of type function an expression (the value is returned)

29 Functions: Anonymous functions Can - sort of - create and use functions similarly with lambda expressions. f = lambda x,y: x+y Creates an object of type function f = lambda x,y: print x+y # Crashes names = [ fred, wilma, barney, betty, dino ] print sorted(names, lambda a,b: len(a) - len(b)) Didn t assign it to a variable first

30 Functions: Nested functions Can be used to avoid polluting the global space. def f(a): def evens(a): return [value for value in a if (value % 2) == 0] return list(reversed(evens(a))) print f(range(10)) print evens(range(10)) # Crashes

31 Functions: Nested functions Can be used to change function signature. def nqueens(n): def solve(n, m, constraints): return solve(n, n, [])

32 Functions: Nested functions Can be used to change function signature. Suppose you have a math function f(x, y) For each fixed variable: f y (x) y, f(x, y) defines a function in one Example: f(x, y) =x + y f 0 (x) =x f 1 (x) =x +1 f 2 (x) =x +2 f(x,y) is like a collection of functions in one variable. How can we generate these functions in Python?

33 Functions: Nested functions How to do this in Python: def f(y): def g(x): return x + y return g f_1 = f(1) print f_1(5) f_2 = f(2) print f_2(5) y is called a non-local variable. For each y, this returns a different function Returned value: g packaged together with a y value Closure: a function bound together with a value

34 Functions: Nested functions How to do this in Python: def f(y): return lambda x: x + y f_1 = f(1) print f_1(5) f_2 = f(2) print f_2(5)

35 Functions: Nested functions How to do this in Python: def makeadderfn(delta): def g(x): return x + delta return g add3 = makeadderfn(3) add4 = makeadderfn(4) print add3(5) print add4(5)

36 Functions: Nested functions How to do this in Python: def makeadderfn(delta): def g(x): delta = delta + 1 return x + delta return g Error add3 = makeadderfn(3) add4 = makeadderfn(4) print add3(5) print add4(5)

37 Functions: Nested functions Another example: def f(canvas): def fstripped(canvas): def g(): return f(canvas) return g h = fstripped(canvas) # Now h is like f canvas

38 Event based programming in Tkinter

39 The high level structure Asynchronous: Flow of the program is determined by events e.g. mouse clicks, key presses 3 Parts: - Event handler functions - Binding events to correct event-handler functions - Main loop: - listens for events - triggers a callback function when event is detected. (events are added to an event queue)

40 from Tkinter import * def mousepressed(event): def keypressed(event): def timerfired(): def redrawall(): def init(): def run(): # Create the root and the canvas global canvas root = Tk() canvas = Canvas(root, width=300, height=200) canvas.pack() # Set up canvas data and call init class Struct: pass canvas.data = Struct() init() # Bind events to correct event handler functions root.bind("<button-1>", mousepressed) root.bind("<key>", keypressed) timerfired() # Main loop root.mainloop()

41 from Tkinter import * def mousepressed(canvas, event): def keypressed(canvas, event): def timerfired(canvas): def redrawall(canvas): def init(canvas): def run(): # Create the root and the canvas root = Tk() canvas = Canvas(root, width=300, height=200) canvas.pack() # Set up canvas data and call init class Struct: pass canvas.data = Struct() init() # Bind events to correct event handler functions root.bind("<button-1>", mousepressed) root.bind("<key>", keypressed) timerfired() # Main loop root.mainloop()

42 from Tkinter import * def mousepressed(canvas, event): def keypressed(canvas, event): def timerfired(canvas): def redrawall(canvas): def init(canvas): def run(): # Create the root and the canvas root = Tk() canvas = Canvas(root, width=300, height=200) canvas.pack() # Set up canvas data and call init class Struct: pass canvas.data = Struct() init(canvas) # Bind events to correct event handler functions root.bind("<button-1>", mousepressed(canvas)) root.bind("<key>", keypressed(canvas)) timerfired(canvas) # Main loop root.mainloop() Not a reference to a function

43 def run(): # Create the root and the canvas root = Tk() canvas = Canvas(root, width=300, height=200) canvas.pack() # Set up canvas data and call init class Struct: pass canvas.data = Struct() init(canvas) # Bind events to correct event handler functions def f(event): mousepressed(canvas, event) root.bind("<button-1>", f) root.bind("<key>", keypressed(canvas)) timerfired(canvas) # Main loop root.mainloop() f > mousepressed canvas

44 def run(): # Create the root and the canvas root = Tk() canvas = Canvas(root, width=300, height=200) canvas.pack() # Set up canvas data and call init class Struct: pass canvas.data = Struct() init(canvas) # Bind events to correct event handler functions def f(event): mousepressed(canvas, event) root.bind("<button-1>", f) root.bind("<key>", lambda event: keypressed(canvas, event)) timerfired(canvas) # Main loop root.mainloop()

45 def timerfired(canvas): redrawall(canvas) delay = 250 # milliseconds def f(): timerfired(canvas) canvas.after(delay, f) f > timerfired canvas Wants a reference to a function

46 eventbasedanimationclass.py eventbasedanimationdemo.py

47 Event list Event <Button-1> <Key> <Return> <B1-Motion> <ButtonRelease-1> <Double-Button-1> <Enter> <Leave> <Configure> Description Mouse left button click Any key press Enter key press Drag: mouse move with left button down Mouse left button release Double click (with left button) Mouse pointer enters the widget Mouse pointer leaves the widget The widget changes size

48 Event object properties Attribute Description type The event type x, y The current mouse position char The character code (for keyboard events) keysym The key symbol (for keyboard events) num The button number (for mouse button events) width, height widget The new size of the widget (for configure events) The widget that the event occurred on (as a reference)

Positional, keyword and default arguments

Positional, keyword and default arguments O More on Python n O Functions n Positional, keyword and default arguments in repl: >>> def func(fst, snd, default="best!"):... print(fst, snd, default)... >>> func(snd='is', fst='python') ('Python', 'is',

More information

Midterm #1 Fall minutes

Midterm #1 Fall minutes 15-112 Midterm #1 Fall 2014 80 minutes Name: Andrew ID: @andrew.cmu.edu Section: INSTRUCTIONS You may not use any books, notes, or electronic devices during this exam. You may not ask questions about the

More information

Software Development Python (Part B)

Software Development Python (Part B) Software Development Python (Part B) Davide Balzarotti Eurecom 1 List Comprehension It is a short way to construct a list based on the content of other existing lists Efficient Elegant Concise List comprehensions

More information

What is a class? Responding to messages. Short answer 7/19/2017. Code Listing 11.1 First Class. chapter 11. Introduction to Classes

What is a class? Responding to messages. Short answer 7/19/2017. Code Listing 11.1 First Class. chapter 11. Introduction to Classes chapter 11 Code Listing 11.1 First Class Introduction to Classes What is a class? If you have done anything in computer science before, you likely will have heard the term object oriented programming (OOP)

More information

CS61A Lecture 15 Object Oriented Programming, Mutable Data Structures. Jom Magrotker UC Berkeley EECS July 12, 2012

CS61A Lecture 15 Object Oriented Programming, Mutable Data Structures. Jom Magrotker UC Berkeley EECS July 12, 2012 CS61A Lecture 15 Object Oriented Programming, Mutable Data Structures Jom Magrotker UC Berkeley EECS July 12, 2012 COMPUTER SCIENCE IN THE NEWS http://www.iospress.nl/ios_news/music to my eyes device converting

More information

Fundamentals of Programming. Week 5- Lecture 1: Intro to Object Oriented Programming (OOP)

Fundamentals of Programming. Week 5- Lecture 1: Intro to Object Oriented Programming (OOP) 15-112 Fundamentals of Programming Week 5- Lecture 1: Intro to Object Oriented Programming (OOP) June 19, 2017 What is object oriented programming (OOP)? 1. The ability to create your own data types. s

More information

Midterm I Practice Problems

Midterm I Practice Problems 15-112 Midterm I Practice Problems Name: Section: andrewid: This PRACTICE midterm is not meant to be a perfect representation of the upcoming midterm! You are responsible for knowing all material covered

More information

Tkinter Part II: Buttons, Lambda & Dynamic Content

Tkinter Part II: Buttons, Lambda & Dynamic Content Tkinter Part II: Buttons, Lambda & Dynamic Content July 8, 2015 Brian A. Malloy Slide 1 of 11 1. We further investigate Labels and Buttons and hook Python actions to these widgets. We present lambda functions,

More information

Fundamentals of Programming. Intro to Object Oriented Programming (OOP) Anil Ada

Fundamentals of Programming. Intro to Object Oriented Programming (OOP) Anil Ada 15-112 Fundamentals of Programming Intro to Object Oriented Programming (OOP) Anil Ada aada@cs.cmu.edu October 21st, 2014 What is object oriented programming (OOP)? 1. The ability to create your own data

More information

Programming with Python

Programming with Python Programming with Python Lecture 3: Python Functions IPEC Winter School 2015 B-IT Dr. Tiansi Dong & Dr. Joachim Köhler Python Functions arguments return obj Global vars Files/streams Function Global vars

More information

What is a Class? Short Answer. Responding to Messages. Everything in Python is an Object 11/8/2010

What is a Class? Short Answer. Responding to Messages. Everything in Python is an Object 11/8/2010 The Practice of Computing Using PYTHON William Punch Richard Enbody Chapter 11 Introduction to Classes class Student(object): """Simple Student class.""" def init (self,first='', last='', id=0): # init

More information

Functions #5. Serdar ARITAN. Department of Computer Graphics Hacettepe University, Ankara, Turkey

Functions #5. Serdar ARITAN. Department of Computer Graphics Hacettepe University, Ankara, Turkey #5 Serdar ARITAN Department of Computer Graphics Hacettepe University, Ankara, Turkey 1 I have never considered Python to be heavily influenced by functional languages, no matter what people say or think.

More information

Chapter 9 GUI Programming Using Tkinter. Copyright 2012 by Pearson Education, Inc. All Rights Reserved.

Chapter 9 GUI Programming Using Tkinter. Copyright 2012 by Pearson Education, Inc. All Rights Reserved. Chapter 9 GUI Programming Using Tkinter 1 Motivations Tkinter is not only a useful tool for developing GUI projects, but also a valuable pedagogical tool for learning object-oriented programming. 2 Objectives

More information

Lecture #15: Generic Functions and Expressivity. Last modified: Wed Mar 1 15:51: CS61A: Lecture #16 1

Lecture #15: Generic Functions and Expressivity. Last modified: Wed Mar 1 15:51: CS61A: Lecture #16 1 Lecture #15: Generic Functions and Expressivity Last modified: Wed Mar 1 15:51:48 2017 CS61A: Lecture #16 1 Consider the function find: Generic Programming def find(l, x, k): """Return the index in L of

More information

61A Lecture 2. Wednesday, September 4, 2013

61A Lecture 2. Wednesday, September 4, 2013 61A Lecture 2 Wednesday, September 4, 2013 Names, Assignment, and User-Defined Functions (Demo) Types of Expressions Primitive expressions: 2 add 'hello' Number or Numeral Name String Call expressions:

More information

CS2304: Python for Java Programmers. CS2304: Advanced Function Topics

CS2304: Python for Java Programmers. CS2304: Advanced Function Topics CS2304: Advanced Function Topics Functions With An Arbitrary Number of Parameters Let s say you wanted to create a function where you don t know the exact number of parameters. Python gives you a few ways

More information

All-Singing All-Dancing Python Bytecode Larry Hastings EuroPython 2013 July 2, 2013

All-Singing All-Dancing Python Bytecode Larry Hastings EuroPython 2013 July 2, 2013 All-Singing All-Dancing Python Bytecode Larry Hastings larry@hastings.org EuroPython 2013 July 2, 2013 Introduction Intermediate CPython 3.3.0 100% roughly applicable elsewhere What Is Bytecode? Opcodes

More information

Mid Unit Review. Of the four learning outcomes for this unit, we have covered the first two. 1.1 LO1 2.1 LO2 LO2

Mid Unit Review. Of the four learning outcomes for this unit, we have covered the first two. 1.1 LO1 2.1 LO2 LO2 Lecture 8 Mid Unit Review Of the four learning outcomes for this unit, we have covered the first two. LO Learning outcome (LO) AC Assessment criteria for pass The learner can: LO1 Understand the principles

More information

CS 360 Programming Languages Interpreters

CS 360 Programming Languages Interpreters CS 360 Programming Languages Interpreters Implementing PLs Most of the course is learning fundamental concepts for using and understanding PLs. Syntax vs. semantics vs. idioms. Powerful constructs like

More information

Programming Training. This Week: Tkinter for GUI Interfaces. Some examples

Programming Training. This Week: Tkinter for GUI Interfaces. Some examples Programming Training This Week: Tkinter for GUI Interfaces Some examples Tkinter Overview Set of widgets designed by John K. Ousterhout, 1987 Tkinter == Tool Kit Interface Mean to be driven by Tcl (Toolkit

More information

Python Scripting for Computational Science

Python Scripting for Computational Science Hans Petter Langtangen Python Scripting for Computational Science Third Edition With 62 Figures 43 Springer Table of Contents 1 Introduction... 1 1.1 Scripting versus Traditional Programming... 1 1.1.1

More information

Chapter 1. Fundamentals of Higher Order Programming

Chapter 1. Fundamentals of Higher Order Programming Chapter 1 Fundamentals of Higher Order Programming 1 The Elements of Programming Any powerful language features: so does Scheme primitive data procedures combinations abstraction We will see that Scheme

More information

Midterm #2a Fall minutes DO NOT WRITE IN THIS AREA

Midterm #2a Fall minutes DO NOT WRITE IN THIS AREA 15-112 Midterm #2a Fall 2015 80 minutes Name: Andrew ID: @andrew.cmu.edu Section: You may not use any books, notes, or electronic devices during this exam. You may not ask questions about the exam except

More information

INF 102 CONCEPTS OF PROG. LANGS FUNCTIONAL COMPOSITION. Instructors: James Jones Copyright Instructors.

INF 102 CONCEPTS OF PROG. LANGS FUNCTIONAL COMPOSITION. Instructors: James Jones Copyright Instructors. INF 102 CONCEPTS OF PROG. LANGS FUNCTIONAL COMPOSITION Instructors: James Jones Copyright Instructors. Topics Recursion Higher-order functions Continuation-Passing Style Monads (take 1) Identity Monad

More information

INF 212 ANALYSIS OF PROG. LANGS FUNCTION COMPOSITION. Instructors: Crista Lopes Copyright Instructors.

INF 212 ANALYSIS OF PROG. LANGS FUNCTION COMPOSITION. Instructors: Crista Lopes Copyright Instructors. INF 212 ANALYSIS OF PROG. LANGS FUNCTION COMPOSITION Instructors: Crista Lopes Copyright Instructors. Topics Recursion Higher-order functions Continuation-Passing Style Monads (take 1) Identity Monad Maybe

More information

OOP and Scripting in Python Advanced Features

OOP and Scripting in Python Advanced Features OOP and Scripting in Python Advanced Features Giuliano Armano Emanuele Tamponi Advanced Features Structure of a Python Script More on Defining Functions Default Argument Values Keyword Arguments Arbitrary

More information

Level 3 Computing Year 2 Lecturer: Phil Smith

Level 3 Computing Year 2 Lecturer: Phil Smith Level 3 Computing Year 2 Lecturer: Phil Smith We looked at: Debugging Previously BTEC Level 3 Year 2 Unit 16 Procedural programming Now Now we will look at: GUI applications. BTEC Level 3 Year 2 Unit 16

More information

[CHAPTER] 1 INTRODUCTION 1

[CHAPTER] 1 INTRODUCTION 1 FM_TOC C7817 47493 1/28/11 9:29 AM Page iii Table of Contents [CHAPTER] 1 INTRODUCTION 1 1.1 Two Fundamental Ideas of Computer Science: Algorithms and Information Processing...2 1.1.1 Algorithms...2 1.1.2

More information

JavaScript. Like PHP, JavaScript is a modern programming language that is derived from the syntax at C.

JavaScript. Like PHP, JavaScript is a modern programming language that is derived from the syntax at C. Like PHP, JavaScript is a modern programming language that is derived from the syntax at C. It has been around just about as long as PHP, also having been invented in 1995. JavaScript, HTML, and CSS make

More information

Python Scripting for Computational Science

Python Scripting for Computational Science Hans Petter Langtangen Python Scripting for Computational Science Third Edition With 62 Figures Sprin ger Table of Contents 1 Introduction 1 1.1 Scripting versus Traditional Programming 1 1.1.1 Why Scripting

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

Tkinter: Input and Output Bindings. Marquette University

Tkinter: Input and Output Bindings. Marquette University Tkinter: Input and Output Bindings Marquette University Tkinter Variables Tkinter contains a useful mechanism to connect widgets to variables This allows us to have variables change when widgets do and

More information

ENGR/CS 101 CS Session Lecture 15

ENGR/CS 101 CS Session Lecture 15 ENGR/CS 101 CS Session Lecture 15 Log into Windows/ACENET (reboot if in Linux) Use web browser to go to session webpage http://csserver.evansville.edu/~hwang/f14-courses/cs101.html Right-click on lecture15.py

More information

Lecture 3 - Overview. More about functions Operators Very briefly about naming conventions Graphical user interfaces (GUIs)

Lecture 3 - Overview. More about functions Operators Very briefly about naming conventions Graphical user interfaces (GUIs) Lecture 3 - Overview More about functions Operators Very briefly about naming conventions Graphical user interfaces (GUIs) Function parameters Passed by reference, but the standard implication that the

More information

What's New in Python 2.2

What's New in Python 2.2 What's New in Python 2.2 LinuxWorld - New York City - January 2002 Guido van Rossum Director of PythonLabs at Zope Corporation guido@python.org guido@zope.com Overview Appetizers Nested Scopes Int/Long

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

PyTrie Documentation. Release 0.3. George Sakkis

PyTrie Documentation. Release 0.3. George Sakkis PyTrie Documentation Release 0.3 George Sakkis Jun 05, 2017 Contents 1 Usage 3 2 Reference documentation 5 2.1 Classes.................................................. 5 2.2 Trie methods...............................................

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

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

Introduction to Programming Using Python Lecture 6. Dr. Zhang COSC 1437 Spring, 2018 March 01, 2018

Introduction to Programming Using Python Lecture 6. Dr. Zhang COSC 1437 Spring, 2018 March 01, 2018 Introduction to Programming Using Python Lecture 6 Dr. Zhang COSC 1437 Spring, 2018 March 01, 2018 Chapter 9 GUI Programming Using Tkinter Getting started with Tkinter with a simple example. Code example:

More information

User Interfaces. getting arguments of the command line a command line interface to store points fitting points with polyfit of numpy

User Interfaces. getting arguments of the command line a command line interface to store points fitting points with polyfit of numpy User Interfaces 1 Command Line Interfaces getting arguments of the command line a command line interface to store points fitting points with polyfit of numpy 2 Encapsulation by Object Oriented Programming

More information

LECTURE 2. Python Basics

LECTURE 2. Python Basics LECTURE 2 Python Basics MODULES ''' Module fib.py ''' from future import print_function def even_fib(n): total = 0 f1, f2 = 1, 2 while f1 < n: if f1 % 2 == 0: total = total + f1 f1, f2 = f2, f1 + f2 return

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

Easy Graphical User Interfaces

Easy Graphical User Interfaces Easy Graphical User Interfaces with breezypythongui Types of User Interfaces GUI (graphical user interface) TUI (terminal-based user interface) UI Inputs Outputs Computation Terminal-Based User Interface

More information

PTN-202: Advanced Python Programming Course Description. Course Outline

PTN-202: Advanced Python Programming Course Description. Course Outline PTN-202: Advanced Python Programming Course Description This 4-day course picks up where Python I leaves off, covering some topics in more detail, and adding many new ones, with a focus on enterprise development.

More information

(b) If a heap has n elements, what s the height of the tree?

(b) If a heap has n elements, what s the height of the tree? CISC 5835 Algorithms for Big Data Fall, 2018 Homework Assignment #4 1 Answer the following questions about binary tree and heap: (a) For a complete binary tree of height 4 (we consider a tree with just

More information

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

(IUCAA, Pune)   kaustubh[at]iucaa[dot]ernet[dot]in. Basics of Python - 2 by Kaustubh Vaghmare (IUCAA, Pune) E-mail: kaustubh[at]iucaa[dot]ernet[dot]in 1 of 54 Sunday 16 February 2014 05:30 PM Our First Program - Rewritten! Let us introduce the following

More information

Fundamentals of Programming. Week 11 - Lecture 1: OOP Part 2.

Fundamentals of Programming. Week 11 - Lecture 1: OOP Part 2. 15-112 Fundamentals of Programming Week 11 - Lecture 1: OOP Part 2. March 29, 2016 >> Inheritance Today s Menu (Wrapping up OOP) - Employee and Student as subclasses of Person - isintance( ) vs type( )

More information

Alastair Burt Andreas Eisele Christian Federmann Torsten Marek Ulrich Schäfer. October 6th, Universität des Saarlandes. Introduction to Python

Alastair Burt Andreas Eisele Christian Federmann Torsten Marek Ulrich Schäfer. October 6th, Universität des Saarlandes. Introduction to Python Outline Alastair Burt Andreas Eisele Christian Federmann Torsten Marek Ulrich Schäfer Universität des Saarlandes October 6th, 2009 Outline Outline Today s Topics: 1 More Examples 2 Cool Stuff 3 Text Processing

More information

Python Decorators. Chris Calloway

Python Decorators. Chris Calloway Python Decorators Chris Calloway What is a Decorator? An object. What is a Decorator? An object. A callable object which is passed a function reference as its sole argument. What is a Decorator? An object.

More information

Intro. Classes & Inheritance

Intro. Classes & Inheritance Intro Functions are useful, but they're not always intuitive. Today we're going to learn about a different way of programming, where instead of functions we will deal primarily with objects. This school

More information

CIS192: Python Programming

CIS192: Python Programming CIS192: Python Programming Functions and Functional Programming Harry Smith University of Pennsylvania January 25, 2018 Harry Smith (University of Pennsylvania) CIS 192 Lecture 3 January 25, 2018 1 / 39

More information

CSE : Python Programming

CSE : Python Programming CSE 399-004: Python Programming Lecture 08: Graphical User Interfaces with wxpython March 12, 2005 http://www.seas.upenn.edu/~cse39904/ Plan for today and next time Today: wxpython (part 1) Aside: Arguments

More information

Thinking in Tkinter. Thinking in Tkinter. by Stephen Ferg ferg.org) revised:

Thinking in Tkinter. Thinking in Tkinter. by Stephen Ferg ferg.org) revised: 1 of 53 Thinking in Tkinter by Stephen Ferg (steve@ ferg.org) revised: 2005-07-17 This file contains the source code for all of the files in the Thinking in Tkinter series. If you print this file with

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

Introduction to C++ Introduction. Structure of a C++ Program. Structure of a C++ Program. C++ widely-used general-purpose programming language

Introduction to C++ Introduction. Structure of a C++ Program. Structure of a C++ Program. C++ widely-used general-purpose programming language Introduction C++ widely-used general-purpose programming language procedural and object-oriented support strong support created by Bjarne Stroustrup starting in 1979 based on C Introduction to C++ also

More information

CS 2316 Exam 3 Fall 2011

CS 2316 Exam 3 Fall 2011 CS 2316 Exam 3 Fall 2011 Name : 1. (2 points) Grading TA: Integrity: By taking this exam, you pledge that this is your work and you have neither given nor received inappropriate help during the taking

More information

Midterm #2a Spring minutes

Midterm #2a Spring minutes 15-112 Midterm #2a Spring 2017 80 minutes Name: Andrew ID: @andrew.cmu.edu Section: You may not use any books, notes, or electronic devices during this exam. You may not ask questions about the exam except

More information

JavaScript Specialist v2.0 Exam 1D0-735

JavaScript Specialist v2.0 Exam 1D0-735 JavaScript Specialist v2.0 Exam 1D0-735 Domain 1: Essential JavaScript Principles and Practices 1.1: Identify characteristics of JavaScript and common programming practices. 1.1.1: List key JavaScript

More information

Introduction to C++ with content from

Introduction to C++ with content from Introduction to C++ with content from www.cplusplus.com 2 Introduction C++ widely-used general-purpose programming language procedural and object-oriented support strong support created by Bjarne Stroustrup

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

Algorithmic Approaches for Biological Data, Lecture #15

Algorithmic Approaches for Biological Data, Lecture #15 Algorithmic Approaches for Biological Data, Lecture #15 Katherine St. John City University of New York American Museum of Natural History 23 March 2016 Outline Sorting by Keys K. St. John (CUNY & AMNH)

More information

PYTHON FOR KIDS A Pl ayfu l I ntrodu ctio n to Prog r am m i ng J a s o n R. B r i g g s

PYTHON FOR KIDS A Pl ayfu l I ntrodu ctio n to Prog r am m i ng J a s o n R. B r i g g s PYTHON FO R K I D S A P l ay f u l I n t r o d u c t i o n to P r o g r a m m i n g Jason R. Briggs Index Symbols and Numbers + (addition operator), 17 \ (backslash) to separate lines of code, 235 in strings,

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

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

CIS192 Python Programming

CIS192 Python Programming CIS192 Python Programming Functional Programming Eric Kutschera University of Pennsylvania January 30, 2015 Eric Kutschera (University of Pennsylvania) CIS 192 January 30, 2015 1 / 31 Questions Homework

More information

CIS192 Python Programming

CIS192 Python Programming CIS192 Python Programming Functional Programming Robert Rand University of Pennsylvania February 03, 2016 Robert Rand (University of Pennsylvania) CIS 192 February 03, 2016 1 / 23 Outline 1 Function Arguments

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

(CC)A-NC 2.5 by Randall Munroe Python

(CC)A-NC 2.5 by Randall Munroe Python http://xkcd.com/353/ (CC)A-NC 2.5 by Randall Munroe Python Python: Operative Keywords Very high level language Language design is focused on readability Mulit-paradigm Mix of OO, imperative, and functional

More information

This course is designed for anyone who needs to learn how to write programs in Python.

This course is designed for anyone who needs to learn how to write programs in Python. Python Programming COURSE OVERVIEW: This course introduces the student to the Python language. Upon completion of the course, the student will be able to write non-trivial Python programs dealing with

More information

Graphical User Interface (GUI)

Graphical User Interface (GUI) Graphical User Interface (GUI) An example of Inheritance and Sub-Typing 1 Java GUI Portability Problem Java loves the idea that your code produces the same results on any machine The underlying hardware

More information

CS115 - Module 9 - filter, map, and friends

CS115 - Module 9 - filter, map, and friends Fall 2017 Reminder: if you have not already, ensure you: Read How to Design Programs, Intermezzo 3 (Section 18); Sections 19-23. Abstraction abstraction, n. 3a.... The process of isolating properties or

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

Subprogram Concept. COMP3220 Principle of Programming Languages. Zhitao Gong Spring

Subprogram Concept. COMP3220 Principle of Programming Languages. Zhitao Gong Spring Subprogram Concept COMP3220 Principle of Programming Languages Zhitao Gong 2016 Spring 1 / 30 Outline Introduction Closure Parameter Passing Summary 2 / 30 Introduction Tow fundamental abstractions process

More information

This text is used together with Mark Pilgrims book Dive Into Python 3 for the Arthead course Python Fundamentals.

This text is used together with Mark Pilgrims book Dive Into Python 3 for the Arthead course Python Fundamentals. 2 About this text This text is used together with Mark Pilgrims book Dive Into Python 3 for the Arthead course Python Fundamentals. The first part is written for Python 2 and at the end there is a section

More information

Algorithms for Bioinformatics

Algorithms for Bioinformatics 582670 Algorithms for Bioinformatics Lecture 1: Primer to algorithms and molecular biology 4.9.2012 Course format Thu 12-14 Thu 10-12 Tue 12-14 Grading Exam 48 points Exercises 12 points 30% = 1 85% =

More information

Programming Languages

Programming Languages Programming Languages Week 9 Exercises Object-oriented programming in Python (2) Objects are especially useful for factoring state and behaviour. When two (or more) different classes of object are specicialisations

More information

Downloaded from Chapter 2. Functions

Downloaded from   Chapter 2. Functions Chapter 2 Functions After studying this lesson, students will be able to: Understand and apply the concept of module programming Write functions Identify and invoke appropriate predefined functions Create

More information

Lecture no

Lecture no Advanced Algorithms and Computational Models (module A) Lecture no. 3 29-09-2014 Giacomo Fiumara giacomo.fiumara@unime.it 2014-2015 1 / 28 Expressions, Operators and Precedence Sequence Operators The following

More information

! The simplest building blocks of a language. ! Compound elements are built from simpler ones

! The simplest building blocks of a language. ! Compound elements are built from simpler ones The Elements of Programming Primitive Expressions and Statements! The simplest building blocks of a language 61 Lecture Monday, ugust 9 Means of Combination! Compound elements are built from simpler ones

More information

Learning outcomes. COMPSCI 101 Principles of Programming. Drawing 2D shapes using Characters. Printing a Row of characters

Learning outcomes. COMPSCI 101 Principles of Programming. Drawing 2D shapes using Characters. Printing a Row of characters Learning outcomes At the end of this lecture, students should be able to draw 2D shapes using characters draw 2D shapes on a Canvas COMPSCI 101 Principles of Programming Lecture 25 - Using the Canvas widget

More information

Pace University. Fundamental Concepts of CS121 1

Pace University. Fundamental Concepts of CS121 1 Pace University Fundamental Concepts of CS121 1 Dr. Lixin Tao http://csis.pace.edu/~lixin Computer Science Department Pace University October 12, 2005 This document complements my tutorial Introduction

More information

Sliders. If we start this script, we get a window with a vertical and a horizontal slider:

Sliders. If we start this script, we get a window with a vertical and a horizontal slider: Sliders Introduction A slider is a Tkinter object with which a user can set a value by moving an indicator. Sliders can be vertically or horizontally arranged. A slider is created with the Scale method().

More information

CSE341: Programming Languages Lecture 9 Function-Closure Idioms. Dan Grossman Winter 2013

CSE341: Programming Languages Lecture 9 Function-Closure Idioms. Dan Grossman Winter 2013 CSE341: Programming Languages Lecture 9 Function-Closure Idioms Dan Grossman Winter 2013 More idioms We know the rule for lexical scope and function closures Now what is it good for A partial but wide-ranging

More information

Binghamton University. CS-120 Summer Introduction to C. Text: Introduction to Computer Systems : Chapters 11, 12, 14, 13

Binghamton University. CS-120 Summer Introduction to C. Text: Introduction to Computer Systems : Chapters 11, 12, 14, 13 Introduction to C Text: Introduction to Computer Systems : Chapters 11, 12, 14, 13 Problem: Too Many Details For example: Lab 7 Bubble Sort Needed to keep track of too many details! Outer Loop When do

More information

CS Introduction to Computational and Data Science. Instructor: Renzhi Cao Computer Science Department Pacific Lutheran University Spring 2017

CS Introduction to Computational and Data Science. Instructor: Renzhi Cao Computer Science Department Pacific Lutheran University Spring 2017 CS 133 - Introduction to Computational and Data Science Instructor: Renzhi Cao Computer Science Department Pacific Lutheran University Spring 2017 Introduction to Python II In the previous class, you have

More information

Modules and scoping rules

Modules and scoping rules C H A P T E R 1 1 Modules and scoping rules 11.1 What is a module? 106 11.2 A first module 107 11.3 The import statement 109 11.4 The module search path 110 11.5 Private names in modules 112 11.6 Library

More information

Selected GUI elements:

Selected GUI elements: Selected GUI elements: Element tkinter Class Description Frame Frame Holds other GUI elements Label Label Displays uneditable text or icons Button Button Performs an action when the user activates it Text

More information

Lecture 7: Lambda & Abstract Data Types

Lecture 7: Lambda & Abstract Data Types UC Berkeley EECS Adj. Ass. Prof. Dr. Gerald Friedland Computational Structures in Data Science Lecture 7: Lambda & Abstract Data Types Computational Concepts Toolbox Data type: values, literals, operations,

More information

Course Outline - COMP150. Lectures and Labs

Course Outline - COMP150. Lectures and Labs Course Outline - COMP150 Lectures and Labs 1 The way of the program 1.1 The Python programming language 1.2 What is a program? 1.3 What is debugging? 1.4 Experimental debugging 1.5 Formal and natural languages

More information

Lessons on Python Functions

Lessons on Python Functions Lessons on Python Functions Walter Didimo [ 90 minutes ] Functions When you write a program, you may need to recall a certain block of instructions several times throughout your code A function is a block

More information

F21SC Industrial Programming: Python: Advanced Language Features

F21SC Industrial Programming: Python: Advanced Language Features F21SC Industrial Programming: Python: Advanced Language Features Hans-Wolfgang Loidl School of Mathematical and Computer Sciences, Heriot-Watt University, Edinburgh Semester 1 2017/18 0 No proprietary

More information

CSCI337 Organisation of Programming Languages LISP

CSCI337 Organisation of Programming Languages LISP Organisation of Programming Languages LISP Getting Started Starting Common Lisp $ clisp i i i i i i i ooooo o ooooooo ooooo ooooo I I I I I I I 8 8 8 8 8 o 8 8 I \ `+' / I 8 8 8 8 8 8 \ `-+-' / 8 8 8 ooooo

More information

CISC 1600, Lab 2.2: Interactivity in Processing

CISC 1600, Lab 2.2: Interactivity in Processing CISC 1600, Lab 2.2: Interactivity in Processing Prof Michael Mandel 1 Getting set up For this lab, we will again be using Sketchpad, a site for building processing sketches online using processing.js.

More information

Python A Technical Introduction. James Heliotis Rochester Institute of Technology December, 2009

Python A Technical Introduction. James Heliotis Rochester Institute of Technology December, 2009 Python A Technical Introduction James Heliotis Rochester Institute of Technology December, 2009 Background & Overview Beginnings Developed by Guido Van Rossum, BDFL, in 1990 (Guido is a Monty Python fan.)

More information

Webgurukul Programming Language Course

Webgurukul Programming Language Course Webgurukul Programming Language Course Take One step towards IT profession with us Python Syllabus Python Training Overview > What are the Python Course Pre-requisites > Objectives of the Course > Who

More information

Structure and Interpretation of Computer Programs

Structure and Interpretation of Computer Programs CS 61A Spring 2017 Structure and Interpretation of Computer Programs Test 1 Solutions INSTRUCTIONS You have 2 hours to complete the exam. The exam is open book, open notes, closed computer, closed calculator.

More information

A Little Python Part 3

A Little Python Part 3 A Little Python Part 3 Introducing Programming with Python I/O, Files, Object Classes, Exception Handling Outline I/O Files opening File I/O, reading writing Python Objects Defining a new object Inheritance

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

Sets. identity maps, unordered collection

Sets. identity maps, unordered collection Sets identity maps, unordered collection Sets [] for lists, () for tuples, {} for dicts, and {} for sets (2.7) construction from lists, tuples, dicts (keys), and strs in, not in, add, remove = {1, 2} a

More information