Showing posts with label Tutorial. Show all posts
Showing posts with label Tutorial. Show all posts

Thursday, May 31, 2012

Blog Index

I have been writing tutorials and posting different projects for a while now, I decided to write an index for easy look up for the different post. They are divided to a few section as the follow. I hope you can find what you are looking for, if not, try to use the search feature located in the lower right side. If you have an question, please feel free to email me or leave me a message in the comment.

Python Tutorial
  • Python Reference
    A list of useful website and textbook review
  • csci133c1.py
  • Basic Hello World, declare variables, simple for loop control statement
  • csci133c2.py
  • Nested for loops, list, counting, if statement
  • csci133c3.py
  • Introduction to function, string's class function, useful tip for handling string
  • csci133c4.py
  • Opening a file, and using everything we know together. Additional to a brief review practice problem, introduce dictionary
  • csci133c5.py
    Talks about function, what are they, how to define them
  • csci133c6.py
    A taste of python's GUI, Tkinter. Introducing the title, frame, button, input widget, and what they can do with each other
  • csci133buildin.py
    Discuss what are the build-in data type (Object) in Python
  • csci133number.py
    Document Integer, Float, Long, and Complex number
  • csci133class.py
    Some notes I have on python's class, tkinter's other module
  • csci133ifelif
    Demonstration of the uses of if and elif (else-if) keyword
  • csci133c7.py
    Classic how to clean up a string and storing the string's corresponding line numbers, it discuss the use all the things we learned so far
  • csci133c8.py
    Some notes on the python's class, and subclass too
  • csci133allCombination.py
    Example of why nest while loop is bad, and how to use one if you really must have it. Plus counter solutions.
  • csci133rep1.py
    An example of how to validate input of telephone number in a specific format, demonstrating simple use of regular expression in python.
  • csci133averageGPA.py
    Simple exercise program to calculate the grade point average
  • csci133rockPaperScissors.py
    A game of rock, paper, scissor implemented in python
  • csci133clock.py
    An example of how to make a clock with tkinter in Python
  • csci133timer.py
    A tutorial on how to build a timer with tkinter in Python

Stackoverflow Goodies


C++ Tutorial

Tuesday, May 22, 2012

Python: How to make a stop watch timer using tkinter

First thing we have to understand is how the time actually work. If you do, you can skip ahead to the next section. I was not completely sure how the time work. I confirmed from the search on google and here is what it said.

1 min = 60 seconds 1 seconds = 100 centiseconds


We use the similar code as the Clock, there is a Lable (a textbox) called timeText, and we will update it every 1 centisecond, and increment our time sturcture by 1 as well. Take a look at the way it is designed.
# timer is a list of integer, in the following order
timer = [minutes, seconds, centiseconds]
Notice in the actual code it is initialized to 0,0,0. But it then created a problem of not being show as 00:00:00 as a normal stop watch would. One way to get around this is to use the string's format.() function.
pattern = '{0:02d}:{1:02d}:{2:02d}'
timeString = pattern.format(timer[0], timer[1], timer[2])

{0:02d}, the first 0 means which parameter in the format() function call, 02d means, it is expecting an integer of length 2, the 02 means it is padding with leading zeros infront of it. Take note of this feature, as it is really powerful, you can mix and match different parameters, instead of {0} {1} {2}, you can do creative things like {2} {1} {1} {2} {0}, (such as different order, multiple use of the same varaible, etc).



The following program contains 4 buttons (start, pause, reset, quit). Which they do what they are named after respectly. The reset function work both running and paused clock. Maybe it is a good idea to add a time lap feature?

import Tkinter as tk

# Note: Python 2.6 or higher is required for .format() to work
def update_timeText():
    if (state):
        global timer
        # Every time this function is called, 
        # we will increment 1 centisecond (1/100 of a second)
        timer[2] += 1
        
        # Every 100 centisecond is equal to 1 second
        if (timer[2] >= 100):
            timer[2] = 0
            timer[1] += 1
        # Every 60 seconds is equal to 1 min
        if (timer[1] >= 60):
            timer[0] += 1
            timer[1] = 0
        # We create our time string here
        timeString = pattern.format(timer[0], timer[1], timer[2])
        # Update the timeText Label box with the current time
        timeText.configure(text=timeString)
        # Call the update_timeText() function after 1 centisecond
    root.after(10, update_timeText)

