Introduction to Programming with Python

Yeukhon Wong, Computer Science 13', CUNY City College

Fall 2012

i iz a Python Chef

John Yeukhon Wong
Computer Science 13"

  • I had Python as one of the two programming languages (Matlab) in my first semester of freshman year
  • My research lab is a Python shop. I use it almost everyday!
  • I still love C and C++. They are awesome with the right task.

Why Python?

  1. Python is extremely popular means many free tools and libraries and big supportive community.
  2. Python's dynamic and interpret nature makes it easy to develop software.
  3. Major sites are built entirely or partially with Python. (Youtube is almost all Python.)
  4. Scientists and engineers like them besides MATLAB.

How many Python?

Python is a programming language. People implement the language using other languages. Most people should choose CPython.
  1. CPython - the oldest, original Python. C-implementation. Stable and most popular. Official Python.
  2. JPython - Java-implementation. Fast because it uses many Java cool stuff.
  3. IronPython - .NET implementation. Its interperter is very user-friendly!
  4. PyPy - implemented using Python, aims for ultra-speed. Less mature but growing its popularity.

Get CPython 2.7

Python 2.7 vs 3.x

CPython offers 2.7.x and 3.x.
Python 2.7 includes many new features in Python 3, but Python 2.7 has a good backward compatibility with the previous Python 2 releases.

Python developers usually do not upgrade to new Python. It's a tradition. Python are extremely stable.

We stick with 2.7 in this workshop.

Real stuff ...

Goals

We want to write a program to calculate total value of coins and dollar bills we have.

  1. It knows about the value of each coin and each bill.
  2. It needs to output the total.
  3. It asks the human for the number of coins and bills.
  4. It should be correct and reliable.

dollars1.py

that wierd # thing is called comment

            # constants - current U.S. currency values
        

Program executes sequentially. Python sees # and ignores it. It's like speaker note. It's a comment for the speaker (programmer) to look at.

            ####### multiple # is also a comment.
            #### another line of comment
            penny = 0.01     # the value of penny
        

# the value of penny is an in-line comment. It's on the same line as a code (actually, a statement). That # makes it a valid statement.

Goals: Re-visit

We want to write a program to calculate total value of coins and dollar bills we have.

  1. It knows about the value of each coin and each bill.
  2. It needs to output the total.
  3. It asks the human for the number of coins and bills.
  4. It should be correct and reliable.

Binding, Names, Object

Variables

Fill in the blanks?

Variables in Programming

The same concept from math applies in programming. Variables are names to some data. e.g an integer, a shape, or a function f(x) or even a piece of code.
The equal sign = is usually denoted as assignment

            penny = 0.01
            nickel = 0.05
            my_name = 'John Yeukhon Wong'
        

Binding in Python is dynamic

In Python, variables and data are in an open relationship. No commitment.
What do you think this snippet will produce?

        penny = 0.01
        penny = "Sheldon!"
        print penny
        

Everything in Python is an Object

Object is like a bio info
  • identity
  • e.g an id of the object
  • type
  • e.g int, float, string, list, dict, or even Person and Cat?
  • value
  • the actual data you care about (a number, a function, etc)

Put everything together about variables

sample code
            penny = 0.01
            penny = "Sheldon!"
            print penny
        
sample code
            penny = 0.01
            penny = "Sheldon"
            print penny
        

Remarks on variables

The variable penny is used to bind to a string later on, and the name just sucks. Good programmers use good names. In this case, just give a new variable. Variables are so cheap ...

        penny = 0.01
        name = "Sheldon"
        

built-in data types

Python knows a lot about human

Every programming language offers some basic data types so programmers can build something more complex.
data type can tell us what kind of data we can put into that object. Every object is created with a type. e.g <type 'int'> refers to an integer object whose type is an integer. When we advance, we will see we can build more complex and interesting data types by combining other types. This is called data structure.

numbers

Numbers

In Python there are four main built-in numberic types:

  • int
  • float
  • long
  • complex

Numbers: int

        number1 = 10
    

number1 now binds to an integer 10

        type(number1)
        <type 'int'>
    

The type function tells us the type of object number1 points to.

Numbers: float and long

        number2 = 3.14
    

number2 now binds to a real number 3.14
float is basically a real number.

        number3 = 10343435129232
    

Long integers will use long.

Numbers: int vs long

Modern Python 2.x release unified int and long into long.

Python 3.x release does not have int anymore!

Python developers shouldn't care about underlying types too much! It's called duck-typing.

strings

String

         'This is a string' 
         "I use double quote" 
    

Strings are defined either with single or double quotes

        """ Hello, 
Second line """

We can use the triple code for multi-line text

String: comment re-visit

         'This is a string' 
         "I use double quote" 
        """ Hello, 
Second line """

