Writing Solid Code Introduction to Python. Program 1 python -c "print 'Hello World' “ python -c "import time; print time.asctime()“ Start an interactive.

Slides:



Advertisements
Similar presentations
Chapter 6 Lists and Dictionaries CSC1310 Fall 2009.
Advertisements

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.
What is a scripting language? What is Python?
Introduction to Python
Chapter 2 Writing Simple Programs
CSC 9010: Natural Language Processing
Python Control of Flow.
Python.
INLS 560 – V ARIABLES, E XPRESSIONS, AND S TATEMENTS Instructor: Jason Carter.
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.
Introduction to Python Guido van Rossum Director of PythonLabs at Zope Corporation
Programming for Linguists An Introduction to Python 24/11/2011.
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.
Copyright © 2012 Pearson Education, Inc. Publishing as Pearson Addison-Wesley C H A P T E R 2 Input, Processing, and Output.
CPTR 124 Review for Test 1. Development Tools Editor Similar to a word processor Allows programmer to compose/save/edit source code Compiler/interpreter.
H3D API Training  Part 3.1: Python – Quick overview.
Introduction to Python September 26, /10/ Bioinformatics Languages Low-level, compiled languages: C, C++, Java… Pros: performance Cons:
Introduction to Python I CSE-391: Artificial Intelligence University of Pennsylvania Matt Huenerfauth January 2005.
Python Lists and Such CS 4320, SPRING List Functions len(s) is the length of list s s + t is the concatenation of lists s and t s.append(x) adds.
If statements while loop for loop
Built-in Data Structures in Python An Introduction.
Getting Started with Python: Constructs and Pitfalls Sean Deitz Advanced Programming Seminar September 13, 2013.
Introducing Python CS 4320, SPRING Resources We will be following the Python tutorialPython tutorial These notes will cover the following sections.
C463 / B551 Artificial Intelligence Dana Vrajitoru Python.
Python uses boolean variables to evaluate conditions. The boolean values True and False are returned when an expression is compared or evaluated.
Exam 1 Review Instructor – Gokcen Cilingir Cpt S 111, Sections 6-7 (Sept 19, 2011) Washington State University.
Introducing Python CS 4320, SPRING Lexical Structure Two aspects of Python syntax may be challenging to Java programmers Indenting ◦Indenting is.
Copyright © 2012 Pearson Education, Inc. Publishing as Pearson Addison-Wesley C H A P T E R 8 Lists and Tuples.
6 Strings and Tuples © 2010 David A Watt, University of Glasgow Accelerated Programming 2 Part I: Python Programming 1.
Python I Some material adapted from Upenn cmpe391 slides and other sources.
CS105 Computer Programming PYTHON (based on CS 11 Python track: lecture 1, CALTECH)
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.
By Austin Laudenslager AN INTRODUCTION TO PYTHON.
Last Week Modules Save functions to a file, e.g., filename.py The file filename.py is a module We can use the functions in filename.py by importing it.
Python Let’s get started!.
Python Mini-Course University of Oklahoma Department of Psychology Day 3 – Lesson 11 Using strings and sequences 5/02/09 Python Mini-Course: Day 3 – Lesson.
Data Collections CS 127. Lists Lists are ordered sequences of items All programming languages provide a sequence structure similar to a Python list; in.
A Tutorial on the Python Programming Language. Overview Running Python and Output Data Types Input and File I/O Control Flow Functions.
Chapter 10 Loops: while and for CSC1310 Fall 2009.
LECTURE 3 Python Basics Part 2. FUNCTIONAL PROGRAMMING TOOLS Last time, we covered function concepts in depth. We also mentioned that Python allows for.
I NTRODUCTION TO PYTHON - GETTING STARTED ( CONT )
LISTS and TUPLES. Topics Sequences Introduction to Lists List Slicing Finding Items in Lists with the in Operator List Methods and Useful Built-in Functions.
Python Programing: An Introduction to Computer Science
9. ITERATIONS AND LOOP STRUCTURES Rocky K. C. Chang October 18, 2015 (Adapted from John Zelle’s slides)
Python Files and Lists. Files  Chapter 9 actually introduces you to opening up files for reading  Chapter 14 has more on file I/O  Python can read.
Introduction to Programming Oliver Hawkins. BACKGROUND TO PROGRAMMING LANGUAGES Introduction to Programming.
1 Python Data Structures LING 5200 Computational Corpus Linguistics Martha Palmer.
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.
Chapter 2 Writing Simple Programs
String and Lists Dr. José M. Reyes Álamo.
Python Let’s get started!.
Introduction to Python
Python: Control Structures
Basic operators - strings
Lecture 10 Data Collections
CHAPTER FOUR Functions.
Arithmetic operations, decisions and looping
4. sequence data type Rocky K. C. Chang 16 September 2018
String and Lists Dr. José M. Reyes Álamo.
Python Tutorial for C Programmer Boontee Kruatrachue Kritawan Siriboon
Topics Sequences Introduction to Lists List Slicing
15-110: Principles of Computing
Topics Basic String Operations String Slicing
Introduction to Computer Science
Topics Sequences Introduction to Lists List Slicing
Lists Like tuples, but mutable. Formed with brackets: Assignment: >>> a = [1,2,3] Or with a constructor function: a = list(some_other_container) Subscription.
Presentation transcript:

