65
Python Programming: Lecture 1 Introduction Lili Dworkin University of Pennsylvania

Python Programming: Lecture 1 Introductioncis192/fall2014/files/lec1.pdfPython Programming: Lecture 1 Introduction ... I Python is the language you write, but there is also a Python

  • Upload
    buithu

  • View
    237

  • Download
    0

Embed Size (px)

Citation preview

Python Programming: Lecture 1Introduction

Lili Dworkin

University of Pennsylvania

Welcome to CIS 192!

I Please come up and take a copy of the first day survey.

I Instead of “Penn ID”, write your email address.

I No laptops allowed today – stow them when class starts.

Introduction

What is a minicourse?

I Only 0.5 credit

I Meets once a week

I Taught by grads or undergrads

I Applying theory to practice

Introduction

What is Python?

I Compromise between shell script and C++/Java program

I Intuitive syntax

I Interpreted (sort of)

I Dynamically typed

I Automatic memory management

I High-level datatypes

I Supports both OOP and FP

I Module system

I Just plain awesome

Introduction

Java

public class Hello {

public static void main(String[] args) {

System.out.println("Hello, world!");

}

}

Introduction

C++

#include <iostream>

int main()

{

std::cout << "Hello World!" << std::endl;

return 0;

}

Introduction

Python

print "hello world"

Introduction

Introduction

Should you take the course?

I You need some programming experience

I I’m assuming you’re new to Python

I Weekly programming assignments - 70% of grade

I Final project - 25% of grade

I Participation - 5% of grade

I No exams

Assignments

I Due Mondays at midnight through Canvas

I You can discuss and work with others, but must write thefinal code yourself

I Similarly, you may look stuff up online, but must cite anywebsites you use and write the final code yourself

I You get two late days – indicate on the assignment if youwant to use one

I Correctness is 80%, Style is 20%

Final Project

I ∼3 weeks at the end of the semester

I Can work individually or with a partner

I Totally open ended!

Participation

I Asking/answering questions in class and on PiazzaI Trying something new: short “quizzes” at the end of class

I Best performers will get extra credit!I Also measures attendance/understanding

Logistical Stuff

I Lili DworkinI Ph.D student in theory / machine learningI Office hours: Fri 3:00 - 4:00pm in Levine 614

I Eric KutscheraI Office hours: Mon 8:00 - 9:00pm in Moore 204

I Harshitha YenugulaI Office hours: TBA

I Webpage: http://www.cis.upenn.edu/∼cis192

I Piazza: Here

I Canvas: Here

Minicourse Shared Lecture

I New lecture series for all minicourse students

I Led by CIS lecturer Swapneel Sheth

I Tuesday Sept 2: shell usage, version control

I Tuesday Sept 9: web / HTTP requests / etc

I Tuesday Sept 16: software engineering practices

Python

“In December 1989, I was looking for a “hobby” programmingproject that would keep me occupied during the week aroundChristmas ... I chose Python as a working title for the project,being in a slightly irreverent mood (and a big fan of MontyPython’s Flying Circus).”

— Guido van Rossum

Python

I What does it mean for a language to be “interpreted?”

I Trick question – “interpreted” and “compiled” refer toimplementations, not languages

I Python is the language you write, but there is also a Pythonprogram/implementation that decides what to do with it

Python

The most common Python implementation (CPython) is a mix:

I Compiles source code to byte code (.pyc files)

I Then interprets the byte code directly, executing as it goes

I No need to compile to machine language

I Essentially, source code can be run directly

Python

How do you use it?

I Write code interactively in the REPL

I Run a file in the REPL with import file

I Run a file on the command line with python file.py

Basics

>>> 1 + 1

2

>>> print "hello world"

hello world

>>> x = 1

>>> y = 2

>>> x + y

3

>>> print x

1

What’s different from Java so far?

Types

What does “dynamically typed” mean?

Types

What does “dynamically typed” mean?

I Variable types are not declared

I Python figures the types out at runtime

Types

I type function:

>>> type(x)

<type 'int'>

I isinstance function:

>>> isinstance(x, int)

True

I Difference? isinstance caters to inheritance

Types

We prefer to use “duck typing.”

“When I see a bird that walks like a duck and swims like aduck and quacks like a duck, I call that bird a duck.”

— James Whitcomb Riley

try:

# assume object has desired type

except:

# try something else

Types

What does “strongly typed” mean?

Types

Interpreter keeps track of all types and doesn’t allow you to dothings that are incompatible with that type:

>>> "hi" + 5

Traceback (most recent call last):

File "<stdin>", line 1, in <module>

TypeError: cannot concatenate 'str' and 'int' objects

Types

>>> x = 3

>>> x = "hello"

I Has x changed type?

I No – x is a name that points to an object

I First we make an integer object with the value 3 and bind thename ’x’ to it

I Then we make a string object with the value hello, and rebindthe name ’x’ to it

I Objects do not change type

Names and Values

>>> x = 23

>>> y = x

>>> x = 12

What happens?

Names and Values

>>> x = 23

>>> y = x # two names, but ONE value

>>> x = 12 # two names, two values

Functions

def add(x, y):

return x + y

>>> add(3,4)

7

I Colon (:) indicates start of a block

I Following lines are indented

I What’s different from Java?

Types in Functions

I Function declaration doesn’t specify return type

I But all functions return a value (None if not specified)

I Parameter datatypes are not specified either

Syntax and Style

I What is a “block?” Functions, if statements, while loops, etc

I All are started with a colon (:)

I Denoted by whitespace; all lines after the first are indented

I Use 4 spaces, not tabs

Syntax and Style

>>> def add(x, y):

... return x + y

...

>>>

I ... indicates more input is expected

I Need blank line to indicate end of block

Syntax and Style

