January 24, 2006And Now For Something Completely Different 1 “And Now For Something Completely Different” A Quick Tutorial of the Python Programming Language.

Slides:



Advertisements
Similar presentations
Container Types in Python
Advertisements

CHAPTER 4 AND 5 Section06: Sequences. General Description "Normal" variables x = 19  The name "x" is associated with a single value Sequence variables:
CS 100: Roadmap to Computing Fall 2014 Lecture 0.
String and Lists Dr. Benito Mendoza. 2 Outline What is a string String operations Traversing strings String slices What is a list Traversing a list List.
I210 review Fall 2011, IUB. Python is High-level programming –High-level versus machine language Interpreted Language –Interpreted versus compiled 2.
DICTIONARIES. The Compound Sequence Data Types All of the compound data types we have studies in detail so far – strings – lists – Tuples They are sequence.
An Introduction to Python – Part II Dr. Nancy Warter-Perez.
Structured programming
Introduction to Python
Javascript II Expressions and Data Types. 2 JavaScript Review programs executed by the web browser programs embedded in a web page using the script element.
JavaScript, Third Edition
JaySummet IPRE Python Review 2. 2 Outline Compound Data Types: Strings, Tuples, Lists & Dictionaries Immutable types: Strings Tuples Accessing.
CMPT 120 Lists and Strings Summer 2012 Instructor: Hassan Khosravi.
The Ruby Programming Language
Introduction to Python Lecture 1. CS 484 – Artificial Intelligence2 Big Picture Language Features Python is interpreted Not compiled Object-oriented language.
CS 100: Roadmap to Computing Fall 2014 Lecture 01.
Introduction to Python
October 4, 2005ICP: Chapter 4: For Loops, Strings, and Tuples 1 Introduction to Computer Programming Chapter 4: For Loops, Strings, and Tuples Michael.
Introduction to Python Basics of the Language. Install Python Find the most recent distribution for your computer at:
Copyright © 2012 Pearson Education, Inc. Publishing as Pearson Addison-Wesley C H A P T E R 9 More About Strings.
Handling Lists F. Duveau 16/12/11 Chapter 9.2. Objectives of the session: Tools: Everything will be done with the Python interpreter in the Terminal Learning.
1 Python CIS*2450 Advanced Programming Concepts Material for this lecture was developed by Dr. D. Calvert.
Introduction to Python I CSE-391: Artificial Intelligence University of Pennsylvania Matt Huenerfauth January 2005.
Strings The Basics. Strings can refer to a string variable as one variable or as many different components (characters) string values are delimited by.
Computer Science 101 Introduction to Programming.
Fall Week 4 CSCI-141 Scott C. Johnson.  Computers can process text as well as numbers ◦ Example: a news agency might want to find all the articles.
Built-in Data Structures in Python An Introduction.
Data TypestMyn1 Data Types The type of a variable is not set by the programmer; rather, it is decided at runtime by PHP depending on the context in which.
Introducing Python CS 4320, SPRING Resources We will be following the Python tutorialPython tutorial These notes will cover the following sections.
10. Python - Lists The list is a most versatile datatype available in Python, which can be written as a list of comma-separated values (items) between.
Introducing Python CS 4320, SPRING Lexical Structure Two aspects of Python syntax may be challenging to Java programmers Indenting ◦Indenting is.
Python Conditionals chapter 5
Python I Some material adapted from Upenn cmpe391 slides and other sources.
Python Primer 1: Types and Operators © 2013 Goodrich, Tamassia, Goldwasser1Python Primer.
Jim Havrilla. Invoking Python Just type “python –m script.py [arg]” or “python –c command [arg]” To exit, quit() or Control-D is used To just use the.
COMPE 111 Introduction to Computer Engineering Programming in Python Atılım University
A Tutorial on the Python Programming Language. Overview Running Python and Output Data Types Input and File I/O Control Flow Functions.
CS190/295 Programming in Python for Life Sciences: Lecture 6 Instructor: Xiaohui Xie University of California, Irvine.
I NTRODUCTION TO PYTHON - GETTING STARTED ( CONT )
12 February 2016Birkbeck College, U. London1 Introduction to Programming Lecturer: Steve Maybank Department of Computer Science and Information Systems.
Expressions and Data Types Professor Robin Burke.
Strings CSE 1310 – Introduction to Computers and Programming Alexandra Stefan University of Texas at Arlington 1.
Strings CSE 1310 – Introduction to Computers and Programming Alexandra Stefan University of Texas at Arlington 1.
Python Arithmetic Operators OperatorOperationDescription +AdditionAdd values on either side of the operator -SubtractionSubtract right hand operand from.
Python Basics 본 자료는 다음의 웹 사이트를 정리 한 내용이니 참조 바랍니다. ythonBasics.
Winter 2016CISC101 - Prof. McLeod1 CISC101 Reminders Quiz 3 next week. See next slide. Both versions of assignment 3 are posted. Due today.
Quiz 3 Topics Functions – using and writing. Lists: –operators used with lists. –keywords used with lists. –BIF’s used with lists. –list methods. Loops.
String and Lists Dr. José M. Reyes Álamo. 2 Outline What is a string String operations Traversing strings String slices What is a list Traversing a list.
PYTHON PROGRAMMING. WHAT IS PYTHON?  Python is a high-level language.  Interpreted  Object oriented (use of classes and objects)  Standard library.
Indentations makes the scope/block Function definition def print_message (): print “hello” Function usages print_message () hubo.move ()// hubo is a class.
ENGINEERING 1D04 Tutorial 2. What we’re doing today More on Strings String input Strings as lists String indexing Slice Concatenation and Repetition len()
String and Lists Dr. José M. Reyes Álamo.
G. Pullaiah College of Engineering and Technology
CSc 120 Introduction to Computer Programing II Adapted from slides by
Introduction to Python
CS 100: Roadmap to Computing
CS-104 Final Exam Review Victor Norman.
Python Data Structures & Algorithms in Python
Arithmetic operations, decisions and looping
An Introduction to Python
String and Lists Dr. José M. Reyes Álamo.
Python Tutorial for C Programmer Boontee Kruatrachue Kritawan Siriboon
Python I Some material adapted from Upenn cmpe391 slides and other sources.
Python Primer 1: Types and Operators
(more) Python.
CHAPTER 3: String And Numeric Data In Python
Introduction to Computer Science
COMPUTER PROGRAMMING SKILLS
Python Review
Class code for pythonroom.com cchsp2cs
Presentation transcript:

