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