Writing Solid Code Introduction to Python

Program 1 python -c "print 'Hello World' “ python -c "import time; print time.asctime()“ Start an interactive session: ◦ python –v  help(command/expression)

Unix Executable Scripts Most portable version: ◦ #!/usr/bin/env python $ cat first.py #!/usr/bin/env python # A comment print 'Hello World‘ print 2**100 $ chmod a+x first.py $ cat first.py #!/usr/bin/env python # A comment print 'Hello World‘ print 2**100 $ chmod a+x first.py $./first.py Hello World $./first.py Hello World

Basic Elements Keywords: and assert break class continue def del elif else except exec finally for from global if import in is lambda not or pass print raise return try while with yield Operators: + - * / % ** // > & | ^ ~ >= <> != == Delimiters: ( ) [ ] { }, :. ' = ; += -= *= /= //= %= &= |= ^= >>= <<= **=

Data Types All data values are objects ◦ type(obj) returns the type. Numbers ◦ Integer: 23, 027 (octal), 0xDA5 (hex) ◦ Floating points : 1.00, 1.0e2 ◦ Complex numbers: 5+6j

Data Types Sequences ◦ Iterables: All sequences are iterable. (for) ◦ Strings:  Can use “” or ‘’ to specify. “abc” ‘abc’ (Same thing.) Unmatched ones can occur within the string. “matt’s”  Use triple double-quotes for multi-line strings or strings than contain both ‘ and “ inside of them: “““a‘b“c”””  Many Methods built into the string, for example: “hello”.upper() gives ‘HELLO’ ◦ Tuples  (x,y)  (100,200,300)

Sequences Lists ◦ [42, 3.14, ‘hello’] ◦ list(‘wow’) gives [‘w’,’o’,’w’] Dictionaries ( key:value pairs ) uses Hash. ◦ D = { ‘x’ : 42, ‘y’:3.14, ‘z’:7} ◦ {1:2, 3:4} ◦ A single dictionary can store values of different types ◦ D[‘x’] is 42. ◦ del D[‘x’] removes the key from D.

Sequences Concatenation: ◦ S1 + S2 ◦ S1 * n gives n copies of S1 concatenated. Membership ◦ x in S : tests to check whether x is in S. ◦ x not in S : Guess? ◦ For strings: x in S means if x is a substring of S Indexing ◦ x = [1,2,3,4] then x[1] is 2 and x[-1] is 4

Sequences Slicing a sequence: ◦ S[i:j]: from item i (included) to item j (excluded) ◦ x = [1,2,3,4] ◦ x[1:3] # [2, 3] ◦ x[1:] # [2, 3, 4] ◦ x[:2] # [1, 2]

List Methods MethodDescription Nonmutating methods L.count(x) Returns the number of items of L that are equal to x. L.index(x) Returns the index of the first occurrence of an item in L that is equal to x, or raises an exception if L has no such item.

List Methods Mutating methods L.append(x) Appends item x to the end of L ; e.g., L[len(L):]=[x]. L.extend(s) Appends all the items of iterable s to the end of L; e.g., L[len(L):]=s. L.insert(i, x) Inserts item x in L before the item at index i, moving following items of L (if any) "rightward" to make space (increases len(L) by one, does not replace any item, does not raise exceptions: acts just like L[i:i]=[x]). L.remove(x) Removes from L the first occurrence of an item in L that is equal to x, or raises an exception if L has no such item.

List Methods MethodDescription L.pop([i]) Returns the value of the item at index i and removes it from L; if i is omitted, removes and returns the last item; raises an exception if L is empty or i is an invalid index in L. L.reverse( )Reverses, in place, the items of L. L.sort([f]) (2.3) Sorts, in place, the items of L, comparing items pairwise via function f; if f is omitted, comparison is via the built-in function cmp. L.sort(cmp=cmp, key=None, reverse=False)(2.4) Sorts, in-place, the items of L, comparing items pairwise via the function passed as cmp (by default, the built-in function cmp). When argument key is not None, what gets compared for each item x is key(x), not x itself.

