A Crash Course Python. Python? Isn’t that a snake? Yes, but it is also a...

Slides:



Advertisements
Similar presentations
Python Whats in a name? Snake logos and mascot notwithstanding, its named after Monty Pythons Flying Circus Humor-impaired can safely.
Advertisements

Optional Static Typing Guido van Rossum (with Paul Prescod, Greg Stein, and the types-SIG)
More about Ruby Maciej Mensfeld Presented by: Maciej Mensfeld More about Ruby dev.mensfeld.pl github.com/mensfeld.
Exception Handling Genome 559. Review - classes 1) Class constructors - class myClass: def __init__(self, arg1, arg2): self.var1 = arg1 self.var2 = arg2.
For loops Genome 559: Introduction to Statistical and Computational Genomics Prof. James H. Thomas.
Chapter Modules CSC1310 Fall Modules Modules Modules are the highest level program organization unit, usually correspond to source files and.
Introduction to Python Week 15. Try It Out! Download Python from Any version will do for this class – By and large they are all mutually.
Introduction to Python
I210 review Fall 2011, IUB. Python is High-level programming –High-level versus machine language Interpreted Language –Interpreted versus compiled 2.
Python: a modern hybrid A language for scripting and prototyping Balance between extensibility and powerful built-in data structures genealogy: –Setl (NYU,
Python By Steve Wright. What is Python? Simple, powerful, GP scripting language Simple, powerful, GP scripting language Object oriented Object oriented.
Introduction to Python. What is Python? Interpreted object oriented high level programming language – No compiling or linking neccesary Extensible: add.
By. What advantages has it? The Reasons for Choosing Python  Python is free  It is object-oriented  It is interpreted  It is operating-system independent.
CSC 9010: Natural Language Processing
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.
November 15, 2005ICP: Chapter 7: Files and Exceptions 1 Introduction to Computer Programming Chapter 7: Files and Exceptions Michael Scherger Department.
CSC1018F: Object Orientation, Exceptions and File Handling Diving into Python Ch. 5&6 Think Like a Comp. Scientist Ch
Builtins, namespaces, functions. There are objects that are predefined in Python Python built-ins When you use something without defining it, it means.
Extending Python with C (Part I – the Basics) June 2002 Brian Quinlan
1 Python CIS*2450 Advanced Programming Concepts Material for this lecture was developed by Dr. D. Calvert.
The Python Programming Language Jeff Myers Programming Language Concepts, 01/14/2002
Chapter 4 Numbers. Python Program Structure Python programs consist of: Modules Statements Expressions Objects.
H3D API Training  Part 3.1: Python – Quick overview.
Errors And How to Handle Them. GIGO There is a saying in computer science: “Garbage in, garbage out.” Is this true, or is it just an excuse for bad programming?
Netprog: Java Intro1 Crash Course in Java. Netprog: Java Intro2 Why Java? Network Programming in Java is very different than in C/C++ –much more language.
CSC 508 – Theory of Programming Languages, Spring, 2009 Week 3: Data Abstraction and Object Orientation.
Built-in Data Structures in Python An Introduction.
Getting Started with Python: Constructs and Pitfalls Sean Deitz Advanced Programming Seminar September 13, 2013.
C463 / B551 Artificial Intelligence Dana Vrajitoru Python.
Python Functions.
Cem Sahin CS  There are two distinguishable kinds of errors: Python's Errors Syntax ErrorsExceptions.
An Introduction. What is Python? Interpreted language Created by Guido Van Rossum – early 90s Named after Monty Python
CS105 Computer Programming PYTHON (based on CS 11 Python track: lecture 1, CALTECH)
Guide to Programming with Python Chapter Seven Files and Exceptions: The Trivia Challenge Game.
Using the while-statement to process data files. General procedure to access a data file General procedure in computer programming to read data from a.
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.
PHP vs. Python. Similarities are interpreted, high level languages with dynamic typing are Open Source are supported by large developer communities are.
Python Let’s get started!.
A Tutorial on the Python Programming Language. Overview Running Python and Output Data Types Input and File I/O Control Flow Functions.
Lecture 4 Python Basics Part 3.
CSx 4091 – Python Programming Spring 2013 Lecture L2 – Introduction to Python Page 1 Help: To get help, type in the following in the interpreter: Welcome.
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 PROGRAMMING. WHAT IS PYTHON?  Python is a high-level language.  Interpreted  Object oriented (use of classes and objects)  Standard library.
Quiz 4 Topics Aid sheet is supplied with quiz. Functions, loops, conditionals, lists – STILL. New topics: –Default and Keyword Arguments. –Sets. –Strings.
FILES AND EXCEPTIONS Topics Introduction to File Input and Output Using Loops to Process Files Processing Records Exceptions.
Quiz 1 A sample quiz 1 is linked to the grading page on the course web site. Everything up to and including this Friday’s lecture except that conditionals.
Python C API overview References:
Memory Management in Java Mr. Gerb Computer Science 4.
Rajkumar Jayachandran.  Classes for python are not much different than those of other languages  Not much new syntax or semantics  Python classes are.
Lecture 2 Python Basics.
Python Let’s get started!.
Introduction to Python
Python Training in Chennai
Introduction to Python
Introduction to Python
Topics Introduction to File Input and Output
Python’s Errors and Exceptions
Introduction to Python
ERRORS AND EXCEPTIONS Errors:
CSC1018F: Intermediate Python
(Oops! When things go wrong)
Python Tutorial for C Programmer Boontee Kruatrachue Kritawan Siriboon
CS 1111 Introduction to Programming Spring 2019
CISC101 Reminders Assignment 3 due next Friday. Winter 2019
COMPUTER PROGRAMMING SKILLS
By Ryan Christen Errors and Exceptions.
Lecture 7: Python’s Built-in Types and Basic Statements
Topics Introduction to File Input and Output
Presentation transcript:

A Crash Course Python

Python? Isn’t that a snake? Yes, but it is also a...

... general-purpose open source computer programming language, optimized for quality, productivity, portability, and integration. It is used by hundreds of thousands of developers around the world, in areas such as Internet scripting, systems programming, user interfaces, product customization, and more. From Programming Python 2nd Ed.

No compile of link steps No type declarations Automatic memory management High-level datatypes and operation Object-oriented programming Embedding and extending in C/C++ Classes, modules, exceptions A simple, clear syntax and design Universal “first-class” object model Interactive, dynamic nature Access to interpreter information Wide interpreter portability Large collection of libraries & tools System calls

What does it look like? foo = 10 bar = “foo” foo2, bar2 = foo, bar if x 10 and x < 20): print "The value is OK." if x < 5 or 10 < x < 20: print "The value is OK." for i in [1,2,3,4,5]: print "This is iteration number", i for j in range(5): print “This is iteration number”, j+1 x = 10 while x >= 0: print "x is still not negative." x = x-1

