Friday, March 23, 2012

csci133class.py

Tkinter module provide many data types, such as Frames, Labels, and Buttons. They equipped with their own sub routines, get for Entry, some of them is standard, like pack, and after. But wouldn't it be nice if we can do their to all the data type (class) we create?

For our ice cream store, we want to create memebership account (Object).
standardMember = Account('George Chan')
standardMember.deposit(100)
Or, for a worker timesheet program, we can create worker that contain other datatype object)
class iceCreamMember:
def __init__(self, name, age):
    self.myName = name
    self.myAge = age
def getAge(self):
    return self.myAge
def getName(self):
    return self.myName

member1 = iceCreamMember('George', 23)
member2 = iceCreamMember('Gerry', 29)

print(member1.getAge())
print(member2.getName())
In python, when we want to create a new datatype (new class), we would use a class statement. The keyword class tells python that it is a new datatype we are creating, notice it is a good style to always name your class with a upper case letter.

And when we want to create an instance of the iceCreamMemeber, an individual object of this new type, we will use the class name as it is a function.
member1 = iceCreamMember('George', 23)
This create a new iceCreamMember object, and member1 refers to it. Remember the constructor is called when we create an instance of the object in C++? In python, the __init__ function will be called right away.
def __init__(self, name, age):
Look at this line, the __init__ function takes 3 parameters, but look at the line #20, we only actually passing 2 to it. Why? Because the first argument is always set to refer to the new instance we just created. (Self, itself). You can name it anything, but the first one is always point to the object itself, so it makes senss to use 'self'. The order of ('George', 23) is important, because name gets 'George', as a string, and age gets 23, as an integer.

Different from C++, python's class instance does not have member variable pre say. They have attributes, and you do it with the syntax of.
self.myName = name
self.myAge = age
To create a function for our userdefined class, we just use def like we always do, with the difference of giving it a (self) parameter. Notice, when we call the function .getName(), we don't have to give it anything. Since the self argument is generated automatically.

But if we try to print(member1), something weird will happen, try it. It actually let us learn another fact about how python work.
>>> 
<__main__.iceCreamMember object at 0x0000000002EE1E48>
The reason why we get the memory address like output, it is because we have yet to "teach" python how we want to print this. python is computer, and that's what the iceCreamMemeber to python is at this moment, let's add another method to our class.
def __str__(self):
    return self.myName + ', and age ' + str(self.myAge)
So when we ask python to print, it will know what to print.

*Important* : self vs. Deck
class goldMemeber(iceCreamMemeber):
def __init__(self, discount):
    iceCreamMemeber.__init__(self)
    self.myDiscount = discount
def __str__(self):
    return "{0}% of discount for member".format(self.myDiscount)
We can understand this new class as: GoldMemeber is a kind of iceCreamMemeber. And the GoldMemeber inherits all the function the iceCreamMemeber has. So the getName, getAge function, will be provided to the GoldMemeber automically.
iceCreamMemeber.__init__(self)
*Important*: We must use the explicitly passing method to to pass the instead. If we use self.__init__(), we will be instead calling the goldMember.__init__ function. Which is the function we are trying to define right now at this moment.

Monday, March 19, 2012

csci133number.py

Reference: http://docs.python.org/library/stdtypes.html#numeric-types-int-float-long-complex
Please, please, please click on it and read it if you want to know the full details of the information. The reference page tell you exactly everything you ever need to understand them!

There are total of 4 number type (or Numeric Type): integers, float, long, complex.
  • Integer - implemented using long in C, have 32bits of precisions.  Integers can be positive and negative, but they are whole numbers. (1,2, 3, 4, 5, 0, -1, -2..)
  • Floating point - implemented using double in C. When you need decimal point, you can use floating point. Such as 1234.5 + 1234.5.
  • Long integers - have unlimited amount of precisions. (See here for long integers). It is useful if you are calculating the amount of debt United States is under. (wink wink)
  • Complex - have real and imaginary component to it. (See here for Complex numbers). I think it is very useful, but I am not yet familiar with it yet, I shall come back to it soon.
If floating point is not enough for your usage, you can also use fraction, and decimal. Python is very nice because it support mixed arithmetic, when you do this, python will convert the broader type into narrower type. For example: Integer * Floating point = Integer.

The relationship is the follow: Complex > Floating point > Long Integer > Integer
# Get the absolute value 
abs(-5)

# Convert something into integer
myNumberInString = '100'
anotherNumber = 50
result = 0
result += int(myNumberInString) + anotherNumber

# The power of x function 2^3
pow(2, 3)

There is a thing called module, it is a package of tools. Similar to header files in C++, remember the math class in C++? There is one similar to it in python, and it is called math too. We have to always import the module before we can use its tool. There are many of them, feel free to experiment with it, they provide you a lot of useful subroutine.
# Sample code for math moduele
import math
print(math.pi)
>>> 3.1415926535897931

csci133Buildin.py

Everything in Python are objects, and python's build-in types are objects too. When you use the build-in types, you don't have to worry about anything such as memory allocation, implement insert, search, sort, list, print, and get routines. We can start immediately work on our code. *In C++, we usually call them functions, In JAVA, we call them methods and finally, in Python, they are called routines. Here is a list of reason why you should try to use build-in types as much as you can.
  1. They are easy- if you need simple program, they are great for fast development , easy to write, debug, and for others to read and understand your code. You can write a program to calculate expense in just about 5 mins using the build in types.
  2. They are useful - you can use them to build more complex object. They are like lego, you can stack them and form different tools.
  3. Efficient - if you want performance, look no further, they are perfected by developer, and will only get better as more release follow. It is less likely you will write a more efficient routines than them, although maybe for highly specialized input.
  4. Always here - every python comes with them, you don't have to download anything extra, and they are standardize cross everyone. Everyone has the same copies when they download the Python.