# To start the kitchen timer
def start():
    global state
    state = True

# To pause the kitchen timer
def pause():
    global state
    state = False

# To reset the timer to 00:00:00
def reset():
    global timer
    timer = [0, 0, 0]
    timeText.configure(text='00:00:00')

# To exist our program
def exist():
    root.destroy()

# Simple status flag
# False mean the timer is not running
# True means the timer is running (counting)
state = False

root = tk.Tk()
root.wm_title('Simple Kitchen Timer Example')

# Our time structure [min, sec, centsec]
timer = [0, 0, 0]
# The format is padding all the 
pattern = '{0:02d}:{1:02d}:{2:02d}'

# Create a timeText Label (a text box)
timeText = tk.Label(root, text="00:00:00", font=("Helvetica", 150))
timeText.pack()

startButton = tk.Button(root, text='Start', command=start)
startButton.pack()

pauseButton = tk.Button(root, text='Pause', command=pause)
pauseButton.pack()

resetButton = tk.Button(root, text='Reset', command=reset)
resetButton.pack()

quitButton = tk.Button(root, text='Quit', command=exist)
quitButton.pack()

update_timeText()
root.mainloop()

Python: How to make a clock in tkinter using time.strftime

This is a tutorial on how to create a clock / Timer using tkinter in Python, note you might have to change Tkinter to tkinter depending on your version of the Python you have. I am using Python 3.2 at the moment. The code itself is quite simple, the only part you need to know is how to get the current time, using time.strftime. You can also get the day of the week, the current month, etc, by changing the parameter you are supplying the function. (See the link for the full table of possible options). But yes, almost anything you can think of any use of, it is there already. :) So this can actual be developed to a calendar like GUI.

Related Tutorial with source code
Stop watch GUI (for counting time): http://ygchan.blogspot.com/2012/05/python-stop-watch-timer-source-code.html


import Tkinter as tk
import time

def update_timeText():
    # Get the current time, note you can change the format as you wish
    current = time.strftime("%H:%M:%S")
    # Update the timeText Label box with the current time
    timeText.configure(text=current)
    # Call the update_timeText() function after 1 second
    root.after(1000, update_timeText)

root = tk.Tk()
root.wm_title("Simple Clock Example")

# Create a timeText Label (a text box)
timeText = tk.Label(root, text="", font=("Helvetica", 150))
timeText.pack()
update_timeText()
root.mainloop()
Reference: http://docs.python.org/library/time.html#time.strftime
Reference: http://docs.python.org/library/string.html#formatstrings

Saturday, April 7, 2012

Python: How to find the integer and float in a string

Reference: http://stackoverflow.com/a/10059001/1276534
Credits: MellowFellow, hexparrot

If you have a string from somewhere, say a textbook, or an input. The string contain the data information you need. How do you extract the string? There are quite a few way to do it, range from hard code accessing it from index, to finding the E=, to using regular expression. In this example we will go over the middle of the range one. Because as beginner, it might not be the best idea to introduce regular expression yet. Plus this is the version I understand, maybe the regular expression version will be provided soon. (If you can't wait, you can check out from the reference link from above, there is the regular expression solution as well.)
# Assume you get this string from either a file or input from user
text_string = 'The voltage is E=500V and the current is I=6.5A'

# The starting index of this locating the voltage pattern
voltage_begin = text_string.find('E=')
# The ending index, note we are ending at 'V'
voltage_end = text_string.find('V', voltage_begin)

voltage_string = text_string[voltage_begin:voltage_end]
print(voltage_string, 'is at index:', voltage_begin, voltage_end)

#Since we know about the first to index is not useful to us
voltage_string = text_string[voltage_begin+2:voltage_end]

# So since now we have the exact string we want, we can cast it to an integer
voltage_as_int = int(voltage_string)
print(voltage_as_int)

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