Calculator Basics Numbers x,y = 10, 5 z = x + y x,y = 10.2, 4.8 z = x + y x = j y = complex(10,4) z = x.real a = y.imag

Strings u“spam eggs” #unicode d = r‘spam eggs’ #raw l = len(d) “”” spam eggs ””” s = “spam” + “eggs” varSpam = s[0:4]

Lists >>> a = ['spam', 'eggs', 100, 1234] >>> a ['spam', 'eggs', 100, 1234] >>> a[0] 'spam' >>> a[3] 1234 >>> a[-2] 100 >>> a[1:-1] ['eggs', 100] >>> a[:2] + ['bacon', 2*2] ['spam', 'eggs', 'bacon', 4] >>> q = [2, 3] >>> p = [1, q, 4] >>> len(p) 3 >>> p[1] [2, 3] >>> p[1][0] 2 >>> p[1].append('xtra') >>> p [1, [2, 3, 'xtra'], 4] >>> q [2, 3, 'xtra']

>>>d2 = {‘spam’:2, ‘ham’:1, ‘eggs’:3} >>>d2[‘ham’] 2 >>>len(d2) 3 >>>d2.has_key(‘spam’) 1 >>>d2.keys() [‘spam’,’ham’,’eggs’] >>>del d2[‘ham’] 1 >>>len(d2) 2 Dictionaries In Python false is [ ], 0, “”, None true is everything else

Tuples >>> a = ("foo",10,5+6j) >>> a ('foo', 10, (5+6j)) >>> a[0] 'foo‘ >>> del a[1] Traceback (most recent call last): File " ", line 1, in ? TypeError: object doesn't support item deletion >>>

Functions def fib(n): # write Fibonacci series up to n """Print a Fibonacci series up to n.""" a, b = 0, 1 while b < n: print b, a, b = b, a+b def foo(n): return lambda x: x+ n

Modules - files that have Python functions and statements - can by run as a script or imported -.py extension - module namespace - import sys - from sys import * - __name__ is the name of the module - if running as a script it is ‘__main__’

Files import sys #built atop C i/o myFile = open(”file.txt”, ‘r’) # ‘r’ read # ‘w’ write # ‘a’ append a = myFile.readline() #go over a list of strings returned by readlines() for i in myFile.readlines(): sys.stdout.write(i) #tell & seek are also methods #optional if exiting app since GC will close it then myFile.close()

Exceptions import string, sys try: f = open('myfile.txt') s = f.readline() i = int(string.strip(s)) except IOError, (errno, strerror): # exception w/ arguments print "I/O error(%s): %s" % (errno, strerror) except ValueError: print "Could not convert data to an integer." except: #default print "Unexpected error:", sys.exc_info()[0] raise #throw finally: pass try: raise NameError, 'HiThere' except NameError: print 'An exception flew by!' raise #User defined exceptions extend the Exception class

Classes class Bag: def __init__(self): self.data = [] def add(self, x): self.data.append(x) def addtwice(self, x): self.add(x)

Boost.python Following C/C++ tradition, let's start with the "hello, world". A C++ Function: char const *greet () {return "hello, world" ;} can be exposed to Python by writing a Boost.Python wrapper: #include using namespace boost::python ; BOOST_PYTHON_MODULE (hello ){ def ("greet",greet ); } That's it. We're done. We can now build this as a shared library. The resulting DLL is now visible to Python. Here's a sample Python session: >>> import hello >>> print hello.greet() hello,world

Jython C:\jython>jython Jython 2.0 on java1.2.1 Type "copyright", "credits" or "license" for more information. >>> from java.util import Random >>> r = Random() >>> r.nextInt() >>> for i in range(5):... print r.nextDouble() >>>

References Lutz, Mark. Programming Python, 2nd Ed. (Safari online through UW Libraries) Lutz, Mark & Ascher, David. Learning Python (In ACM Library in 326) l