An Introduction. What is Python? Interpreted language Created by Guido Van Rossum – early 90s Named after Monty Python www.python.org.

Slides:



Advertisements
Similar presentations
Optional Static Typing Guido van Rossum (with Paul Prescod, Greg Stein, and the types-SIG)
Advertisements

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.
A Crash Course Python. Python? Isn’t that a snake? Yes, but it is also a...
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. Outline Python IS ……. History Installation Data Structures Flow of Control Functions Modules References.
Introduction to Python
Chapter 2 Writing Simple Programs
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.
Introduction to Python (for C++ programmers). Background Information History – created in December 1989 by Guido van Rossum Interpreted Dynamically-typed.
Python Control of Flow.
A Tutorial on the Python Programming Language Moshe Goldstein Most of it based on a Python Presentation by Michael DiRamio
Python quick start guide
Python.
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
January 24, 2006And Now For Something Completely Different 1 “And Now For Something Completely Different” A Quick Tutorial of the Python Programming Language.
Introduction to Python Basics of the Language. Install Python Find the most recent distribution for your computer at:
1 Python CIS*2450 Advanced Programming Concepts Material for this lecture was developed by Dr. D. Calvert.
Introduction to PythonIntroduction to Python SPARCS `08 서우석 (pipoket) `09 Summer SP ARCS Seminar`09 Summer SP ARCS Seminar.
CPTR 124 Review for Test 1. Development Tools Editor Similar to a word processor Allows programmer to compose/save/edit source code Compiler/interpreter.
The Python Programming Language Jeff Myers Programming Language Concepts, 01/14/2002
H3D API Training  Part 3.1: Python – Quick overview.
Introduction to Programming David Goldschmidt, Ph.D. Computer Science The College of Saint Rose Java Fundamentals (Comments, Variables, etc.)
C Derived Languages C is the base upon which many build C++ conventions also influence others *SmallTalk is where most OOP comes Java and Javascript have.
Hello.java Program Output 1 public class Hello { 2 public static void main( String [] args ) 3 { 4 System.out.println( “Hello!" ); 5 } // end method main.
An Introduction to Python Blake Brogdon. What is Python?  Python is an interpreted, interactive, object-oriented programming language. (from python.org)
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.
Introducing Python CS 4320, SPRING Lexical Structure Two aspects of Python syntax may be challenging to Java programmers Indenting ◦Indenting is.
Before starting OOP… Today: Review Useful tips and concepts (based on CS 11 Python track, CALTECH)
CS105 Computer Programming PYTHON (based on CS 11 Python track: lecture 1, CALTECH)
RUBY by Ryan Chase.
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.
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.
CSE 130 : Winter 2009 Programming Languages Lecture 11: What’s in a Name ?
I NTRODUCTION TO PYTHON - GETTING STARTED ( CONT )
Introduction to Programming Oliver Hawkins. BACKGROUND TO PROGRAMMING LANGUAGES Introduction to Programming.
PYTHON PROGRAMMING. WHAT IS PYTHON?  Python is a high-level language.  Interpreted  Object oriented (use of classes and objects)  Standard library.
Python Programming Language by Vasu Chetty. Origins of Python Created by: Guido van Rossum, a Dutch Programmer Created during: Christmas Break, 1989 Created.
Indentations makes the scope/block Function definition def print_message (): print “hello” Function usages print_message () hubo.move ()// hubo is a class.
Lecture III Syntax ● Statements ● Output ● Variables ● Conditions ● Loops ● List Comprehension ● Function Calls ● Modules.
Chapter 2 Writing Simple Programs
Key Words / Reserved Words
Python Let’s get started!.
Introduction to Python
Tutorial Lecture for EE562 Artificial Intelligence for Engineers
Statement atoms The 'atomic' components of a statement are: delimiters (indents, semicolons, etc.); keywords (built into the language); identifiers (names.
Python is a general-purpose interpreted, interactive, object-oriented, and high-level programming language. It was created by Guido van Rossum during.
Introduction to Python
Introduction to Python
CISC101 Reminders Quiz 1 grading underway Assn 1 due Today, 9pm.
Lecture 2 Python Programming & Data Types
Introduction to Python
An overview of Java, Data types and variables
PHP.
Python Tutorial for C Programmer Boontee Kruatrachue Kritawan Siriboon
Lecture 2 Python Programming & Data Types
G. Pullaiah College of Engineering and Technology
(more) Python.
CISC101 Reminders All assignments are now posted.
Programming Languages and Paradigms
Python Basics. Topics Features How does Python work Basic Features I/O in Python Operators Control Statements Function/Scope of variables OOP Concepts.
Python Reserved Words Poster
PYTHON - VARIABLES AND OPERATORS
Presentation transcript:

An Introduction

What is Python? Interpreted language Created by Guido Van Rossum – early 90s Named after Monty Python

Why use Python? Rapid development – Clear & concise syntax – Tons of libraries FOSS: – Free and Open Source Software – GPL compatible license

Why use Python? Portability. – Linux – Windows – Mac – JVM –.Net – Etc.

Why not Python Performance critical applications – Realtime systems – Scientific computations issues with multi-threading no static type verification for large projects

Versions Python version 3.* – Not backwards compatible with 2.* – We’ll learn 2.*

Hello World Observations – Semicolons not needed – Strings can be in single or double quotes a = 'hello' b = "world" print a, b

Basic Types observations? – dynamic typing a = 13 # integer literals b = 0xbeef # hex literals a = 5.5 # float literals b = True # boolean types: True, False a = None # python's null type del a # a is no longer defined b = 'str' # a string

Numbers Supports the usual operators (except ++, --) Built-in Bignums a = 4 b = 5.2 print a + b # 9.2 b = 2 ** 100 # exponentiation print b # L

Strings use single or double quotes use + for Concatenation triple quotes preserve formatting a = r"raw \t string\n" print a # raw \t string\n a = ''' triple quotes'''

Strings what is the result of 'nana nana nana Batman!' a = "Batman!" b = 'nana ' print b*3 + a

conversions a = 20 b = 12 print str(a) + str(b) # 2012 a = '2000' b = '12.0' print int(a) + float(b) #

Branching boolean types: True, False mandatory indentation – can use spaces or tabs – must be consistent a = True if a: print 'a is True' # a is True

Boolean Operators boolean operators: – and, or, not, >, =, <= b = 5 if b 10: pass # pass allows empty blocks elif b >= 4 and b < 7: print 'found' else: print 'none'

Data Structures Lists Dictionaries Sets Tuples

Lists what is mylist[1:3] + [mylist[0]] ? ['three',4,2] mylist = [1, 2,'three',4,'five'] print mylist[1] # 2 print len(mylist) # 5 print mylist[2:4] # ['three',4] print mylist.pop() # 'five' print mylist.pop(0) # 1 print mylist # [2,'three',4] mylist.append(5) # same as mylist += [5]

Dictionaries what is the result of print d['all'][2] 3 d = {1:'one', 'two':2, 'all':[1,2,3]} print d[1] # one print d['two'] # 2 print d[99] # KeyError if 99 in d: # checks for a key print d[99]

Tuples like anonymous immutable structs t = ('str', 5, False) print t[2] # False t[1] = 9 # error, cannot assign a,b,c = t # multiple assignment print b # 5

looping for-loops and while-loops break and continue # print all digits: for i in range(10): print i i = 0 while True: if i > 5: break i += 1

iterating over data quicky create data with list comprehensions: – "expr for var in iterable" iterate over data with "for … in …" squares = [i*i for i in range(10)] for square in squares: print square d = {'1':1,'2':2,'3':3} for val in sorted(d.values()): print val

iterating over data what is the result? [1,3,5,7,9] mylist = [i for i in range(10) if i % 2 == 1] print mylist

functions use the 'def' keyword return type is inferred supports default parameters def greet(name='stranger'): print 'hello', name greet('Guido') # hello Guido greet() # hello stranger

functions first-class functions and closures what is the result of myfunc(4)? 9 def make_adder(op1=1): def adder(op2): return op1 + op2 return adder myfunc = make_adder(5) myfunc(4)

Lambdas lambdas are anonymous functions what would be the result of – filter(lambda x: True, mylist) – [] mylist = [1,2,3,4,5,6,7,8,9] evens = filter(lambda x: x%2 == 0, mylist) print evens # [2,4,6,8]

Generators what is the value of mylist? [1, 2, 4, 8, 16, 32, 64, 128, 256, 512] def powers_of_2(limit): x = 1 for i in range(limit): yield x x *= 2 mylist = [i for i in powers_of_2(10)]

Global Scope globals variables – ok to access in nested scope – must declare as global to modify x,y,z = 0,0,0 # global vars def foo(): global x x += 1 # ok print y # ok z += 1 # error!

Imports import to use objects and functions from another file. def foo(): pass def bar(): pass a.py b.py import a from a import bar a.foo() bar()

Imports import: – loads types from another module on the path. from … import: – directly imports only the specified type. import math from math import sqrt print sqrt(16) # ok print cos(0) # error print math.cos(0) # ok

Exception Handling use except to catch exceptions use raise to throw an exception try: raise NameError('oops') except NameError as e: print 'error: ', e except: print 'some other error'

Exception Handling else is optional. runs if no exception happens. finally is optional. always runs. def divide(x, y): try: result = x/y except ZeroDivisionError: print "who divided by zero?" else: print "result is", result finally: print "finally"

Example File IO reading a file by line is super easy. file handles can iterate over the lines of a file. f = open('file.txt', 'r') for line in f: print line f.close()

Example File IO another (better) way to do the same thing: use with to manage resources. simpler than try … finally. with open('file.txt', 'r') as f: for line in f: print line print f.closed # True

More File operations with open('file.txt', 'rP') as f: line = f.readline() # read a line block = f.read(1024) # read the next 1024 bytes f.seek(0) # go to the 1st byte all = f.read() # read all the bytes f.write('LOL!!!11') # write a string to the file

CLasses python supports OOP. all methods are public and virtual. supports multiple inheritance.

Classes declare classes using the class keyword 1 st parameter of methods is always the self reference. class Adder: def add(self, op1, op2): return op1 + op2 a = Adder() print a.add(1,5) # 6

Classes class Counter: def __init__(self, x): self.x = x def inc(self): self.x += 1 c = Counter(0) print c.x # 0 c.inc() print c.x # 1

Interpreter The Python interactive interpreter – use to learn – use to debug – use as calculator >>> i = 0 >>> while i >>