1 Python Control of Flow and Defining Classes LING 5200 Computational Corpus Linguistics Martha Palmer.

Slides:



Advertisements
Similar presentations
Programming with App Inventor Computing Institute for K-12 Teachers Summer 2012 Workshop.
Advertisements

CATHERINE AND ANNIE Python: Part 3. Intro to Loops Do you remember in Alice when you could use a loop to make a character perform an action multiple times?
Python Objects and Classes
Computer Science 1620 Loops.
Road Map Introduction to object oriented programming. Classes
VBA Modules, Functions, Variables, and Constants
1 Programming for Engineers in Python Autumn Lecture 5: Object Oriented Programming.
Python (yay!) November 16, Unit 7. Recap We can store values in variables using an assignment statement >>>x = We can get input from the user using.
Python November 18, Unit 7. So Far We can get user input We can create variables We can convert values from one type to another using functions We can.
Terms and Rules Professor Evan Korth New York University (All rights reserved)
Introduction to Python II CIS 391: Artificial Intelligence Fall, 2008.
Python 3 Some material adapted from Upenn cis391 slides and other sources.
Introduction to Python II CSE-391: Artificial Intelligence University of Pennsylvania Matt Huenerfauth January 2005.
Guide to Programming with Python
Python 3 Some material adapted from Upenn cis391 slides and other sources.
Loops and Iteration Chapter 5 Python for Informatics: Exploring Information
Python Control of Flow.
Java Unit 9: Arrays Declaring and Processing Arrays.
Week 4-5 Java Programming. Loops What is a loop? Loop is code that repeats itself a certain number of times There are two types of loops: For loop Used.
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.
Introduction to Python III CSE-391: Artificial Intelligence University of Pennsylvania Matt Huenerfauth January 2005.
ASP.NET Programming with C# and SQL Server First Edition Chapter 3 Using Functions, Methods, and Control Structures.
COMPUTER PROGRAMMING. Control Structures A program is usually not limited to a linear sequence of instructions. During its process it may repeat code.
CPS120 Introduction to Computer Science Iteration (Looping)
Collecting Things Together - Lists 1. We’ve seen that Python can store things in memory and retrieve, using names. Sometime we want to store a bunch of.
CPS120: Introduction to Computer Science Decision Making in Programs.
Saeed Ghanbartehrani Summer 2015 Lecture Notes #5: Programming Structures IE 212: Computational Methods for Industrial Engineering.
Python uses boolean variables to evaluate conditions. The boolean values True and False are returned when an expression is compared or evaluated.
Python Functions.
A Third Look At ML Chapter NineModern Programming Languages, 2nd ed.1.
AP Computer Science edition Review 1 ArrayListsWhile loopsString MethodsMethodsErrors
Introduction to Python III CIS 391: Artificial Intelligence Fall, 2008.
Python Primer 1: Types and Operators © 2013 Goodrich, Tamassia, Goldwasser1Python Primer.
CSC 212 Object-Oriented Programming and Java Part 2.
More Python!. Lists, Variables with more than one value Variables can point to more than one value at a time. The simplest way to do this is with a List.
1 Printing in Python Every program needs to do some output This is usually to the screen (shell window) Later we’ll see graphics windows and external files.
Programming Fundamentals. Topics to be covered Today Recursion Inline Functions Scope and Storage Class A simple class Constructor Destructor.
Midterm Review Important control structures Functions Loops Conditionals Important things to review Binary Boolean operators (and, or, not) Libraries (import.
Written by: Dr. JJ Shepherd
Controlling Program Flow with Decision Structures.
CS190/295 Programming in Python for Life Sciences: Lecture 6 Instructor: Xiaohui Xie University of California, Irvine.
Chapter 1 C++ Basics Review (Section 1.4). Classes Defines the organization of a data user-defined type. Members can be  Data  Functions/Methods Information.
Today… Python Keywords. Iteration (or “Loops”!) Winter 2016CISC101 - Prof. McLeod1.
4 - Conditional Control Structures CHAPTER 4. Introduction A Program is usually not limited to a linear sequence of instructions. In real life, a programme.
CMSC201 Computer Science I for Majors Lecture 20 – Classes and Modules Prof. Katherine Gibson Prof. Jeremy Dixon Based on slides from the.
Lecture III Syntax ● Statements ● Output ● Variables ● Conditions ● Loops ● List Comprehension ● Function Calls ● Modules.
Python 3 Some material adapted from Upenn cis391 slides and other sources.
Object Oriented Programming in Python: Defining Classes
CS170 – Week 1 Lecture 3: Foundation Ismail abumuhfouz.
CS-104 Final Exam Review Victor Norman.
Chapter 3: Using Methods, Classes, and Objects
Creating and Deleting Instances Access to Attributes and Methods
Sentinel logic, flags, break Taken from notes by Dr. Neil Moore
Procedural Abstraction Object-Oriented Code
Methods The real power of an object-oriented programming language takes place when you start to manipulate objects. A method defines an action that allows.
Object Oriented Programming in Python Session -3
Python Classes By Craig Pennell.
Chapter 3 Introduction to Classes, Objects Methods and Strings
Sentinel logic, flags, break Taken from notes by Dr. Neil Moore
CMSC201 Computer Science I for Majors Lecture 16 – Classes and Modules
CS190/295 Programming in Python for Life Sciences: Lecture 6
CMSC 202 Java Primer 2.
Object Oriented Programming in java
CISC124 Labs start this week in JEFF 155. Fall 2018
Python 3 Some material adapted from Upenn cis391 slides and other sources.
CISC101 Reminders All assignments are now posted.
Classes, Objects and Methods
Review of Previous Lesson
SPL – PS3 C++ Classes.
Presentation transcript:

1 Python Control of Flow and Defining Classes LING 5200 Computational Corpus Linguistics Martha Palmer

2 For Loops

LING 5200, 2006 BASED on Matt Huenerfauth’s Python Slides 3 For Loops 1 A for-loop steps through each of the items in a list, tuple, string, or any other type of object which the language considers an “iterator.” for in : When is a list or a tuple, then the loop steps through each element of the container. When is a string, then the loop steps through each character of the string. for someChar in “Hello World”: print someChar

LING 5200, 2006 BASED on Matt Huenerfauth’s Python Slides 4 For Loops 2 The part of the for loop can also be more complex than a single variable name.  When the elements of a container are also containers, then the part of the for loop can match the structure of the elements.  This multiple assignment can make it easier to access the individual parts of each element. for (x, y) in [(a,1), (b,2), (c,3), (d,4)]: print x

LING 5200, 2006 BASED on Matt Huenerfauth’s Python Slides 5 For loops and range() function Since we often want to range a variable over some numbers, we can use the range() function which gives us a list of numbers from 0 up to but not including the number we pass to it. range(5) returns [0,1,2,3,4] So we could say: for x in range(5): print x

LING 5200, 2006 BASED on Matt Huenerfauth’s Python Slides 6 Control of Flow There are several Python expressions that control the flow of a program. All of them make use of Boolean conditional tests.  If Statements  While Loops  Assert Statements

LING 5200, 2006 BASED on Matt Huenerfauth’s Python Slides 7 If Statements if x == 3: print “X equals 3.” elif x == 2: print “X equals 2.” else: print “X equals something else.” print “This is outside the ‘if’.” Be careful! The keyword ‘if’ is also used in the syntax of filtered list comprehensions.

LING 5200, 2006 BASED on Matt Huenerfauth’s Python Slides 8 If Statements – Another Ex. x = ‘killer rabbit’ if x == ‘roger’: print “how’s jessica?” elif x == ‘bugs’: print “What’s up, doc?” else: print “Run away! Run away!” Run away!

LING 5200, 2006 BASED on Matt Huenerfauth’s Python Slides 9 While Loops x = 3 while x < 10: x = x + 1 print “Still in the loop.” print “Outside of the loop.”

LING 5200, 2006 BASED on Matt Huenerfauth’s Python Slides 10 While Loops, more examples While 1: print “Type Ctrl-C to stop me!” x = ‘spam’ While x: print x x = x[1:] ‘spam’ ‘pam’ ‘am’ ‘m’

LING 5200, 2006 BASED on Matt Huenerfauth’s Python Slides 11 Break and Continue You can use the keyword break inside a loop to leave the while loop entirely. You can use the keyword continue inside a loop to stop processing the current iteration of the loop and to immediately go on to the next one.

LING 5200, 2006 BASED on Matt Huenerfauth’s Python Slides 12 While Loop with Break while 1: name = raw_input(‘Enter name:’) if name == ‘stop’: break age = raw_input(‘Enter age:’) print ‘Hello’, name, ‘=>’,\ int(age)**2

LING 5200, 2006 BASED on Matt Huenerfauth’s Python Slides 13 While Loop with Break, cont. Enter name: mel Enter age: 20 Hello mel => 400 Enter name: bob Enter age: 30 Hello, bob => 900 Enter name: stop

LING 5200, 2006 BASED on Matt Huenerfauth’s Python Slides 14 While Loop with Continue x = 10 while x: x = x-1 if x % 2 != 0: continue#Odd? Skip print print x

LING 5200, 2006 BASED on Matt Huenerfauth’s Python Slides 15 Assert An assert statement will check to make sure that something is true during the course of a program.  If the condition if false, the program stops. assert(number_of_players < 5) if number_of_players >= 5: STOP

16 Logical Expressions

LING 5200, 2006 BASED on Matt Huenerfauth’s Python Slides 17 True and False True and False are constants in Python.  Generally, True equals 1 and False equals 0. Other values equivalent to True and False:  False: zero, None, empty container or object  True: non-zero numbers, non-empty objects. Comparison operators: ==, !=, <, <=, etc.  X and Y have same value: X == Y  X and Y are two names that point to the same memory reference: X is Y

LING 5200, 2006 BASED on Matt Huenerfauth’s Python Slides 18 Boolean Logic Expressions You can also combine Boolean expressions.  True if a is true and b is true: a and b  True if a is true or b is true: a or b  True if a is false: not a Use parentheses as needed to disambiguate complex Boolean expressions.

LING 5200, 2006 BASED on Matt Huenerfauth’s Python Slides 19 Special Properties of And and Or Actually ‘and’ and ‘or’ don’t return True or False. They return the value of one of their sub-expressions (which may be a non-Boolean value). X and Y and Z  If all are true, returns value of Z.  Otherwise, returns value of first false sub- expression. X or Y or Z  If all are false, returns value of Z.  Otherwise, returns value of first true sub- expression.

LING 5200, 2006 BASED on Matt Huenerfauth’s Python Slides 20 The “and-or” Trick There is a common trick used by Python programmers to implement a simple conditional using ‘and’ and ‘or.’ result = test and expr1 or expr2  When test is True, result is assigned expr1.  When test is False, result is assigned expr2.  Works like (test ? expr1 : expr2) expression of C++. But you must be certain that the value of expr1 is never False or else the trick won’t work. I wouldn’t use this trick yourself, but you should be able to understand it if you see it

21 Object Oriented Programming in Python

LING 5200, 2006 BASED on Matt Huenerfauth’s Python Slides 22 It’s all objects… Everything in Python is really an object.  We’ve seen hints of this already… “hello”.upper() list3.append(‘a’) dict2.keys()  You can also design your own objects… in addition to these built-in data-types. In fact, programming in Python is typically done in an object oriented fashion.

23 Defining Classes

LING 5200, 2006 BASED on Matt Huenerfauth’s Python Slides 24 Defining a Class A class is a special data type which defines how to build a certain kind of object.  The ‘class’ also stores some data items that are shared by all the instances of this class.  ‘Instances’ are objects that are created which follow the definition given inside of the class. Python doesn’t use separate class interface definitions as in some languages. You just define the class and then use it.

LING 5200, 2006 BASED on Matt Huenerfauth’s Python Slides 25 Methods in Classes You can define a method in a class by including function definitions within the scope of the class block.  Note that there is a special first argument self in all of the method definitions.  Note that there is usually a special method called __init__ in most classes.  We’ll talk about both later…

LING 5200, 2006 BASED on Matt Huenerfauth’s Python Slides 26 Definition of student class student: “““A class representing a student.””” def __init__(self,n,a): self.full_name = n self.age = a def get_age(self): return self.age

27 Creating and Deleting Instances

LING 5200, 2006 BASED on Matt Huenerfauth’s Python Slides 28 Instantiating Objects There is no “new” keyword as in Java. You merely use the class name with () notation and assign the result to a variable. b = student(“Bob Smith”, 21) The arguments you pass to the class name are actually given to its.__init__() method.

LING 5200, 2006 BASED on Matt Huenerfauth’s Python Slides 29 Constructor: __init__ __init__ acts like a constructor for your class.  When you create a new instance of a class, this method is invoked. Usually does some initialization work.  The arguments you list when instantiating an instance of the class are passed along to the __init__ method. b = student(“Bob”, 21) So, the __init__ method is passed “Bob” and 21.

LING 5200, 2006 BASED on Matt Huenerfauth’s Python Slides 30 Constructor: __init__ Your __init__ method can take any number of arguments.  Just like other functions or methods, the arguments can be defined with default values, making them optional to the caller. However, the first argument self in the definition of __init__ is special…

LING 5200, 2006 BASED on Matt Huenerfauth’s Python Slides 31 Self The first argument of every method is a reference to the current instance of the class.  By convention, we name this argument self. In __init__, self refers to the object currently being created; so, in other class methods, it refers to the instance whose method was called.  Similar to the keyword ‘this’ in Java or C++.  But Python uses ‘self’ more often than Java uses ‘this.’

LING 5200, 2006 BASED on Matt Huenerfauth’s Python Slides 32 Self Although you must specify self explicitly when defining the method, you don’t include it when calling the method. Python passes it for you automatically. Defining a method:Calling a method: (this code inside a class definition.) def set_age(self, num):>>> x.set_age(23) self.age = num

LING 5200, 2006 BASED on Matt Huenerfauth’s Python Slides 33 No Need to “free” When you are done with an object, you don’t have to delete or free it explicitly.  Python has automatic garbage collection.  Python will automatically detect when all of the references to a piece of memory have gone out of scope. Automatically frees that memory.  Generally works well, few memory leaks.  There’s also no “destructor” method for classes.

34 Access to Attributes and Methods

LING 5200, 2006 BASED on Matt Huenerfauth’s Python Slides 35 Definition of student class student: “““A class representing a student.””” def __init__(self,n,a): self.full_name = n self.age = a def get_age(self): return self.age

LING 5200, 2006 BASED on Matt Huenerfauth’s Python Slides 36 Traditional Syntax for Access >>> f = student (“Bob Smith”, 23) >>> f.full_name # Access an attribute. “Bob Smith” >>> f.get_age() # Access a method. 23

LING 5200, 2006 BASED on Matt Huenerfauth’s Python Slides 37 Accessing unknown members What if you don’t know the name of the attribute or method of a class that you want to access until run time… Is there a way to take a string containing the name of an attribute or method of a class and get a reference to it (so you can use it)?

LING 5200, 2006 BASED on Matt Huenerfauth’s Python Slides 38 getattr(object_instance, string) >>> f = student(“Bob Smith”, 23) >>> getattr(f, “full_name”) “Bob Smith” >>> getattr(f, “get_age”) >>> getattr(f, “get_age”)() # We can call this. 23 >>> getattr(f, “get_birthday”) # Raises AttributeError – No method exists.

LING 5200, 2006 BASED on Matt Huenerfauth’s Python Slides 39 hasattr(object_instance,string) >>> f = student(“Bob Smith”, 23) >>> hasattr(f, “full_name”) True >>> hasattr(f, “get_age”) True >>> hasattr(f, “get_birthday”) False

40 Attributes

LING 5200, 2006 BASED on Matt Huenerfauth’s Python Slides 41 Two Kinds of Attributes The non-method data stored by objects are called attributes. There’s two kinds:  Data attribute: Variable owned by a particular instance of a class. Each instance can have its own different value for it. These are the most common kind of attribute.  Class attributes: Owned by the class as a whole. All instances of the class share the same value for it. Called “static” variables in some languages. Good for class-wide constants or for building counter of how many instances of the class have been made.

LING 5200, 2006 BASED on Matt Huenerfauth’s Python Slides 42 Data Attributes You create and initialize a data attribute inside of the __init__() method.  Remember assignment is how we create variables in Python; so, assigning to a name creates the attribute.  Inside the class, you refer to data attributes using self – for example, self.full_name class teacher: “A class representing teachers.” def __init__(self,n): self.full_name = n def print_name(self): print self.full_name

LING 5200, 2006 BASED on Matt Huenerfauth’s Python Slides 43 Class Attributes All instances of a class share one copy of a class attribute, so when any of the instances change it, then the value is changed for all of them. We define class attributes outside of any method. Since there is one of these attributes per class and not one per instance, we use a different notation:  We access them using self.__class__.name notation. class sample:>>> a = sample() x = 23 >>> a.increment() def increment(self): >>> a.__class__.x self.__class__.x += 124

LING 5200, 2006 BASED on Matt Huenerfauth’s Python Slides 44 Data vs. Class Attributes class counter: overall_total = 0 # class attribute def __init__(self): self.my_total = 0 # data attribute def increment(self): counter.overall_total = \ counter.overall_total + 1 self.my_total = \ self.my_total + 1 >>> a = counter() >>> b = counter() >>> a.increment() >>> b.increment() >>> b.increment() >>> a.my_total 1 >>> a.__class__.overall_total 3 >>> b.my_total 2 >>> b.__class__.overall_total 3