I Single line comments are denoted with # ...

I Multi-line comments are denoted with """ ... """

I Variable and function names should be lower case withunderscores separating words

I Use docstrings to document what a function does:

def add(x, y):

""" Adds two numbers """

return x + y

Syntax and Style

I And so much more: two blank lines between functions,separate parameter inputs with a space, etc.

I Read the PEP-8 style guide

I ... or at least install the automatic checker

I Your code should pass for full style points!

Printing vs. Returning

>>> def print_arg(x):

... print x

...

>>> def return_arg(x):

... return x

...

Printing vs. Returning

>>> print_arg(10)

10

>>> return_arg(10)

10

>>> print_arg("Hello world")

Hello world

>>> return_arg("Hello world")

'Hello world'

Printing vs. Returning

>>> type(print_arg(10))

10

<type 'NoneType'>>>> type(return_arg(10))

<type 'int'>

Printing vs. Returning

>>> x = print_arg(10)

10

>>> x + 5

TypeError: unsupported operand type(s) for +: 'NoneType' and 'int'

Datatypes: Overview

I None

I Booleans (True, False)

I Integers, FloatsI Sequences

I ListsI TuplesI StringsI Dictionaries

I Classes and class instances

I Modules and packages

Booleans

I Booleans: True, FalseI The following act like False:

I NoneI 0I Empty sequences

I Everything else acts like True

Booleans: Operations

I and, or both return one of their operands

I and, or are short-circuit operators

Booleans: Examples

>>> (2 + 4) or False

6

>>> not True

False

>>> not 0

True

>>> 0 and 2

0

>>> True and 7

7

Integers and Floats

I Numeric operators: + - * / % **

I No i++ or ++i, but we do have += and -=

I Ints vs. Floats

>>> 5/2

2

>>> 5/2.

2.5

>>> float(5)/2

2.5

>>> int(5.2)

5

Imports

>>> import math

>>> math.sqrt(9)

3.0

Assignments

>>> a = b = 0

>>> a, b = 3, 5

Something cool:

>>> a, b = b, a

>>> a

5

>>> b

3

Comparisons

>>> 5 == 5

True

>>> "hello" == "hello"

True

>>> 1 != 2

True

>>> 5 > 3

True

>>> "b" > "a"

True

If Statements

if a == 0:

print "a is 0"

elif a == 1:

print "a is 1"

else:

print "a is something else"

If Statements

I Don’t need the elif or else

I Condition can be any value, not just boolean

if 5:

print "hello"

if "hello":

print 5

For Loops

>>> range(5)

[0, 1, 2, 3, 4]

>>> for i in range(5):

... print i

...

0

1

2

3

4

Ranges

I range(n) produces [0, 1, ..., n-1]

I range(i, j) produces [i, i+1, ..., j-1]

I range(i, j, k) produces [i, i+k, ..., m]

(where m < k)

>>> range(5, 25, 3)

[5, 8, 11, 14, 17, 20, 23]

>>> range(10, 5, -1)

[10, 9, 8, 7, 6]

Break and Continue

>>> for i in range(5):

... print i

... if i < 3:

... continue

... break

...

0

1

2

3

While Loops

>>> i = 0

>>> while i <= 3:

... print i

... i += 1

...

0

1

2

3

Example: Factorial Function

5! = 5*4*3*2*1

0! = 1

Iterative Factorial Function

def factorial(x):

Iterative Factorial Function

def factorial(x):

ans = 1

for i in range(2, x+1):

ans = ans * i

return ans

Recursive Factorial Function

def factorial(x):

Recursive Factorial Function

def factorial(x):

if x == 0:

return 1

else:

return x * factorial(x - 1)

Python Files

import <>

def <>:

...

def <>:

...

def main():

...

if __name__ == "__main__":

main()

Python Files

I name is a variable that evaluates to the name of thecurrent module

I e.g. if your file is hw1.py, name = ‘‘hw1’’

I But if your code is being run directly, via python hw1.py,then name = ‘‘ main ’’

Running Python Files

I In the interpreter or from within another file:I Use import hw1I If you make changes, call reload(hw1)

I In command line:I python hw1.pyI This will call your main() function

Homework 1

I Mostly to make sure you have a working Python setupI Please use version 2.7.*I Python 2.7.3 is installed on Eniac machinesI To install on a personal machine, follow instructions hereI If you have trouble, see me or a TA as soon as possible

I Due Monday the 15th at midnight

I Turn it in using Canvas (just submit the one file)

I Remember to install and use the PEP-8 style chekcer (bestway to install is with the pip package manager)

Homework 1

We’ll be using a module called doctest, which embeds test casesin the docstrings of functions. Here’s a snippet from homework 1:

def is_prime(n):

""" Return True if n is prime and False otherwise

>>> is_prime(9)

False

"""

pass

Homework 1

When you run python hw1.py, you’ll see output like this:

**********************************************

File ``hw1.py'', line 42, in __main__.is_prime

Failed example:

is_prime(9)

Expected:

False

Got nothing

**********************************************

Homework 1

I Always keep the doctests at the TOP of the function (i.e.replace the pass statement with your code)

I Feel free to add other test cases

I If you pass all test cases, you should just see the output“Running doctests...” and nothing else

I Doesn’t mean you got 100% – we’ll be testing your code onadditional cases :)

Quiz

1. What kind of code (source, byte, or machine) do .pyc filescontain?

2. What is the type (not output) of the following expression?math.sqrt(9)/3

3. What is the type of the following expression?isinstance(5.5, float)

4. If I have a function:

def print_hello():

print "hello world"

Then what is the type of the following expression?print hello()

5. What does the following expression evaluate to? ’hi’ and 0

6. Write code to generate a list of even integers from 0 up toand including 10.