Name
Example
Sample Code
Reference
Number
12345, 1234.5
String
‘Hello Python’
List
[1, 2, 3] [‘a’, ‘b’, ‘c’]
csci133list.py
Dictionary
{‘username’:’password’}
csci133dictionary.py
Boolean
True, False
csci133boolean.py

Here is an index of some of the basic build in types offered by python, please note there are a lot more other kinds that I didn't have a chance to cover! Although it is my goal, to write about all the build in data types :) . Python is dynamically typed (instead of declaring the type and compile the code), and strongly typed (means you can not perform other type function on another type). It is something to keep in mind when you are learning other languages.

Friday, March 16, 2012

csci133p6.py

This is a taste of graphical user interface, and including myself too. When the program is run with a GUI, the feeling is just so much "different", you are able to change your option with a click of bottom, there are now colors! You can change the color of the background easily. And the very sample program that you write are now so much more interesting. But the planning is now more important than ever as well, because you need to figure out what is it you want to be display on the screen before you start.

The focus we are using in this series of tutorial is from Tkinter, or known as TK.
from Tkinter import *

root = Tk()
# Change the background color to light green
root['bg'] = 'light green'

# Create a title widget in the frame of root
simpleTitle = Label(root)
simpleTitle['text'] = 'Hello Tkinter!'
simpleTitle.pack()

mainloop()
The output of the program above is like this, it is a simple window with the string, 'Hello Tkinter!', but try to make the window size better!


Do you see the green color? That's the light green background color we set. It is not shown when the GUI launched, you can resize the window, by moving your mouse pointer to the border of the window, and then just drag it larger. So there you have it you see the background color. You can also change the color of the text label if you want it too.


Look at line 1:
from Tkinter import *
We have to import the module of Tkinter, because although python does ship with this, you have to let python know you want to use this.
We create a Tk() object named root, this is like a base frame. And then we can change the background color, by accessing its ['bg'] indexed variable, and assign it to 'light green'. If you want, you can change it to 'light pink' as well.
Look at line 8:
simpleTitle = Label(root)
simpleTitle['text'] = 'Hello Tkinter!'
simpleTitle.pack()
We here create a Label named simpleLabel, it is based on the root's frame, that's the reason. If there is another frame, we would replace root with the name of the frame. For example: myLabel = Label(anotherFrame). Just like ['bg'] field, there is a ['text'] field associate with it too, we access it the same way we access the background color, we can assign a string to it. And at last, we have to call .pack(), to ask Tk to draw it onto the screen. When we make changes, we have to always do .pack(). Notice pack() is a function, it actually takes parameters!

Reference: http://docs.python.org/library/tkinter.html#packer-options
Here is the list of possible options:
  • expand: if it is set to true, it will expand as the window's size get bigger. Ex: foo.pack(expand=YES)
  • fill: it is to screen, there are 3 options to it, either X, Y, BOTH
    Ex: foo.pack(fill=BOTH)
  • side: it get where your widget want to be positioned. TOP (default), BOTTOM, LEFT, RIGHT
    Ex: foo.pack(side=LEFT)
  • anchor: which way it snaps on to, it is think as a compass, has 8 directions. "n", "ne", "e", "se", "s", "sw", "w", "nw", "center"
    Ex: foo.pack(anchor=w)

Example of such chained options:
foo.pack(expand=YES, side=LEFT, fill=X)

Wednesday, March 14, 2012

csci133c5.py

In python, there is an extremely useful data type called dictionary. What a dictionary is a collection of unordered (key, value) pairs. Notice, one value can be mapped to one key only, so if you try to add another value with the same key, it will change the value it originally assigned to it. It makes sense because if you have a few values mapped to the same key, you have no idea which is which.

Take a look at the example for the dictionary below
passwords = {'george':'dog', 'gerry':'cat', 'stephen':'chicken'}
name = input('Username: ')
password = input('Password: ')
if name == passwords[password]:
   print('Correct, welcome:', name)
else:
   print('Sorry, bad password.')
Output:
Username: george
Password: dog
Correct, welcome: george

Username: george
Password: cat
Sorry, bad password.
Reference: http://docs.python.org/tutorial/datastructures.html#dictionaries
And lastly, we can not use a list as the key either, because you can modify a list by accessing it with the index assignment, slice assignment or other methods. You create a dictionary with a pair of braces{}, it is now an empty dictionary. You separate the entries by comma, and you give the value to the key by :. key: value is the syntax for the dictionary entries.
  • keys(), which return a list of all the keys used in the dictionary
  • del dictionary[key], delete the key:value pair
  • if you store a key that is already has a value, the old value will be gone
  • the keys can be strings and numbers 
  • the value can be objects of any kind
When you want to look up a key and see what its value is, do this:
passwords['george']
# Return value will be 'dog'
Look at line 4, there is a if statement, similar to C++, if is a control flow statement. You can write a else statement that allow it to be executed when the if statement condition is not satisfy. But you can just use if statement by itself too.
myNum = 10
if myNum > 5:
    print('My number is greater than 5') # Totally cool too
So, now you know for loop, you know how to open a file, and a if else. Let's start to create some program with them. It is like lego, when you have more parts, you can create more complex (powerful) projects.

Monday, February 20, 2012

csci133c4.py

Since we downloaded a txt file, this tutorial is about opening it. Here is the code.
with open('book.txt') as book:
    # The book is a list containing all lines
    for line in book:
        # If the line contain the string 'yourselves'
        if 'yourselves' in line:
            print(line)
The first line there is a reserved python keyword with, followed by open('filename'). It is actually a path name between the (), but if you don't provide a path, it is assumed it is the current directory. In case you have to access a file from a different folder, you would provide it a path with the file name. Such as ../../csci133/ch1/csci133c4.py.

