Python, Part 2. Python Object Equality x == y x is y In Java: (x.equals(y)) (x == y)

Slides:



Advertisements
Similar presentations
Python Mini-Course University of Oklahoma Department of Psychology Lesson 28 Classes and Methods 6/17/09 Python Mini-Course: Lesson 28 1.
Advertisements

A Crash Course Python. Python? Isn’t that a snake? Yes, but it is also a...
Types in Scripting Languages CS 351 – Programming Paradigms.
1 COMP 144 Programming Language Concepts Felix Hernandez-Campos Lecture 21: Functional Programming in Python COMP 144 Programming Language Concepts Spring.
Structured programming
Week 7 Lists Special thanks to Scott Shawcroft, Ryan Tucker, and Paul Beck for their work on these slides. Except where otherwise noted, this work is licensed.
Functions in Python. The indentation matters… First line with less indentation is considered to be outside of the function definition. Defining Functions.
REFERENCES: CHAPTER 8 Object-Oriented Programming (OOP) in Python.
Python 3 Some material adapted from Upenn cis391 slides and other sources.
Python Control of Flow.
Python Crash Course Classes 3 rd year Bachelors V1.0 dd Hour 7.
Data Structures Akshay Singh.  Lists in python can contain any data type  Declaring a list:  a = [‘random’,’variable’, 1, 2]
Floating point numbers in Python Floats in Python are platform dependent, but usually equivalent to an IEEE bit C “double” However, because the significand.
Python.
1 Python Control of Flow and Defining Classes LING 5200 Computational Corpus Linguistics Martha Palmer.
Introduction to Python Lecture 1. CS 484 – Artificial Intelligence2 Big Picture Language Features Python is interpreted Not compiled Object-oriented language.
Inheritance. Inhertance Inheritance is used to indicate that one class will get most or all of its features from a parent class. class Dog(Pet): Make.
And PyLNP for the RCX By: Eric Cranmer and Nick Blake.
CSC1018F: Object Orientation, Exceptions and File Handling Diving into Python Ch. 5&6 Think Like a Comp. Scientist Ch
Python: Classes By Matt Wufsus. Scopes and Namespaces A namespace is a mapping from names to objects. ◦Examples: the set of built-in names, such as the.
Sorting and Modules. Sorting Lists have a sort method >>> L1 = ["this", "is", "a", "list", "of", "words"] >>> print L1 ['this', 'is', 'a', 'list', 'of',
By: Chris Harvey Python Classes. Namespaces A mapping from names to objects Different namespaces have different mappings Namespaces have varying lifetimes.
CS 326 Programming Languages, Concepts and Implementation Instructor: Mircea Nicolescu Lecture 7.
Scheme & Functional Programming. ( ) >> 64 ( ) >> 666 (* ) >> 1200 (+ (* 3 5) (- 10 6)) >> 19.
An Introduction to Python Blake Brogdon. What is Python?  Python is an interpreted, interactive, object-oriented programming language. (from python.org)
Python functional programming. Functions are first-class objects Functions can be used as any other datatype, eg: Arguments to function Return values.
Iterators, Linked Lists, MapReduce, Dictionaries, and List Comprehensions... OH MY! Special thanks to Scott Shawcroft, Ryan Tucker, and Paul Beck for their.
Before starting OOP… Today: Review Useful tips and concepts (based on CS 11 Python track, CALTECH)
An Introduction. What is Python? Interpreted language Created by Guido Van Rossum – early 90s Named after Monty Python
P YTHON ’ S C LASSES Ian Wynyard. I NTRODUCTION TO C LASSES A class is the scope in which code is executed A class contains objects and functions that.
Higher Order Functions Special thanks to Scott Shawcroft, Ryan Tucker, and Paul Beck for their work on these slides. Except where otherwise noted, this.
Python – reading and writing files. ??? ???two ways to open a file open and file ??? How to write to relative and absolute paths?
Extra Stuff for CS106 Victor Norman CS106. break and continue break and continue are both ways to alter the flow of a loop Can be used only inside a loop.
Copyright © 2010 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 5: Looping.
11. EXCEPTION HANDLING Rocky K. C. Chang October 18, 2015 (Adapted from John Zelle’s slides)
Python Let’s get started!.
Python – May 19 Review –What is the difference between: list, tuple, set, dictionary? –When is it appropriate to use each? Creating our own data types:
Lecture 4 Python Basics Part 3.
Topic 1 Object Oriented Programming. 1-2 Objectives To review the concepts and terminology of object-oriented programming To discuss some features of.
Chapter Looping 5. The Increment and Decrement Operators 5.1.
Useful Python Techniques: A brief introduction to List Comprehensions, Functional Programming, and Generators October 4, 2011 Joe Cross.
Chapter Looping 5. The Increment and Decrement Operators 5.1.
LECTURE 2 Python Basics. MODULES So, we just put together our first real Python program. Let’s say we store this program in a file called fib.py. We have.
 Python for-statements can be treated the same as for-each loops in Java Syntax: for variable in listOrstring: body statements Example) x = "string"