List Methods  >>> a + [‘whites'] [‘blend','eggs‘,2,234,‘whites']  >>> a.append('!') [‘blend','eggs‘,2,234,'!']  >>> 2*a [‘blend','eggs',2,234,'!',‘blend','eggs',2,234,'!']

Dictionary Methods Nonmutating Methods D.copy( ) Returns a shallow copy of the dictionary (a copy whose items are the same objects as D's, not copies thereof) D.has_key(k) Returns TRue if k is a key in D; otherwise, returns False, just like k in D D.items( ) Returns a new list with all items (key/value pairs) in D D.keys( )Returns a new list with all keys in D D.values( )Returns a new list with all values in D D.iteritems( ) Returns an iterator on all items (key/value pairs) in D D.iterkeys( )Returns an iterator on all keys in D D.itervalues( )Returns an iterator on all values in D D.get(k[, x]) Returns D[k] if k is a key in D; otherwise, returns x (or None, if x is not given)

Dictionary Methods Mutating Methods D.clear( ) Removes all items from D, leaving D empty D.update(D1)For each k in D1, sets D[k] equal to D1[k] D.setdefault(k[, x]) Returns D[k] if k is a key in D; otherwise, sets D[k] equal to x and returns x D.pop(k[, x]) Removes and returns D[k] if k is a key in D; otherwise, returns x (or raises an exception if x is not given) D.popitem( ) Removes and returns an arbitrary item (key/value pair)

Control Flow if expression: statement(s) elif expression: statement(s) elif expression: statement(s)... else: statement(s)

Control Flow if x < 0: print "x is negative" elif x % 2: print "x is positive and odd" else: print "x is even and non-negative"

Control Flow : while x = 64 count = 0 while x > 0: x = x // 2 # truncating division count += 1 print "The approximate log2 is", count # if count == 6: break

Control Flow : for for target in iterable: statement(s) for letter in "ciao": if letter == ‘c’: continue print "give me a", letter, "...“ for key, value in d.items( ): # cannot use iteritems if not key or not value: # keep only true keys and values del d[key] for x in range(1,5): print x # output:

Sample Code #!/usr/bin/env python import string, sys # If no arguments were given, print a helpful message if len(sys.argv)==1: print 'Usage: celsius temp1 temp2...' sys.exit(0) # Loop over the arguments for i in sys.argv[1:]: fahrenheit=float(string.atoi(i)) celsius=(fahrenheit-32)*5.0/9.0 print '%i\260F = %i\260C' % (int(fahrenheit), int(celsius+.5))

Functions def function-name(parameters): statement(s) def double(x): return x*2 Calling Functions in python function-object(arguments) print double(432) def f(x, y): x = 23 y.append(42) a = 77 b = [99] f(a, b) print a, b

Import statement A Typical python program is made up of several source files. Each source file corresponds to a module. “import” keyword allows to include other modules into a python program. Modules ◦ sys: stdin, stderr, argv ◦ os: system, path ◦ string: split ◦ re: match compile ◦ math: exp, sin, sqrt, pow

Calling External programs import os ◦ subprocess.Popen(["ls", "-la"]).wait()

Sample Program # average4.py # A program to average a set of numbers # Illustrates sentinel loop using empty string as sentinel def main(): sum = 0.0 count = 0 xStr = raw_input("Enter a number ( to quit) >> ") while xStr != "": x = eval(xStr) sum = sum + x count = count + 1 xStr = raw_input("Enter a number ( to quit) >> ") print "\nThe average of the numbers is", sum / count

Output Enter a number ( to quit) >> 34 Enter a number ( to quit) >> 23 Enter a number ( to quit) >> 0 Enter a number ( to quit) >> -25 Enter a number ( to quit) >> Enter a number ( to quit) >> 22.7 Enter a number ( to quit) >> The average of the numbers is

Sample Program # average5.py # Computes the average of numbers listed in a file. def main(): fileName = raw_input("What file are the numbers in? ") infile = open(fileName,'r') sum = 0.0 count = 0 for line in infile.readlines(): sum = sum + eval(line) count = count + 1 print "\nThe average of the numbers is", sum / count

Sample Program # average6.py # Computes the average of numbers listed in a file. def main(): fileName = raw_input("What file are the numbers in? ") infile = open(fileName,'r') sum = 0.0 count = 0 line = infile.readline() while line != "": sum = sum + eval(line) count = count + 1 line = infile.readline() print "\nThe average of the numbers is", sum / count

Assignment for today Implement: closest_pair([(0,0),(7,6),(2,20),(12,5),(16,16),(5,8),(19,7),(14,22),(8,19),(7,29),(10,11),(1,13)]) returns: (7,6),(5,8) Should run in O(nlogn)

Pointers Learn Python in 10 minutes: ◦ Dive into Python ◦