January 24, 2006And Now For Something Completely Different 1 “And Now For Something Completely Different” A Quick Tutorial of the Python Programming Language Michael Scherger Department of Computer Science Kent State University

January 24, 2006And Now For Something Completely Different 2 Contents Python Resources Python Basics and Language Elements Statements and Control Structures Input, Output, and File Access Functions Classes and Objects

January 24, 2006And Now For Something Completely Different 3 Python Resources

January 24, 2006And Now For Something Completely Different 4 Python Resources Python Web Site: Check out the tutorial at: Download current stable version for your PC

January 24, 2006And Now For Something Completely Different 5 Running Python PC –c:\>python –Use Python GUI called ‘IDLE’ Linux % python Mac version available

January 24, 2006And Now For Something Completely Different 6 Running Python

January 24, 2006And Now For Something Completely Different 7 Running Python

January 24, 2006And Now For Something Completely Different 8 Python Basics and Language Elements

January 24, 2006And Now For Something Completely Different 9 Numbers Integers –Decimal At least 32 bit –Octal and hexadecimal Long integers –Limited by memory size –Trailing “L” Floating point Complex –Use “j” instead of “i” Boolean >>> >>> >>> 1+1e0 2.0 >>> >>> L >>> L >>> L >>> >>> >>> >>> 0x11 17 >>>

January 24, 2006And Now For Something Completely Different 10 Variables Variables do not have types You do not declare variables –They appear when you assign them –They disappear when you do not use them anymore >>> x = >>> x 2 >>> x = >>> x 2.0 >>> >>> y Traceback (most recent call last): File " ", line 1, in -toplevel- y NameError: name 'y' is not defined >>> y = None >>> y >>> y == None True >>> del y >>> y Traceback (most recent call last): File " ", line 1, in -toplevel- y NameError: name 'y' is not defined >>>

January 24, 2006And Now For Something Completely Different 11 Lists Python’s array like object is a list –Uses [ ] –Subscripted like arrays in C (zero based) –Mutable –Use len(L) to get the length of the list >>> z = [4, 5, 6] >>> z[1] 5 >>> z[1] = 7 >>> z [4, 7, 6] >>> len( z ) 3 >>>

January 24, 2006And Now For Something Completely Different 12 Lists Indexing –Uses bracket notation –Indexes start at 0…can have a negative index name = [“Cleese”, “John”]# example of strings in a list print name[1], name[0] # prints “John Cleese” name[0] = “Smith” x=[[1,2,3],[y,z],[[[]]]]# example of lists in a list “A”“B”“C”“D”“E”