Python Basics 본 자료는 다음의 웹 사이트를 정리 한 내용이니 참조 바랍니다. ythonBasics.
EXCEPTIONS. Catching exceptions Whenever a runtime error occurs, it create an exception object. The program stops running at this point and Python prints.
MapReduce, Dictionaries, List Comprehensions Special thanks to Scott Shawcroft, Ryan Tucker, and Paul Beck for their work on these slides. Except where.
CSCI/CMPE 4341 Topic: Programming in Python Chapter 7: Introduction to Object- Oriented Programming in Python – Exercises Xiang Lian The University of.
CS314 – Section 5 Recitation 10
Higher Order Functions
Intro2CS Tirgul 11.
Introduction to Higher Order (Functional Programming) (Python) part 2
Example: Vehicles What attributes do objects of Sedan have?
Python Let’s get started!.
Lecture VI Objects The OOP Concept Defining Classes Methods
Chapter 5: Looping Copyright © 2010 Pearson Education, Inc. Publishing as Pearson Addison-Wesley.
Creating and Deleting Instances Access to Attributes and Methods
CHAPTER FOUR Functions.
Python’s Errors and Exceptions
Functions and Procedures
Python Classes Python has Classes, Methods, Overloaded operators, as well as Inheritance. Its somewhat 'loose' in the since it does not have true encapsulation,
Object Oriented Programming in Python
Python Tutorial for C Programmer Boontee Kruatrachue Kritawan Siriboon
Writing Functions( ) (Part 4)
(more) Python.
Lambda Functions, MapReduce and List Comprehensions
COMPUTER PROGRAMMING SKILLS
CSE 231 Lab 11.
Migrating to Object-Oriented Programs
functions are also data! other functions as input!
Presentation transcript:

Python, Part 2

Python Object Equality x == y x is y In Java: (x.equals(y)) (x == y)

Python Exceptions try: do_stuff() if something_bad_has_happened(): raise MyException, "something happened" except MyException, e: print "My exception occurred, value: ", e.value

Python Exceptions while True: try: x = int(raw_input("Please enter a number: ")) except ValueError: print "That was no valid number. Try again."

Functional programming features: map lst = ["1", "2", "3", "4", "5"] nums = map(string.atoi, lst) # nums is now [1, 2, 3, 4, 5]

map def add(x, y): return x + y lst1 = [1, 2, 3, 4, 5] lst2 = [6, 7, 8, 9, 10] lst_sum = map(add, lst1, lst2) # lst_sum == [7, 9, 11, 13, 15]

reduce def add(x, y): return x + y lst1 = [1, 2, 3, 4, 5] sum = reduce(add, lst1) # sum == 15

filter nums = range(0,101) # [0, 1, ] def is_odd(x): return x % 2 == 1 odd_nums = filter(is_odd, nums) # odd_nums == [1, 3, 5,... 99]

Lambda: Anonymous functions t = lambda x,y: x*y def t: return x*y answer = t(2,3)

Lambda Useful for map, reduce, filter: nums = range(0,101) # [0, 1, ] odd_nums = filter(lambda x: x%2==1, nums) # odd_nums == [1, 3, 5,... 99]

Pass Comparators to Sort: #return data which has groups of a name followed by 2 scores. def get_data(): return [('fred',10,1),('bill',3,0),('betty',5,8)] a=get_data() a.sort(lambda x, y: cmp(x[2],y[2])) print a >>>[('bill', 3, 0), ('fred', 10, 1), ('betty', 5, 8)]

Each “file” is a module. Consider module called “hello.py”: def printer(message): print message In module main.py write: import hello hello.printer(“hello”) -OR- from hello import printer printer(“hello”) from hello import *

Main Module What about interactive session? Is it a module?? Yes: __main__ Modules executed on import. In many modules you will see: if __name__ == "__main__": main()

Python Classes: Attributes can be added/deleted dynamically (no declaring) Keyword self (like this) passed into all class methods Special methods __init__ (Constructor) __del__ (Destructor)

class Student: def __init__(self, name, hours, qpts): self.name = name self.hours = hours self.qpts = qpts def getName(self): return self.name def gpa(self): return self.qpts/self.hours

from student import * aStudent = Student(“Mary Adams”, 127, 228) gpa = aStudent.gpa() print gpa s = Student(…) calls the constructor. To call the destructor: s = 0

Creating a list the old way… >>> squares = [] >>> for x in range(10): squares.append(x**2) >>> squares [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

List Comprehensions >>> squares = [] >>> for x in range(10): squares.append(x**2) >>> squares [0, 1, 4, 9, 16, 25, 36, 49, 64, 81] >>>squares = [x**2 for x in range(10)]

List Comprehensions >>> vec = [-4, -2, 0, 2, 4] >>> [x*2 for x in vec]

List Comprehensions >>> vec = [-4, -2, 0, 2, 4] >>> [x*2 for x in vec] [-8, -4, 0, 4, 8]

>>> vec = [-4, -2, 0, 2, 4] >>> [x for x in vec if x >= 0]

>>> vec = [-4, -2, 0, 2, 4] >>> [x for x in vec if x >= 0] [0, 2, 4]

Can do embedded loops too >>> [(x, y) for x in [1,2,3] for y in [3,1,4] if x != y]

Can do embedded loops too >>> [(x, y) for x in [1,2,3] for y in [3,1,4] if x != y [(1, 3), (1, 4), (2, 3), (2, 1), (2, 4), (3, 1), (3, 4)]