You would open the text file into another object . You don't have to call it book, you can call it anything you want, that would be list containing all the "lines". In the event of it is actually a text file with strings after strings, you does make sense to call it something along the line of data, book, and myFile. You can try to iterate through it with for loop.
for object in objects:
    # do something here
Example problem #1: Count the number of words contained in the txt file
count = 0
with open('book.txt') as book:
    for line in book:
            # += is the same as count = count + count
            count += len(line.split())
print('There are', count, 'of words.')
Before we are done, there is also way to get input from the user, you would set up a variable, and assign it the value of the input.
Example problem #2: Take an input from the user (like cin in C++)
name = input('What is your name?')
print('Hello, nice to meet you', name) 
Python's list comprehension
It is a handy way to write code in a very short way, compare the two code. They do the same thing. I heard from people, it is a way to pretend to be smart, on the other hand, it seems useful to write code in a short way I guess. I prefer slightly the longer way, but I have a feeling in the professional world, everyone use list comprehension. Because it is faster, and less likely to create errors.
for number in numbers:
    data[number] = data[years][time] 
    return data
the data to be changed for object in objects
return [data[number][time] for number in years]
# Regular code
iceCreams = IceCreamFlavor()
iceCreamMenu = [] # iceCreamMenu is a list
for number in range(5):
    iceCreamMenu = iceCreams.random()

# Same code with list comprehension
iceCreams = IceCreamFlavor()
iceCreamMenu = [iceCreams.random() for number in range(5)]
The more I use it, the more I think it is useful. Just like all functions and methods (well, most of them). It is meant to help us write program faster and easier. Just like a a lot of the helper function is build in, this is build in to help us not have to spend as much time to get what we want.

Notice the range(5)? That means it is created a list of 5 numbers, [1, 2, 3, 4, 5]. Useful tool as well! Instead of doing a = [1, 2, 3, 4, 5]. And for number in a.
# The range(5)
for number in range(5):
    # Statement

# Same as this
numbers = [0, 1, 2, 3, 4]
for number in numbers:
    # Statement
Reference: http://docs.python.org/library/functions.html#range
range([start], stop[, step]) 
It is very commonly used in for loops, the start and stop arguments must be integers, if you didn't give it a step argument, it will be default to 1. If you didn't give it a start argument, it will be default to 0.
The range() function create a list with the number 0, 1, 2, 3, 4. Notice python is zero based, so if you need to print out from 1 to 5. You would not want to offset the number variable. <Correct way: to use the start argument>
# To print 1-5 the correct way
for number in range(1,6):
    print(number)
Output:
>>> for number in range(1,6):
...     print(number)
... 
1
2
3
4
5
>>>  
As for the step argument, it is what the increment is used. If you use the step of 2. Ex: range(0, 10, 2), it will give you [2, 4, 6, 8, 10]

Practice Problem:
# Write a range(start, stop, step) that generate the following results
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
[0, 2, 4, 6, 8, 10]
[1, 3, 5, 7, 9, 11]
[0, 50, 100]
[3, 9, 12, 15, 18, 21]

Answer to the problems: Notice for the question when it ask you where to stop, you can either stop at the next value (11) for the case of 10, or stop at the next increment value, 150 for the case of 100, or 101 for the case of 100. It will still work the same. I just like to do it this way, if you get the same answer, then you should be good to go.
>>> for number in range(10):
>>> for number in range(1, 11):
>>> for number in range(0, 12, 2):
>>> for number in range(1, 13, 2):
>>> for number in range(0, 150, 50):
>>> for number in range(3, 23, 3):
Note: Because reading again on the range() documentation, I thought the only way to do print 1-5 is to offset. Which show us how important and good it is to read the reference.

Monday, February 6, 2012

csci133c3.py

Welcome to the 3rd notes for the python programming lab. Let's take a look at the code and see what does it do. Today we will talk about the function. Function is a block of code that do varies kind of thing, and might or might not return the value it get.
line = 'This is a sample line of text.'
# Measure the length of the line string
print(len(line))

# Split the line string by spaces, return a list
print(line.split())

# Measure how many word are there now
print(len(line.split()))
Output:
30
['This', 'is', 'a', 'sample', 'line', 'of', 'text.']
7
Pay close attention to line #3, when we call a function (or to use a function). We can also pass some data if the function accept it, that data is called parameter, or argument. So we passed the line into the length function, len(line). And the function returned the result of 30, and then it is being passed to the print function and print on the screen. That is why it is outputed as 30.

Whenever we want to print thing on the screen, we are always actually calling the print function, and passing the number, letter, or word into the function. What about the split function? What does it do? From the python's web manual.
http://docs.python.org/library/stdtypes.html#str.split
str.split([sep[, maxsplit]])

Return a list of the words in the string, using sep as the delimiter string. If maxsplit is given, at most maxsplit splits are done (thus, the list will have at most maxsplit+1 elements). If maxsplit is not specified, then there is no limit on the number of splits (all possible splits are made).

For example, ' 1 2 3 '.split() returns ['1', '2', '3'], and ' 1 2 3 '.split(None, 1) returns ['1', '2 3 '].
The function require a string to be invoked on, that's why it has str.split(), the split function actually takes argument. But at the moment we just want it to split with blanks, or spaces. Note each data type has their own set of functions build in to them.

Example Problem #1: Turn a string into all lower case
If you want to turn a string to lower case
word = 'THE QUEEN'
word = 'THE APPLE'
newWord = word.lower()
print('Before:', word)
print('After:', newWord)
Output:
Before: THE QUEEN
After: the queen
Example Problem #2: Turn every word into lower case, remove the symbols, print them one by one. (One on each line). String is from a random novel on the web.
line = 'http://www.gutenberg.org/cache/epub/39133/pg39133.txt'
newLine = ''
for char in line:
    if char in 'abcdefghijklmnopqrstuvwxyz':
        newLine = newLine + char
    else:
        newLine = newLine + ' '