January 24, 2006And Now For Something Completely Different 13 Lists Slicing is similar to indexing except you indicate both the start and stop index separated by a colon x = ["spam1","spam2","spam3","spam4","spam5","eggs","and","spam6"] print x[5:7] # Prints the list ["eggs","and"] “A”“B”“C”“D”“E”

January 24, 2006And Now For Something Completely Different 14 List Methods append()add an element to the end of the list pop()remove an element from the end of a list insert()add an element anywhere in the list + and *list concatenation and replication And a whole bunch more…look them up!

January 24, 2006And Now For Something Completely Different 15 Strings A string is a sequence of characters between quotes; either “ “ or ‘ ‘ –There is no character data type in Python…only string Strings are not arrays of characters as in C/C++! –Use subscript notation to read individual characters as a string –Strings are immutable –Use len(S) to get the length of the string >>> x = "abc" >>> x[0] 'a' >>> len(x) 3 >>> x[0] = 'd' Traceback (most recent call last): File " ", line 1, in -toplevel- x[0] = 'd' TypeError: object doesn't support item assignment >>>

January 24, 2006And Now For Something Completely Different 16 Converting Values String values can be converted to integers using the int() function String values can be converted to floating points using the float() function Ints and floats can be converted to string values str() function Example x = int( “10” ) y = float( “10”) yy = float (10) Z = str( )

January 24, 2006And Now For Something Completely Different 17 String Methods upper()Returns the uppercase version of the string lower()Returns the lowercase version of the string swapcase() Returns a new string where the case of each letter is switched capitalize()Returns a new string with the first letter capitalized and the remaining letters are in lowercase title() Returns a new string with the first letter of each word capitalized and all other letters are in lower case strip() Returns a new string with leading and trailing white space removed. replace( old, new, [,max])Returns a new string where occurrences of the string “old” are replaced by “new” up to “max” number of times