We can use single, double or triple quotes as comments.

String: comment re-visit (example)

Tell me the result of this code

String: comment re-visit (example)

Tell me the result of this code

Why nothing happened? Because the triple quote surrounded that block of code is considered as a comment, which means the computer will ignore it when running the script.

Try replace triple quote with single quote and try with double quote. Any difference? :P

boolean values

Boolean: True

True if it is:

  • True
  • 1
  • Any number other than 0
  • an object's value is not None or False

Boolean: False

False if it is:

  • False
  • 0
  • any object has a value None

None ...

None

This is a bit advance but usually you see a None which is a NoneType when a function returns no value expliclity (whether it's a number, a string, a boolean, or even some complex object).

None is considered a False value

expression

Python expression

Anything that is reduced to a value and no side-effect (simplified version).

        0.01
        pennies * penny
        pennies * penny + nickels * nickel
        total = pennis * penny + .... hundreds * hundred 
    

The last one is NOT an expression.

statement

Python statement

A statement is anything that does something and causes side effect.

        penny= 0.01
        total = pennis * penny + .... hundreds * hundred
        var1 = 'hello'
        if var1 == 'hello': 
print 'var1 is hello'

Line #1 is a statement, a.k.a assignment statement.
Line #2 is another assignment statement made up of a bunch of arihemtic expressions.
Line #3 and #4 are a block of statement a.k.a logical statements.

dollars.py

Is this really correct?

assert

Use assert

assert total == 101.25

assert tests whether the logical expression is True or False. It fails if the logical expression fails.

In general, you should always test your code. assert is not the way to test your code. I will show you in the workshop how to use unittest.

Use assert

assert not not total == 101.25
            assert total <= 101.25

Which one of them will fail the assert test?

if ...

if

            if <expression>:
               do_stuff
        

expression could be any valid Python expression.

        if var1 == 'hello': 
print 'var1 is hello'

The comparison var1 == 'hello' evaluates to a value so that's an expression.

if ... else ...

if-else

Sometimes we want either case to happen. else is usually used as default case.
            if <expression>:
               do_stuff
            else:
               do_something_else
      

if ... elif ... else ...

if-elif-else

Very often we have more than two decisions to make.
            if <expression>:
               do_stuff
            elif <expression>:
               do_something_2
            else:
               do_something_else
      

if-elif-else

            position = get_curr_position(my_map)
            if position == 1:
               print 'Position is at 1'
            elif position == 2:
               print 'Position is at 2'
            else:
               print 'current position is at :', position
      

<, > ==, !=, not

      1 < 2
      

1 is less than 2 True

  1 > 2
     

1 is greater than 2 False

1 <= 2

1 is less than or equal to 2 True

2 >= 1

2 is greater than or equal to 1 True

Negation is achieved either by ~ or not keyword.
      1 != 2
      

1 is not equal to 2 True. But instead, I want it to be False :)

     ~ 1 != 2
     not 1 != 2
     

Python developers use not which is more Pythonic!

Use assert: re-visit

assert not not total == 101.25
            assert total <= 101.25

Now are you sure they will both return True?

Goals: Re-visit again

We want to write a program to calculate total value of coins and dollar bills we have.

  1. It knows about the value of each coin and each bill.
  2. It needs to output the total.
  3. It asks the human for the number of coins and bills.
  4. It should be correct and reliable.

Q&A

input

raw_input

usr_input = raw_input("Tells user what you want them to enter: ")

raw_input is a function that accepts user input from the keyboard. No evaluation. Keeps it as a string. It's safe

input:

input = raw_input("Tells user what you want them to enter: ")

input is a function that accepts user input from the keyboard but tries to convert the input into some data types.
e.g. converts '1' to <int>. Security alarm!

Goals: Re-visit again

So can somebody get user input for all the coins and bills using what we've learned so far?

  1. It knows about the value of each coin and each bill.
  2. It needs to output the total.
  3. It asks the human for the number of coins and bills.
  4. It should be correct and reliable.

dollars.py

while

while

This program only run once. What if the user is helping the whole class counting? You have multiple batches!

		while <expression>:
		    do_something
		

This thing will run as long as expression is True.

while: cont'

		total = 0
        while total <=0:
            print 'dude. your total is zero. try again.'
		    total = int(raw_input('Enter a total: '))
        

Someone try to walk through this code?

for

        for <expression-a>in <expression-b> :
            do_something
        

This will iterate as long as we haven't exhausted all items in expression-b

		for num in [1,2,3,5]:
		    print num
		

[1,2,3,5] is called a list. You can put anything you want in there.

dollars3.py

dollar3.py

while True:

What's the problem?

dollars4.py

Thank You :)

Q&A