print('Before:', line)
print('After:', newLine)
print('Split it:', newLine.split())
for word in newLine.split():
    print(word)
Output:
Before: http://www.gutenberg.org/cache/epub/39133/pg39133.txt
After: http   www gutenberg org cache epub       pg      txt
Split it: ['http', 'www', 'gutenberg', 'org', 'cache', 'epub', 'pg', 'txt']
http
www
gutenberg
org
cache
epub
pg
txt 
So before we go, let's go to this link, download the file into our current dir. Because the next tutorial we will use that file! http://www.gutenberg.org/cache/epub/39133/pg39133.txt , and rename it to book.txt

Practice Problem:  Write a program to clean up the following string, turn all letters into lower case, and print one word per line.
foo = '[_He approaches Fabiani._]'
Output:
he
approaches
fabiani

Wednesday, February 1, 2012

Pydev in Eclipse on Mac

When you downloaded Pydev for Eclipse, you have to set up the Python interpreter before you can start using it. Here is the instruction.

To configure a Python or Jython interpreter in 
Eclipse > Preferences > PyDev



When you are in Preferences, find PyDev, and click on the Interpreter - Python



Choose New in the upper right and enter /usr/bin/python
Eclipse will then take care of the rest for you – ie. updating the $PYTHONPATH
    Reference & Credit: On Using Pydev on a Mac.

    Friday, January 20, 2012

    Python Reference Link

    In this post I will include all the reference I used when I am learning Python, some of them are textbook, some of them are website.

    • http://effbot.org/tkinterbook/tkinter-whats-tkinter.htm
      Very easy and simple to read, proivde a good starting point if you never done any kind of GUI before. It is very short and to the point, there are no complicated theory or other information. Not to say it is not important however, but to get you up to speed and start writing software, it is great!
    • http://stackoverflow.com/questions/tagged/python
      A google for programming related question, actually it is a really good idea to just read the questions and the answers. Sometimes it is like little trick and tips, sometimes it is the concept explained in another point of view that is not like from a textbook, but from a working professional programmer. It fits the bill of learning something everyday ;)
    • http://python.net/~goodger/projects/pycon/2007/idiomatic/handout.html
      It is like a python programming guide with a lot of cool tips and trick that a new programmers might overlook. Good read, and interesting.
    • http://docs.python.org/tutorial/
      The best tutorial there is for beginner learning how to write program in python. It talks about a lot of the buildin function, type, module. It shows great example code as well as the required parameters and return type.

    Python's Doc Tutorial Notes

    Chapter 1: Whetting Your Appetite

    Python is really simple to use, but at the same time it offer more structure and support for large program. In particular, the error checking is very well developed compare to C. Where in C, they expect you to make judgement yourself, and handle the possible problem yourself. And of course, Python has a lot of high-level data types built in, such as flexible array and dictionaries, which can be apply to all types, even your own class. Similar to C++'s vector, you can put your class object into the vector.

    Python follows the main heart idea of OOP, it allows user to separate and export their program into modules. And then you can reuse or extend it as needed. There are quite a few module that comes standard with all the python installation, such as file I/O, system calls, sockets, and graphical user interface toolkit such as tkinter.

    Python is an interpreted language, so you don't have to worry about comilating and linking your file. Remember when you write a c program, instead of just pressing a "run" button, or F5 in the default IDE, you will instead go to your terminal, type in: g++ -Wall -o csci133p1 csci133p1.cpp ccsci133myClass.cpp. These sort of goodies, after you type them, and then you are hit with a wall of error message that is not very human-readable, but except telling you line number x is broken?

    And a couple of key note-worthy characteristic:
    1. Python can do complex operations in 1 liner, and in fact most python programmer love the 1 liner solutions a lot.
    2. Python's statement grouping is done by indentation, instead of the ending brackets {}
    3. There are no variable type declaration, and similarly, there is no return type specified. You can return as many things as your heart desire, by doing return my_number, my_home, my_food

    Python's name has nothing to do with the reptiles, it is because the author like the BBC show "Monty Python's Flying Cirus". But despite reading this, I still think about python as "a big snake". :)

    Chapter 2.1 Notes

    Thursday, January 19, 2012

    csci133c2.py

    After we learn how to write a loop, we can do more by combining two or more of them. It is actually very easy too. Say I want to list all the possible combination of ice cream. I want to create something that will output this.
    # Output desired
    I like Vanilla ice cream with Gummy Bear
    I like Vanilla ice cream with Cookies
    I like Vanilla ice cream with Nuts
    I like Vanilla ice cream with Chips
    I like Chocolate ice cream with Gummy Bear
    I like Chocolate ice cream with Cookies
    I like Chocolate ice cream with Nuts
    I like Chocolate ice cream with Chips
    
    There are 2 kinds of ice cream and 4 kinds of topping in this program, so we most likely going to need 2 list, and then we loop them each through another.
    # Solution code for the example above
    iceCreams = ['Vanilla', 'Chocolate']
    toppings = ['Gummy Bear', 'Cookies', 'Nuts', 'Chips']
    # Looping through the ice creams
    for iceCream in iceCreams:
        # Looping through the toppings
        for topping in toppings:
            print('I like', iceCream, 'ice cream with', topping)
    
    There you have it, it is actually very simply to check for all possible combinations of the items you have in your list, does not matter if they are food, student, car, dog, anything you want. Anyway, so now let say you only want Cookies as your topping on your ice cream, you will need to check if topping is cookies, here is how to do it in python!
    # if statement example
    numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
    prime = [1, 2, 3, 5, 7]
    for number in numbers:
        # Check if the number is in the list of prime we have
        if number in prime:
           print('The number', number, 'is a prime!')
    
    Output:
    The number 1 is a prime!
    The number 2 is a prime!
    The number 3 is a prime!
    The number 5 is a prime!
    The number 7 is a prime!
    
    Note, this is just an example to showcase the example of the if statement, in real life this is not how it is done. A much more useful example: The vowels example:
    # Example problem that check for vowels
    vowels = 'aeiou'
    words = ['apple', 'banana', 'orange', 'grapes', 'mango']
    for word in words:
        for letter in word:
                if letter in vowels:
                   print(letter, 'is in the word:', word)
    
    Output:
    a is in the word: apple
    e is in the word: apple
    a is in the word: banana
    a is in the word: banana
    a is in the word: banana
    o is in the word: orange
    a is in the word: orange
    e is in the word: orange
    a is in the word: grapes
    e is in the word: grapes
    a is in the word: mango
    o is in the word: mango
    
    Practice Problem:
    Write a program that checks the word 'google', and print what are the vowels.
    Write a program that print one type of ice cream on each line
    # Use this list of ice cream for the practice problem
    iceCreams = ['Vanilla', 'Chocolate', 'Strawberry',
                 'Neapolitan', 'Chocolate Chip', 'French vanilla', 
                 'Cookies and Cream', 'Vanilla Fudge Ripple', 'Praline pecan']
    
    Write a program that print 'I love ice cream' 50 times :)
    # Tip: Don't write print() 16 times, think about loop, n * n = 16...?
    Write a program that count down from 20 to 1
    # Tip: Create an integer counter, and -1 each time you run through
    20
    19
    18
    17
    16
    15
    14
    13
    12
    11
    10
    9
    8
    7
    6
    5
    4
    3
    2
    1
    
    Write a program that check the vowel in the ice cream name list
    # Use this list of ice cream for the practice problem
    iceCreams = ['Vanilla', 'Chocolate']
    
    Solution
    # Solution on the question
    iceCreams = ['Vanilla', 'Chocolate']
    vowels = 'aeiou'
    for iceCream in iceCreams:
        for letter in iceCream:
            for letter in vowels:
                print(iceCream, 'has vowel', letter, 'in it')
    

    Thursday, January 5, 2012

    csci133c1.py

    In the first program we are going to start with "Hello World", in python it is actually really simple to do. Type the below code into the file, and press save and run!
    # Example: Hello World
    print('Hello World! Python is fun!')
    Output:
    Hello World! Python is fun!
    Notice in the single quote signs, what is between ' ' is viewed as a sequence of characters. Unlike in C++, python is an interrupt language, we don't need to complie, we just need to save and run it. (Control + Save) Then (F5) And in python, you can comment with " # " sign, the python will not do anything to that line, it is for reference and notes. It is always good habit to document your code, and keep the comments outdated when you make changes.

    Let's create a string variable name food, and we print "I like that food".
    # Example: Printing with variable
    food = 'cookies'
    print('I like', food)
    
    Output:
    I like cookies
    Here there we learn two things, one is the way the python declare the variable, without a type. It takes care of figuring out what is the type, base on what you give it. In this case the food is a string variable, and the way to include the variable in the print, we separate it with a comma (,).  And let's take a closer look at the first line, the equal sign does not mean food is equal to cookies, rather it mean we assign cookies to the object data named food. There is a difference there, it would be best if we read it as, "food is the name of the string for cookies", or "cookie is now food" in our program. Below is another example to demonstrate how to use a few variable at the time in the print.
    # Example: What do you eat everyday?
    breakfast = 'milk'
    lunch = 'burger'
    dinner = 'steak'
    print('I eat', breakfast, lunch, dinner, 'everyday.')
    
    Output:
    I eat milk, burger, steak everyday.
    This example we can see we can chain more variables in the print statement, you can do it with different variables if you have other. And take a note on the following piece of example, guess what is the output?
    # Little Quiz 
    breakfast = egg
    print('Today"'"s breakfast:', breakfast
    breakfast = sandwich
    print('Today"'"s breakfast:', breakfast
    Can you guess what is the output?
    Here is the answer!
    Today's breakfast: egg
    Today's breakfast: sandwich
    If you guessed correctly, good job! And if you wonder why I used double quotes ( " ), it is because it is the only way to print single quote. You need to wrap the single quote in a double quotes. "'". Try it and see if it works!

    But it is kind of hard to type out all this, if we have many many different kind of food for breakfast, what if we have 5 different foods, do we need to write 5 identical print lines? The answer is no! Check out the following example.
    # Simple for loop example
    foods = ['egg', 'juice', 'apple', 'bread', 'cookies']
    for food in foods:
        print('Today"'"s breakfast:', food)
    Output
    Today's breakfast: egg
    Today's breakfast: juice
    Today's breakfast: apple
    Today's breakfast: bread
    Today's breakfast: cookies
    Don't you think it is a lot easier this way? And feel free to type your own favorite food for breakfast. For these who are new to python programming, there is actually a lot going on in this example.
    1. The object we created in the example above is a list, in this case it is a list contain 5 string objects, a list is a sequence of objects. We create list in python by separating the string objects with commas, and enclose the sequence with square brackets. Another example of a list contain 2 student: ['Sam', 'Kelly']
    2. You can create a list of other types too, with integers, whole numbers, such as 1, 2, 3, 4, 5, including negative numbers too. Example: dates = [1, 5, 12, 19, 20]. We have here a list object name dates, containing 5 integers.
    3. There is control statement, or as call it, a for loop. The structure of the statement is like this:
      # Example for a for loop control statement
      for object in objects:
      <Indentation> statement
      <Indentation> statement
      The python only know the statement is "inside" a loop when you indent it, otherwise it has no way of knowing. It is different from say other language like C++, as they use {} to create a block of code. And although we don't have to end every single statement with " ; ", but in the case for the loop, we need to add a colon " : ", to let python know this is the end of the condition. I provide readers with a few more example here:
      # Always object for object(s)
      for line in lines:
      <Indentation> statement
      
      for car in cars:
      <Indentation> statement
      
      for class in classes:
      <Indentation> statement 
    However, python doesn't care what name we use, just like in other programming language, the name (identifier) is for the programmers (human) to read. So there is nothing stopping you to do something silly like this.
    # A really bad example
    aawhjwb = [1, 5, 20, 55]
    for bbb in aawhjwb:
        print('Visit doctor at: ', bbb, 'of this month')
    But it will be very hard to remember what is going on, so try to use something that make sense, that way it is easier to debug and for other programmers to read your code. Please do not do not do this.

    Practice Problem:
    Write a program that produce the following output:
    Tip: Create a list contain 3 student's name.
    Hello George
    Hello Peter
    Hello Joe
    
    Write a program that produce the following output:
    Tip: To print an empty line, do print(), this will produce an empty line
    Red Car
    Red Truck
    Red Tank
    Red Boat
    
    Blue Car
    Blue Truck
    Blue Tank 
    Blue Boat
    
    Green Car
    Green Truck
    Green Tank
    Green Boat
    

    Tuesday, March 29, 2011

    csci133Tkinter.py

    A post about Tkinter's most common usage question, answer and demonstration sample code.

    Monday, March 21, 2011

    csci133string.py

    Reference: http://docs.python.org/library/stdtypes.html#sequence-types-str-unicode-list-tuple-bytearray-buffer-xrange

    String is one of the most if not the most common object used in all languages, you can create a string object by doing.

    myString = 'George'

    # Work in progress #

    Monday, December 13, 2010

    csci135c3.cpp

    This is the second kind of loops, the while loops. In this tutorial, I am also going to demonstrate a variation of the while loop, the do-while loop.
    /*
     *  csci135c3.cpp
     *  This program shows the useage of the while loop.
     *
     */
    
    #include <iostream>
    using namespace std;
    
    int main()
    {
       int counter = 5; // our integer counter variable
       cout << "While loop #1, while counter > 0" << endl;
       while (counter > 0)
       {
          cout << "Counter is now: " << counter << endl;
          counter--;
       }
       
       counter = 10; // reset counter back to 10
       cout << endl; // just for the display, this skip one line 
       
       cout << "Do While loop, while counter > 0" << endl;
       do
       {
          cout << "It still run one time although it does not satisific the "
          << "condition counter > 10 " << endl;
          counter--;
       } while (counter > 10);
       
       return 0;
    }
    The format of the loop is like this:
    while (condition)
    {
       // do something here
       // some kind of counter adjustment
    }
    The concept of the while loop is just like how it sounds, while condition is true, do the execution in the block. But unlike the for loop, the counter adjusting is do in the loop. See the example, line 17 is counter--. Of course, you can increment as well. At this point, you might be asking: “What happen if we do not know in advance how many times we need to run?” This is not true, because we can use variable in the condition. You can do something like this.
    while (counter > whereToStop)
    {
       // do something here
    }
    However, something important need to be clear. Be careful that your loop, whether it is a for loop or while loop, it is not an infinite loop. An infinite loop is a loop that will not terminate, something it is because the condition is always possible to satisfy, or more frequently, remember to include the counter adjustment. Below are some examples that show what possible mistake one can make.
    int counter = 0;
    while (counter < 10)
    {
       // No decrement or increment, it won't be ever greater than or equal
       // to 10. So it will be an infinite loop.
    }
    
    int counter = 10;
    while (counter > 10)
    {
       // the counter is going the opposite direction, and it will
       // never be greater than 10. This is an infinite loop.
       counter--;
    }
    Lastly, there are times when you do want the loop be infinite. I remember it the canvas GUI program, the screen requires to be refreshed until the user click the close button. You do not need to use the above examples, you can simply do the follow.
    while (true)
    {
       // do something here
    }
    This is a very well know way to create an infinite loop, all the programmers understand this is a loop that wanted to be run forever. There are some usage of this, just take know of such a thing.

    Finally, let’s look at the do while loop at the last part. This loop is interesting because, even though the condition of the loop does not satisfy, it will still run for the first time. Let me give you a real world example, let say everyone can get a free cookies from the school’s café, and you can get more if you have a ticket, each ticket you have allow you to get one more cookie. So everyone get to the school café, the loop in this case, will get to run once.
    int ticket = 5; // the amount of cookie tickets they have
    do 
    {
       cout << "Give you a piece of cookie. " << endl;
       ticket--;
    } while (ticket >= 0);
    Note, this case the student will get 6 pieces of cookies. The first one that everybody gets just by showing up, and then 5 more cookies (from the exchange of tickets). There are many situations too, this is just one of the example I come up with. And plus who doesn’t like cookie? :9
    Note: This example has some problems, edit or remove before publish. 

    Practice Problem

    Write a program that will count from 0 to 10. The output should be like the following.
    0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10

    Sunday, December 12, 2010

    csci135c2.cpp

    A program is good for doing things thousands of times and accurately. What if we want repeat doing something many times? How should we program this? It is okay for us to type it out line by line if the number is small, but what if we want to write from 1 to 1000? We need some kind of looping function to do this!
    /*
     *  csci135c2a.cpp
     *  This program count from 1-20, by hand, typing it out one by one. It might
     *  taking a little bit longer time than using a loop. But let's try it out.
     *
     */
    
    #include <iostream>
    using namespace std;
    
    int main()
    {
        cout << "1 " << "2 " << "3 " << "4 " << "5 " << "6 " << "7 " << "8 " << "9 " 
             << "10 " << "11 " << "12 " << "13 " << "14 " << "15 " << "16 " << "17 " 
             << "18 " << "19 " << "20 " << endl;
        cout << "I am tired, we need to write a loop to do this." << endl;
        return 0;
    }
    Not only this takes a lot of time to write, but the size of this program is also much larger than what it will take if it is written in a loop. Now let's look at how to do it with a for loop, it require much less typing, and the chances of making a typo error is also much smaller. Remember what does int mean? (answer, int means integer, 0,1,2,3)
    /*
     *  csci135c2a.cpp
     *  This is the for loop version of the previous program, this is much easier
     *  to write a loop that count a few thousands time. Rather than writing it 
     *  line by line by hand. Just need to change the int i = x part.
     *
     */
    
    #include <iostream>
    using namespace std;
    
    int main()
    {
       // this the for loop, that count from 0 = 20, i+1 is the offset, because
       // this count from 0-19. But we want to print from 1-20, so offset is 1
       for (int i = 0; i <= 20; i++){
          cout << i+1;
       }
       cout << endl; // this is the space to skip to the next line
       cout << "I am tired, we need to write a loop to do this." << endl;
       return 0;
    }
    
    First we take a look at the structure of a "for" loop:
    for (set up counter; condition of the counter; counter adjustment){
       // do something here
    }
    In pain English, this can be view as the following: "for an integer start at 0, i is less or equal to 20, i plus plus. Then in the loop we can print the value of i (offset is 1 in this case)." Usually (for general usage), the counter will be an int, and it can be named anything you like. But a single letter i, j, k, will more popular, because it is also used as index for array and vector. But nothing is wrong with a name called "counter" too, the condition of the counter, there are many examples. i < 10, means it goes up to 9. i <= 10, means it goes to 10. As for the adjustment, you can let the counter count up to 10, or count down to 10. Both is correct usage depend on what you do, there is no right or wrong answer here.
    // Increment from 0 to 9 (total of 10 times)
    for (int i = 0;  i <= 10; i++)
    {
       // do something here
    }
    
    // Decrement from 10 - 0 (total of 10 times)
    for (int i = 10; i <= 0; i--)
    {
       // do something here
    }
    This two function will both execute the statement within 10 times. But to be sure, if you want to print out from 0-10, you need to do some adjustment to the decrement version. Because the counter i is going from 10 to 1, and if you want to print from 1 to 10, then you can do the following.
    // Print 0 to 10 in the decrementing fashion of for loop
    for (int i = 10; i <= 1; i--)
    {
       int number = 0; // declare a integer variable for displaying our value
       cout << number << endl;
       number++; // increment the printing number
    }
    Practice Problem:
    Write a program that display the first 10 odd number using the for loop, they should be in the same format as below. Separated by a comma. Tips: You can use the offset to display the odd number, try different offset and see what happen.
    1, 3, 5, 7, 9, 11, 13, 15, 17, 19

    Thursday, December 2, 2010

    Practice Solution for C1

    Write a program that print Good morning, Good afternoon, Good night in 3 separate lines. Tips, to go to next line, use endl. The output of the program should look like this.
    Good morning
    Good afternoon
    Good night
    The solution of the practice problem is below. If you type the keywords correctly, you should get the program to compile and finish in about 10 to 15 mins. The idea is to test if you know what does endl do. Test it out, try to see what happen if you don't add endl like we did in the solution. You will get everything on the same line.
    Good morningGood afternoonGoodnight
    So what you want to do is to add a space at the end of the each word, like below.
    cout << "Good morning " << "Good afternoon " << " Good night " << endl; 
    // output will be like this: Good morning Good afternoon Good night
    Finally, here is the solution to the question above. If you have any question, please feel free to email me or post question in the comment section below. Happy coding! :)
    /*
     *  csci135p1.cpp
     *  Solution to the practice, just make sure to type endl for the next line
     *
     */
    
    #include <iostream>
    using namespace std;
    
    int main()
    {
       cout << "Good morning" << endl;
       cout << "Good afternoon" << endl;
       cout << "Good night" << endl;
       return 0;
    }

    Wednesday, December 1, 2010

    csci135c1.cpp

    Since this is the first tutorial, and I am still trying to figure out my way of how to do this. Let's do a easy example, the well know "Hello World" example. This program will display a message to the terminal.
    /*
     *  csci135c1.cpp
     *  The classical program that display a message to the screen.
     *  The basic structure of the c++ program, and the main function.
     *
     */
    
    #include <iostream>
    using namespace std;
    
    int main()
    {
        cout << "Hello World! " << endl;
        cout << "I like programming, programming is fun. " << endl;
        return 0;
    }
    The first section of the code is the comment, there are a few ways to include comments in our source code. The first way is only for a single line, it seems to be the easiest way. It is useful for variable descriptions or function's comment. The second one is good for comments that is a few lines. But for the second way to display comment, please remember to end the comment with */. Or else it will give you a compiler error. Of course, you can go fancy with that method. But some of the professors might not like it. They might prefer the first way, just add // to every single line.
    // This is a comment
    
    /* This comment can
       be written over
       a few lines, just remember
       to close it! */
    
    /* 
     * Look at this
     * beautiful
     * comment style.
     *
     */
    
    // One line of comment
    // Another line of comment
    // You can type as many single lined comment as you want
    
    The first thing you see after the comment section will be the include statement, we will discuss it more in the later tutorial. For now just remember to type it when you want to do any kind of displaying messages, the include is to let the linker know I am including part of the codes from different header files. 
    #include <iostream>
    using namespace std;
    The main function's name... is called main. And int represents integer, therefore main function will return an integer. The integer is used to determine the state of the function, whether it is not working, it crash, or anything important the program is going to telling the operating system or user. Usually 0 means it is normal, and the rest other is considered to be not "normal". But what it returns is purely based on the what the programmer wants it to be. The meat of this program is the following line.
    cout << "Hello World! " << endl;
    cout means the stream that the data is sending to, << is called the insertion operator, it will send the data into the stream. And endl; is a symbol to let the program knows it is going to go to the next line. It is possible to link the input data like the following to create something like this. Notice the last example, show you how to control how many line to skip.
    cout << "Regular style, outputting message. " << endl;
    cout << "There " << "are " << "more " << "messages. " << endl;
    cout << "Let's skip 5 lines? " << endl << endl << endl << endl << endl;
    
    Thoughts: This first tutorial is a lot longer than what I thought it will be... I did not expect it to be so lengthy. most programmers can write this piece of code within 20 seconds, when trying to explain it without any prior knowledge is a different story. And I will have to double check the facts of my explanation.

    Practice Problem 1:
    Write a program that print Good morning, Good afternoon, Good night in 3 separate lines. Tips, to go to next line, use endl. The output of the program should look like this.
    Good morning
    Good afternoon
    Good night
    See here for solution

    csci135c1.cpp

    Since this is the first tutorial, and I am still trying to figure out my way of how to do this. Let's do a easy example, the well know "Hello World" example. This program will display a message to the terminal.
    /*
     *  csci135c1.cpp
     *  The classical program that display a message to the screen.
     *  The basic structure of the c++ program, and the main function.
     *
     */
    
    #include <iostream>
    using namespace std;
    
    int main()
    {
        cout << "Hello World! " << endl;
        cout << "I like programming, programming is fun. " << endl;
        return 0;
    }
    The first section of the code is the comment, there are a few ways to include comments in our source code. The first way is only for a single line, it seems to be the easiest way. It is useful for variable descriptions or function's comment. The second one is good for comments that is a few lines. But for the second way to display comment, please remember to end the comment with */. Or else it will give you a compiler error. Of course, you can go fancy with that method. But some of the professors might not like it. They might prefer the first way, just add // to every single line.
    // This is a comment
    
    /* This comment can
       be written over
       a few lines, just remember
       to close it! */
    
    /* 
     * Look at this
     * beautiful
     * comment style.
     *
     */
    
    // One line of comment
    // Another line of comment
    // You can type as many single lined comment as you want
    
    The first thing you see after the comment section will be the include statement, we will discuss it more in the later tutorial. For now just remember to type it when you want to do any kind of displaying messages, the include is to let the linker know I am including part of the codes from different header files. 
    #include <iostream>
    using namespace std;
    The main function's name... is called main. And int represents integer, therefore main function will return an integer. The integer is used to determine the state of the function, whether it is not working, it crash, or anything important the program is going to telling the operating system or user. Usually 0 means it is normal, and the rest other is considered to be not "normal". But what it returns is purely based on the what the programmer wants it to be. The meat of this program is the following line.
    cout << "Hello World! " << endl;
    cout means the stream that the data is sending to, << is called the insertion operator, it will send the data into the stream. And endl; is a symbol to let the program knows it is going to go to the next line. It is possible to link the input data like the following to create something like this. Notice the last example, show you how to control how many line to skip.
    cout << "Regular style, outputting message. " << endl;
    cout << "There " << "are " << "more " << "messages. " << endl;
    cout << "Let's skip 5 lines? " << endl << endl << endl << endl << endl;
    
    Thoughts: This first tutorial is a lot longer than what I thought it will be... I did not expect it to be so lengthy. most programmers can write this piece of code within 20 seconds, when trying to explain it without any prior knowledge is a different story. And I will have to double check the facts of my explanation.

    Practice Problem 1:
    Write a program that print Good morning, Good afternoon, Good night in 3 separate lines. Tips, to go to next line, use endl. The output of the program should look like this.
    Good morning
    Good afternoon
    Good night
    See here for solution

    Monday, November 29, 2010

    Textbook Resource

    • Small C++ How to Program (5th Edition) - the classroom textbook used in the csci135, I think most of the the 135s in hunter college used this book as well. I like this book, besides the interesting cover (with a microscope observing an ant buddy). It provide easy to understand explaining, and the colored coding highlight also help more easy understand of what the code is doing. However, I recommend not to get too attached to their use of spaces in between the loops.
      // This book like to add space everywhere
      if ( int i = 5 ) 
      // Compare to regular style
      if (int i = 5)
      
      I think it does not hurt to pick up a used copy, it is very user friendly, while it does not go into absolute details and provide all the c reference like other books do, I think it is very straight forward.
      • Brand New: $71.40
      • Used (condition like new): $19.08

    • C++ Primer Plus (5th Edition) - a well known favorite introduction textbook that many C++ programmer read at least a few times. It goes into great detail of explaining everything in length. It fills all the holes left out in the small C++ textbook, granted, this book is about 2-3 times as big as this book. I think this book is a must read for all student who completed csci135, preferably in the winter or summer break, about 40% of the things will be a review. But there are a lot of other details and area is new, highly highly recommended. And the cost of this book is cheap, pick up one please. This book also gives you a great deal of exposure to all the topics in csci135 that the classroom does not cover fully. (It is not the class's fault, we only met twice a week for 1 hour and 15 mins, the professors only have time to cover the basics). Great read, great read.
      • Brand New: $37.79
      • Used (condition like new): $29.99

    • Saad's notes -  this is sometimes referred as notes, but it is almost a fully length ready to go textbook in my opinion. It is written by professor saad from hunter college. If you ever happened to find out he is teaching it. Please consider take it, it will be difficult, but it will be well worth your time. It is not an easy A by any mean, but, you will learn a lot. This book is written in very condensed fashion, by condense I mean he skips the un-needed material and left with only the interesting and useful examples. Moreover, this book has a lot of c reference. It does a great job of exposing student to read c code. A lot of student who called themselves programmer, yes, they are very good at c++ programming, but they can not read c code. Which is a real problem when we are looking for a job, you need to understand them.
      // C string examples from p.100 of the book.pdf
      int main() {
         char s[6]={'h','e','l','l','o','\0'};
         s[0]='b'; //ok at compile time and run-time
      }
      • Brand New: Free
      • Used (condition like new): Print it out maybe costing you a few dollars