January 24, 2006And Now For Something Completely Different 18 Tuples Tuples are like lists –Immutable –Use ( ) notation instead of [ ]’s for creation –Uses [ ] notation for indexing and slicing >>> x = (1, "Mike", 2, Laurie", 3, "Sarah") >>> x (1, 'Mike', 2, 'Laurie', 3, 'Sarah') >>> x[1] = 'Michael' Traceback (most recent call last): File " ", line 1, in - toplevel- x[1] = 'Michael' TypeError: object doesn't support item assignment >>>

January 24, 2006And Now For Something Completely Different 19 Dictionaries Dictionaries are unordered lists –Associative array/list or table or map –List of “key/value” pairs –Use “key” to look up the element or value person = {'first name': "Robin", 'last name’ : "Hood", 'occupation': "Scoundrel" } person[‘last name’] = “of Locksley”

January 24, 2006And Now For Something Completely Different 20 Dictionary Methods keys()returns a list of keys values()returns a list of values items()returns a list of key value pairs has_key()tests if a key exists And a whole bunch more…look them up!

January 24, 2006And Now For Something Completely Different 21 Assignments Assignment uses = Equality uses == Not Equal uses != or <> x, y, z = 1, 2, 3 first, second = second, first a = b = 123

January 24, 2006And Now For Something Completely Different 22 Other Assignment Operators Augmented assignment operators –A combination of assignment and a mathematical operation *=x *= 5x = x * 5 /=x /= 5x = x / 5 %=x %=5x = x % 5 +=x += 5x = x + 5 -=x -= 5x = x - 5

January 24, 2006And Now For Something Completely Different 23 Logical Values Python 2.3 has a Boolean type –Prior versions do not –False is zero or empty –True is not False (non-zero or not empty) –And, Or, Not are short- circuited –Can do lexicographic comparison of sequences (lists, strings, tuples) 1 < 2# True 1 > 2# False [1,2] < [3,4]# True [1,2] == [1,2]# True “ab” == “a” + “b”# True (1,2) == [1,2]# False not []# True not [1,2,3]# False not ‘’# True not ‘ab’# False

January 24, 2006And Now For Something Completely Different 24 Statements and Control Structures

January 24, 2006And Now For Something Completely Different 25 Blocks Blocks are indicated using indentation only –No BEGIN/END or { } if x 10 and x < 20): print “The value is OK.” if x < 5 or 10 < x < 20: print “The value is OK.”

January 24, 2006And Now For Something Completely Different 26 If-Elif-Else if color == Green: do_green_function() elif color == Blue: do_blue_function() elif color == Red: do_red_function() else: report_error()

January 24, 2006And Now For Something Completely Different 27 While Loops Example of a while loops x = 10 while x >= 0: print “x is still negative.” x = x-1

January 24, 2006And Now For Something Completely Different 28 For Loops To make an “ordinary” for loop use the built-in function range() # Print out the values from 0 # to 99 inclusive for value in range(100): print value

January 24, 2006And Now For Something Completely Different 29 For Loops More examples of for loops # print values in a list for value in [1, 2, 3, 4, 5, 4, 3, 2, 1]: print value # print 10 thru 19 for value in range(10,20): print value # print for value in range(10, 20, 2): print value

January 24, 2006And Now For Something Completely Different 30 Input, Output, and File Access

January 24, 2006And Now For Something Completely Different 31 Getting User Input The raw_input function returns a string. –Be careful! 10 is not the same as “10” Other functions convert strings to integers and vice versa. Example: Personal Greeter

January 24, 2006And Now For Something Completely Different 32 A Tiny Algorithm Prompt user for a number Print out the square of the number x = input( “Please enter a number: “) print “The square of that number is”, x * x Could also use… x = raw_input( “Please enter a number: “) x = int(x) print “The square of that number is”, x * x

January 24, 2006And Now For Something Completely Different 33 File Input / Output Example filespec = open( “somefile”, “r” ) s = filespec.readline() # read one line s = filespec.readlines() # read all lines filespec.close()

January 24, 2006And Now For Something Completely Different 34 File Input / Output Example filespec = open( “somefile”, “w” ) filespec.writeline(s) # write one string filespec.writelines(l) # write string list filespec.close()

January 24, 2006And Now For Something Completely Different 35 Functions

January 24, 2006And Now For Something Completely Different 36 Functions Use the keyword def –Passing parameters –Named arguments –Default values –Variable scoping def square(x): return x*x print square(2)# prints out 4

January 24, 2006And Now For Something Completely Different 37 Functions When you pass a parameter to a function, you bind the parameter to the value Creates a new reference def change(some_list): some_list[1] = 4 x = [1,2,3] change(x) print x # Prints out [1,4,3]

January 24, 2006And Now For Something Completely Different 38 Functions Another example def nochange(x): x = 0 y = 1 nochange(y) print y # Prints out 1 Example: Balanced Parentheses and Fibonocci NumbersExample: Balanced Parentheses and Fibonocci Numbers

January 24, 2006And Now For Something Completely Different 39 Functions Example >>>def sumdif(a, b): return a+b, a-b >>>sumdif( 5, 7 ) (12,2) >>>

January 24, 2006And Now For Something Completely Different 40 Putting It All Together Write a Python version of wc (word count) –Writes the counts of the number of characters, words, and lines in a file Algorithm –open the file –count the characters, words, and lines –write out the counts –close the file Example: wc –% python wc.py somefile.ext

January 24, 2006And Now For Something Completely Different 41 Classes and Objects

January 24, 2006And Now For Something Completely Different 42 Classes and Objects class Basket: def __init__(self, contents=None): self.contents = contents or [] def add(self, element): self.contents.append(element) def print_me(self): result = “” for element in self.contents: result = result + “ “ + `element` print “Contains: “ + result

January 24, 2006And Now For Something Completely Different 43 Classes and Objects All methods (functions in an object) received an additional argument at the start of the argument list containing the object itself. (Called self which is customary) Methods are called like this: object.method( arg1, arg2) Some method names, like __init__ (two underscores on each side), are predefined and mean special things (constructor) Some arguments are optional and given and default value Short circuit evaluation and assignment Backquotes convert an object to its string representation Addition sign (+) is used for string concatenation

January 24, 2006And Now For Something Completely Different 44 Classes and Objects Instead of short circuit to assign contents…could have written the statement like this if contents: self.contents = contents else: self.contents = [] def __init__(self,contents=[]) self.contents = contents[:]

January 24, 2006And Now For Something Completely Different 45 Classes and Objects To create an instance of a class (object) a = Basket() b = Basket( [“apple”, “lemon”]) b.add( “orange” ) b.print_me()

January 24, 2006And Now For Something Completely Different 46 Classes and Objects Convert object to string –Use the __str__ method def __str__(self) result = “” for element in self.contents: result = result + “ “ + `element` return “Contains: “ + “ “ + result

January 24, 2006And Now For Something Completely Different 47 Classes and Objects Example: Basket Class >>> b = Basket() >>> b >>> print b Contains: >>> b.add( "Foo" ) >>> print b Contains: 'Foo' >>> b.add (["Foo", "Bar"]) >>> b.print_me() Contains: 'Foo' ['Foo', 'Bar'] >>> b.add ((1,2,3)) >>> print b Contains: 'Foo' ['Foo', 'Bar'] (1, 2, 3) >>>