tag:blogger.com,1999:blog-2872689247830974902024-03-12T16:10:24.471-07:00George Chan's BlogMy notes on Python and C++, import this.Unknownnoreply@blogger.comBlogger41125tag:blogger.com,1999:blog-287268924783097490.post-79960061915187737412013-06-30T05:12:00.001-07:002013-06-30T05:32:51.844-07:00Java: Rock, Paper, Scissor Game Source CodeThis is the source code for how to implement a rock, paper, scissor game in JAVA. It has a swing GUI interface (using JOptionPane) that prompt the user for input.<br /><br>
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEi7kBdaKcfMu5_tDcHhATyAffirnZb1mUQ5tdy8BHLGYBIUKjyKCNLcyHVUceos9CgtW-aumyArhII_UqHT-_9MWWXPZi6XSO915AKWjf7WdgIILwe8E3fWLblnQ0_HKVifYoKRepHwXbw/s393/Untitled.tiff" imageanchor="1" ><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEi7kBdaKcfMu5_tDcHhATyAffirnZb1mUQ5tdy8BHLGYBIUKjyKCNLcyHVUceos9CgtW-aumyArhII_UqHT-_9MWWXPZi6XSO915AKWjf7WdgIILwe8E3fWLblnQ0_HKVifYoKRepHwXbw/s393/Untitled.tiff" /></a>
<pre class="brush: java">
// A game that plays rock paper scissor with user
import javax.swing.JOptionPane;
public class GameRockPaperScissor {
public static void main(String[] args) {
// Prompt the user to input the option they choose
String humanInput = JOptionPane.showInputDialog(
"Enter rock, paper, or scissor:");
// Convert to lower case
humanInput = humanInput.toLowerCase();
// Generate a random number
// Scissor (0), rock (1), paper (2)
int random = (int)(Math.random() * 3);
String computerInput; // Computer's choice
if (random == 0)
computerInput = "rock";
else if (random == 1)
computerInput = "paper";
else
computerInput = "scissor";
String message = "The computer is " + computerInput + ". You are "
+ humanInput;
// Determine who win
boolean isTie = computerInput.equals(humanInput);
boolean isWin =
((computerInput.equals("rock") && humanInput.equals("scissor")) ||
(computerInput.equals("paper") && humanInput.equals("rock")) ||
(computerInput.equals("scissor") && humanInput.equals("paper")));
// Prepare the message
if (isWin)
message += ". Computer Won.";
else if (isTie)
message += " too. It is Tie";
// There are 3 options, computer win, tie, or you win
// So we don't have to test here, if the code reach here, human win.
else
message += ". You Won";
// Display the result on the screen
JOptionPane.showMessageDialog(null, message);
}
}</pre>Unknownnoreply@blogger.com2tag:blogger.com,1999:blog-287268924783097490.post-72396967164134879882012-05-31T09:48:00.000-07:002012-05-23T17:21:38.391-07:00Blog IndexI 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.<br />
<br />
<span style="font-size: small;"><b>Python Tutorial </b></span><br />
<ul>
<li><a href="http://ygchan.blogspot.com/2012/01/python-reference-link.html">Python Reference</a><br />
A list of useful website and textbook review</li>
<li><a href="http://ygchan.blogspot.com/2012/03/csci133apy.html">csci133c1.py </a></li>
Basic Hello World, declare variables, simple for loop control statement
<li><a href="http://ygchan.blogspot.com/2012/03/csci133c2py.html">csci133c2.py</a></li>
Nested for loops, list, counting, if statement
<li><a href="http://ygchan.blogspot.com/2012/03/csci133c3py.html">csci133c3.py</a></li>
Introduction to function, string's class function, useful tip for handling string
<li><a href="http://ygchan.blogspot.com/2012/03/csci133c4py.html">csci133c4.py </a></li>
Opening a file, and using everything we know together. Additional to a brief review practice problem, introduce dictionary
<li><a href="http://ygchan.blogspot.com/2012/03/csci133p5py.html">csci133c5.py </a><br />
Talks about function, what are they, how to define them </li>
<li><a href="http://ygchan.blogspot.com/2012/03/csci133p5py.html">csci133c6.py </a><br />
A taste of python's GUI, Tkinter. Introducing the title, frame, button, input widget, and what they can do with each other</li>
<li><a href="http://ygchan.blogspot.com/2012/03/pythons-build-in-types.html">csci133buildin.py</a><br />
Discuss what are the build-in data type (Object) in Python</li>
<li><a href="http://csci133number.py/">csci133number.py</a><br />
Document Integer, Float, Long, and Complex number</li>
<li><a href="http://csci133number.py/">csci133class.py</a><br />
Some notes I have on python's class, tkinter's other module</li>
<li><a href="http://ygchan.blogspot.com/2012/03/pythons-if-vs-elif.html">csci133ifelif</a><br />
Demonstration of the uses of if and elif (else-if) keyword</li>
<li><a href="http://ygchan.blogspot.com/2012/03/csci133cleanuppy.html">csci133c7.py </a><br />
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</li>
<li><a href="http://ygchan.blogspot.com/2012/01/notes.html">csci133c8.py </a><br />
Some notes on the python's class, and subclass too</li>
<li><a href="http://ygchan.blogspot.com/2012/03/pythons-nested-while-loop-in-c-style.html">csci133allCombination.py</a><br />
Example of why nest while loop is bad, and how to use one if you really must have it. Plus counter solutions.</li>
<li><a href="http://ygchan.blogspot.com/2012/03/python-regular-expression-101-example.html">csci133rep1.py</a><br />
An example of how to validate input of telephone number in a specific format, demonstrating simple use of regular expression in python.</li>
<li><a href="http://ygchan.blogspot.com/2012/04/python-calculate-grade-point-average.html">csci133averageGPA.py</a><br />
Simple exercise program to calculate the grade point average</li>
<li><a href="http://csci133rockpaperscissors.py/">csci133rockPaperScissors.py</a><br />A game of rock, paper, scissor implemented in python</li>
<li><a href="http://ygchan.blogspot.com/2012/05/python-how-to-make-clock-timer-in.html">csci133clock.py</a><br />An example of how to make a clock with tkinter in Python</li>
<li><a href="http://ygchan.blogspot.com/2012/05/python-stop-watch-timer-source-code.html">csci133timer.py</a><br />A tutorial on how to build a timer with tkinter in Python</li>
</ul>
<br />
<h3>
<b>Stackoverflow Goodies</b></h3>
<ul>
<li><a href="http://ygchan.blogspot.com/2012/03/python-get-most-frequent-elements-from.html">Python: Get the most frequent elements from list when there is more than one</a><br />
Given a list that is unsorted, how do you get the most frequent appeared element?</li>
<li><a href="http://ygchan.blogspot.com/2012/03/python-regular-expression-101-example.html">Python: Regular Expression 101 Example Code</a><br />
A very simple demonstration of Python's Regular Expression, in particular, how to validate if a telephone number is in the format we want xxx-xxx-xxxx</li>
<li><a href="python:%20How%20to%20print%20the%20ValueError%20Error%20Message">Python: How to print the ValueError Error Message</a><br />
It is actually better to expect error than to test them out</li>
<li><a href="http://ygchan.blogspot.com/2012/04/python-vs-vs.html">Python: [] vs. {} vs. ()</a><br />
A flash card for: list vs. dictionary / set vs. tuple</li>
<li><a href="http://ygchan.blogspot.com/2012/04/python-tkinter-how-to-set-window-size.html">Python Tkinter: How to change window size without using canvas</a><br />
Use the .pack_propagate() method to change the flag</li>
<li><a href="python:%20When%20NOT%20To%20use%20Global%20Variable,%20Use%20Return%21">Python: When NOT To use Global Variable, Use Return!</a><br />
Why you might not want to use global variable all the time, and what do you do with returned values.</li>
<li><a href="http://ygchan.blogspot.com/2012/04/python-how-to-remove-or-pop-element.html">Python: How to remove, or pop an element randomly from a list</a><br />
Use randrange() instead of random.choice(range(myList))</li>
<li><a href="http://ygchan.blogspot.com/2012/04/python-how-to-search-list-of-class.html">Python: How to search a list of class element by their data</a><br />
Put the _classVariable into a dictinoary {} into your class</li>
<li><a href="http://ygchan.blogspot.com/2012/04/python-how-to-find-integer-and-float-in.html">Python: How to find the integer and float in a string</a><br />
If you given a string in the form of an equation, how to extract the integer and float from the string. Beginner style! No regular expression used. </li>
<li><a href="http://ygchan.blogspot.com/2012/04/python-how-to-insert-characters-to.html">Python: How to insert characters to the string at the end</a><br />
Example of 3 different way you can insert some characters into the string</li>
<li><a href="http://ygchan.blogspot.com/2012/05/python-how-to-load-image-to-tkinter.html">Python: How to load image to tkinter window example (GIF only)</a><br />Example to how to load an image and display on the tkinter</li>
<li><br />
</li>
</ul>
<br />
<b><span style="font-size: small;">C++ Tutorial </span></b><br />
<ul>
<li><a href="http://ygchan.blogspot.com/2010/11/textbook-resource.html">C++ Resource</a></li>
Discussion about what are the good reference for the class
<li><a href="http://ygchan.blogspot.com/2011/03/csci135c1cpp_19.html">csci135c1.cpp</a></li>
Hello world, talks about cout and endl
<li><a href="http://ygchan.blogspot.com/2010/12/csci135c2cpp.html">csci135c2.cpp</a></li>
More cout, and for loop
<li><a href="http://ygchan.blogspot.com/2010/12/csci135c3cpp.html">csci135c3.cpp </a></li>
while loops and do while loop tutorial in great details </ul>Unknownnoreply@blogger.com0tag:blogger.com,1999:blog-287268924783097490.post-80619961124899718712012-05-22T16:26:00.007-07:002012-05-24T21:55:38.490-07:00Python: How to make a stop watch timer using tkinterFirst 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. <br />
<br />
<h3>1 min = 60 seconds 1 seconds = 100 centiseconds </h3><br />
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. <br />
<pre class="brush: python"># timer is a list of integer, in the following order
timer = [minutes, seconds, centiseconds]
</pre>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. <br />
<pre class="brush: python">pattern = '{0:02d}:{1:02d}:{2:02d}'
timeString = pattern.format(timer[0], timer[1], timer[2])
</pre>{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). <br />
<br />
<img border="0" height="211" width="400" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEg4VoLBkaYsh6bSL3pYgHLZvERVp0L4EJF3cL8EXGznx1rVDXuVVst4PgEp1sPWf-YYx7CVn04-DGZXxUGwiW3wwo8D5gGuiTB7WcOVOrPgNwehH5BmdXYiG_Hx3MDI2x7iOIwTy24Ivlw/s400/Screen+Shot+2012-05-25+at+12.49.15+AM.png" /><br />
<br />
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?<br />
<br />
<pre class="brush: python">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()
</pre>Unknownnoreply@blogger.com9tag:blogger.com,1999:blog-287268924783097490.post-20263007633362355902012-05-22T07:41:00.001-07:002012-05-23T17:20:14.406-07:00Python: How to make a clock in tkinter using time.strftimeThis 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 <a href="http://docs.python.org/library/time.html#time.strftime">time.strftime</a>. 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.<br />
<br />
Related Tutorial with source code<br />
Stop watch GUI (for counting time): <a href="http://ygchan.blogspot.com/2012/05/python-stop-watch-timer-source-code.html">http://ygchan.blogspot.com/2012/05/python-stop-watch-timer-source-code.html</a><br />
<br />
<img border="0" height="121" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjXIsLWEn4GHA8Rg3MkbYOSQEcuJZrj5nNQQaSmRN0wNc-fYEvOFU_QSEXmw9PRuNyRbuxvjLW-97tRuzbOQzHLXuAKrryn6e0b4191RIqH4SjJM1Q0Ihmx_r3MsLAv-Mr1ultikQCb5Is/s400/clock.png" width="400" />
<br />
<pre class="brush: python">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()
</pre>
<b>Reference: </b><a href="http://docs.python.org/library/time.html#time.strftime">http://docs.python.org/library/time.html#time.strftime</a><br />
<b>Reference: </b><a href="http://docs.python.org/library/string.html#formatstrings">http://docs.python.org/library/string.html#formatstrings</a>Unknownnoreply@blogger.com3tag:blogger.com,1999:blog-287268924783097490.post-86346652911536913642012-05-20T11:57:00.000-07:002012-05-20T12:04:51.915-07:00Python: How to load and display an image (GIF) in tkinter<div class="separator" style="clear: both; text-align: center;">
<a href="http://i.stack.imgur.com/trwQs.png" imageanchor="1" style="clear: left; float: left; margin-bottom: 1em; margin-right: 1em;"><img border="0" src="http://i.stack.imgur.com/trwQs.png" /></a></div>
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
Reference: <a href="http://stackoverflow.com/q/10675551/1276534">http://stackoverflow.com/q/10675551/1276534 </a><br />
Credits: <a href="http://stackoverflow.com/users/1194629/mg">mg_</a>, <a href="http://stackoverflow.com/users/1378811/carlos">Carlos</a>, <a href="http://stackoverflow.com/users/1276534/george">George</a>, <a href="http://stackoverflow.com/users/7432/bryan-oakley">Bryan Oakley</a><br />
<br />
This is a simple code that get the input from the <code>inputBox</code> to <code>myText,</code> and also display a picture (gif only) to the tkinter window. Depending on what
else you need to check or do, you can add more functions to it. Notice
you might have to play around with the order of the line <code>image = tk.PhotoImage(data=b64_data)</code>. Because if you put it right after <code>b64_data = ...</code>.
It will gives you error. See reference at the
bottom if you want to learn more.<br />
<br />
<pre class="brush: python">import tkinter as tk
import urllib.request
import base64
# Download the image using urllib
URL = "http://www.contentmanagement365.com/Content/Exhibition6/Files/369a0147-0853-4bb0-85ff-c1beda37c3db/apple_logo_50x50.gif"
u = urllib.request.urlopen(URL)
raw_data = u.read()
u.close()
b64_data = base64.encodestring(raw_data)
# The string you want to returned is somewhere outside
myText = 'empty'
def getText():
global myText
# You can perform check on some condition if you want to
# If it is okay, then store the value, and exist
myText = inputBox.get()
print('User Entered:', myText)
root.destroy()
root = tk.Tk()
# Just a simple title
simpleTitle = tk.Label(root)
simpleTitle['text'] = 'Please enter your input here'
simpleTitle.pack()
# The image (but in the label widget)
image = tk.PhotoImage(data=b64_data)
imageLabel = tk.Label(image=image)
imageLabel.pack()
# The entry box widget
inputBox = tk.Entry(root)
inputBox.pack()
# The button widget
button = tk.Button(root, text='Submit', command=getText)
button.pack()
tk.mainloop()
</pre>
<br />
Here is the reference if you want to know more about the Tkinter Entry Widget: <a href="http://effbot.org/tkinterbook/entry.htm" rel="nofollow">http://effbot.org/tkinterbook/entry.htm</a><br />
Reference on how to get the image: <a href="http://stackoverflow.com/questions/6086262/python-3-how-to-retrieve-an-image-from-the-web-and-display-in-a-gui-using-tkint">Stackoverflow Question</a>Unknownnoreply@blogger.com3tag:blogger.com,1999:blog-287268924783097490.post-83618118836475103342012-05-11T12:52:00.000-07:002012-05-23T14:49:41.402-07:00Python: Rock, Paper, Scissor Game Source CodeI implemented a simple game of rock, paper, scissors game in python as a after school project. The game itself is really simple, not that I need to. But I pay a quick visit to wiki's page, and read through it. The original program has a long list of if statement, but as I was thinking through it, it comes to me quickly, that you actually does not need to have that many control statement, just three is enough. Since there is only three possible outcome.<br />
<br />
<b>The logic goes like this:</b><br />
<ol>
<li>If you and the computer's outcome (choice) is the same, then you are tie. Regardless of what kind of choice you or your computer made. A tie is a tie. </li>
<li>Then there is 3 possible ways you can win. </li>
<ol>
<li>You are Rock, computer is Scissors</li>
<li>You are Paper, computer is Rock</li>
<li>You are Scissors, computer is Paper </li>
</ol>
<li>If you didn't tie, and you didn't win, your only option is to lose the game. </li>
</ol>
You can easily put a while (myResponse is not 'quit') loop, and have this game goes on forever.
Below is the source code for the game. I found out I win quite often... for what ever reason.<br />
<br />
<pre class="brush: python"># Hunter College CSCI133 Python Project
# Rock Paper Scissors Game Source code in Python
# Implemented by George Chan, 5/2/2012
# Email: ygchan89@gmail.com
# A simple game to play rock, paper, scissors with the computer
import random
# Create the list of of choices, which stored at string
gameChoices = ['rock', 'paper', 'scissors']
# Our default ready flag is false
ready = False
print('rock, paper, scissors Game!')
while (not ready):
myResponse = raw_input('Please enter which option you are going with: ')
myResponse = myResponse.lower()
# We will change our flag to true and break out of the loop
# if and only if the input is equiv to one of our choices
if (myResponse in gameChoices):
ready = True
# Randomly pick a choice from the list gameChoices
computerResponse = random.choice(gameChoices)
print('Computer picked:', computerResponse)
# There are three possible condition of the game, either you tie,
# with the computer or you win, else you lose
# Tie condition is when you and computer choice is the same
if (myResponse == computerResponse):
print('Tie Game')
# Win condition is the below three possible one
elif (myResponse == 'rock' and computerResponse == 'scissors' or
myResponse == 'paper' and computerResponse == 'rock' or
myResponse == 'scissors' and computerResponse == 'paper'):
print('You win')
# If you didn't tie, didn't win, then you must lose
else:
print('You lose!')
</pre>
Sample Output:
<br />
<pre class="brush: python">rock, paper, scissors Game!
Please enter which option you are going with: rock
('Computer picked:', 'rock')
Tie Game
rock, paper, scissors Game!
Please enter which option you are going with: rock
('Computer picked:', 'scissors')
You win
</pre>Unknownnoreply@blogger.com0tag:blogger.com,1999:blog-287268924783097490.post-24350219354433279292012-04-07T18:15:00.003-07:002012-04-23T09:46:55.077-07:00Python: How to insert characters to the string at the endReference: <a href="http://stackoverflow.com/q/10059554/1276534">http://stackoverflow.com/q/10059554/1276534</a><br />
Credits: <a href="http://stackoverflow.com/users/1319219/user1319219">user1319219</a>, <a href="http://stackoverflow.com/users/1078084/akavall">Akavall</a>, <a href="http://stackoverflow.com/users/61974/mark-byers">Mark Byers</a><br />
<br />
Just in case you wondering what are the ways to insert character to the string at the front or back (beginning or end) of a string. Here are the ways to do it. Notice, string is immutable object, so you can not insert anymore characters into it. All we are doing is create a new string, and assign it to the variable. (That's why I did not use the same name, because I want to emphasize they are NOT the same string). But you can just as well use text = (any method)<br />
<br />
<pre class="brush: python"># Create a new string that have 1 x in the beginning, and 2 x at the end
# So I want the string to look like this 'xHello Pythonxx'
text = 'Hello Python'
# Method 1, string concatenation
new_text = 'x' + text + 'xx'
# Method 2, create a new string with math operators
i = 1
j = 2
new_text = ('x'*i) + text + ('x'*j)
# Method 3, use the string's join() method
# You are actually joining the 3 part into a originally empty string
new_text = ''.join(('x', text, 'xx'))
</pre>And in case you don't trust me and want to see the output:<br />
<pre class="brush: js">xHello Pythonxx
xHello Pythonxx
xHello Pythonxx
</pre>Unknownnoreply@blogger.com1tag:blogger.com,1999:blog-287268924783097490.post-56994539728550042472012-04-07T17:57:00.002-07:002012-04-07T17:59:46.753-07:00Python: How to find the integer and float in a stringReference: <a href="http://stackoverflow.com/a/10059001/1276534">http://stackoverflow.com/a/10059001/1276534</a><br />
Credits: <a href="http://stackoverflow.com/users/1289410/mellowfellow">MellowFellow</a>, <a href="http://stackoverflow.com/users/1191579/hexparrot">hexparrot</a><br />
<br />
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.)<br />
<pre class="brush: python"># 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)
</pre>Unknownnoreply@blogger.com0tag:blogger.com,1999:blog-287268924783097490.post-25117155137637243382012-04-07T00:45:00.003-07:002012-04-07T09:27:07.223-07:00Python: How to search a list of class element by their data (self.name) variableReference: <a href="http://stackoverflow.com/q/10052322/1276534">http://stackoverflow.com/q/10052322/1276534</a><br />
Credits: <a href="http://stackoverflow.com/users/1257953/nitin">nitin</a>, <a href="http://stackoverflow.com/users/416467/kindall">kindall</a><br />
<br />
Imagine you have a class of Food, and you want to create a list that store your class of Food. How do you search your class element within your list? Take a look at the code.<br />
<pre class="brush: python">class Food:
def __init__(self, name):
self.name = name
chicken = Food('Egg')
cow = Food('Beef')
potato = Food('French Fries')
# And then you create the list of food?
myFoodList = [chicken, cow, potato]
</pre>The way you want to implement your class so you can search through them by their name variable is done via dictionary. (This is one way to do it, set also might work depend on your class's implementation and required functionality). <br />
<pre class="brush: python">class Food:
lookup = {}
def __init__(self, name):
self.name = name
Food.lookup[name] = self
chicken = Food('Egg')
cow = Food('Beef')
potato = Food('French Fries')
# Example of a lookup from the dictionary
# If your name is in your class Food's lookup dictionary
if 'Egg' in Food.lookup:
# Do something that you want
print (Food.lookup['Egg'].name)
</pre>Unknownnoreply@blogger.com0tag:blogger.com,1999:blog-287268924783097490.post-21510580569531024842012-04-06T12:32:00.005-07:002012-04-06T12:50:16.995-07:00Python: How to remove, or pop an element randomly from a listReference: <a href="http://stackoverflow.com/q/10048069/1276534">http://stackoverflow.com/q/10048069/1276534</a><br />
Credit: <a href="http://stackoverflow.com/users/289572/henrik">Henrik</a>, <a href="http://stackoverflow.com/users/505154/f-j">F.J</a>, <a href="http://stackoverflow.com/users/201359/oscar-lopez">Óscar López</a>, <a href="http://stackoverflow.com/users/916657/niklas-b">Niklas B.</a><br />
<br />
Assuming you want to randomly remove an element from your list, you can use the random module, to generate a random number, between the valid index in your list. Take a look at the code below.<br />
<pre class="brush: python"># Import the random module
import random
# This is your list with some number
# But you can of course have anything you in your list
myList = [1, 3, 5, 7, 9, 11]
# Method #1
myList.pop(random.randrange(len(myList)))
# Method #2 (This one will change your list)
random.shuffle(myList)
# While my list is not empty
while myList:
myList.pop
</pre><br />
(Method 1) Let's studying this code from the inner to the outer layer. <br />
<ol><li>We get the length of the list, with my len(myList)</li>
<li>Then we call randrange(), what randrange does it return a number that is pick randomly between the range we provide it. But except we do not actually create this list. Like range() would.</li>
<li>Then finally we pop it from our list.</li>
</ol>(Method 2) This will be good, if you want to use your list all together, instead of just popping one element. This is used in the csci133 example in the playing deck, since you have to shuffle your whole deck and then pick 1 card at a time. It make sense to have it shuffled. <br />
<ol></ol>Unknownnoreply@blogger.com1tag:blogger.com,1999:blog-287268924783097490.post-87372600614342322902012-04-05T16:48:00.007-07:002012-04-06T12:38:18.017-07:00Python: When NOT To use Global Variable, Use Return!Reference: <a href="http://stackoverflow.com/questions/10036747/global-variable-cant-be-assigned-in-python/10037052#10037052">http://stackoverflow.com/q/10036747/1276534</a><br />
Credit: <a href="http://stackoverflow.com/users/1316367/ricky">Ricky</a>, <a href="http://stackoverflow.com/users/496445/jdi">jdi</a>, <a href="http://stackoverflow.com/users/538990/maty">Maty</a><br />
<br />
Using global variable in your Python function is really easy, but today I read a post that explain why not to use it. And I found it make a lot of sense, I am not used to write without the <i>pass by reference</i>. Take a look at this code below.<br />
<pre class="brush: python">def getSalary():
global a, b, c
a = input("Please enter the boss's salary")
b = input("Please enter the director's salary")
c = input("Please enter the factory worker's salary")
</pre><br />
Notice this function, it asks the user for 3 different salary and store them in a, b, c respectively. But it is not a good practice, instead we should use the return function.<br />
<br />
<pre class="brush: python">def getSalary():
a = input("Please enter the boss's salary")
b = input("Please enter the director's salary")
c = input("Please enter the factory worker's salary")
return a, b, c
# And to way to use this function is like
a, b, c = getSalary()
</pre>This make the code a lot more readable, and useable. Imagine if you make a mistake in the program, if you use global variable, you will have a very hard time tracking where exactly does your value get changed. While doing it the second method, you will know a, b, c is changed on the getSalary line's return. And you can print them as you writing your program to debug it.<br />
<br />
And as jdi pointed out, it is always always better to use more meaningful variable name than a,b,c,d, or x,y,z. Imagine you use bossSalary, directorSalary, factoryWorkerSalary, the code is a lot easier to understand. Granted, maybe a little bit long. But maybe you can use workerSalary at least!<br />
<br />
And when you have a function that modify your object, such as your own class, a list. Maybe (depending on the situation), you might want to create a new variable and assign it, or you can overwrite it too!<br />
<pre class="brush: python">def newSalary(salary):
return salary + salary * 0.02
# Use it like this
nextYearSalary = newSalary(salary)
# Or overwrite the old one
mySalary = newSalary(salary)
</pre>Unknownnoreply@blogger.com0tag:blogger.com,1999:blog-287268924783097490.post-5995047756380466022012-04-03T16:27:00.003-07:002012-04-03T16:29:30.491-07:00Python: How to print the ValueError Error Message<pre class="brush: js">try:
...
except ValueError as e:
print(e)
</pre>Unknownnoreply@blogger.com0tag:blogger.com,1999:blog-287268924783097490.post-3528229545643474742012-04-03T08:50:00.010-07:002012-04-06T12:38:35.265-07:00Python Tkinter: How to set the window size without using canvasReference: <a href="http://stackoverflow.com/q/9996599/1276534">http://stackoverflow.com/q/9996599/1276534</a><br />
Credit: <a href="http://stackoverflow.com/users/1276534/george">George</a>, <a href="http://stackoverflow.com/users/7432/bryan-oakley">Bryan Oakley</a><br />
<br />
Here is the code on how to set the window size without using canvas, it is great if you just starting, or do not want to use canvas to do this. You can specify your dimension in your frame, and then use pack_progate(0) flag to tell tkinter to use your size. <br />
<pre class="brush: python">import tkinter as tk
root = tk.Tk()
frame = tk.Frame(root, width=400, height=400)
frame.pack_propagate(0) # set the flag to use the size
frame.pack() # remember to pack it or else it will not be pack
textBox = tk.Label(frame, text="(x,y): ")
textBox.pack()
root.mainloop()
</pre>Note: If your frame is not big enough to how the items, it will expand to fit your items). And the pack_progate(0) is a flag, it does not replace pack() method, you still have to call it or otherwise it will not appear. Hope this help.<br />
<br />
Reference: <a href="http://stackoverflow.com/questions/9996599/tkinters-pack-propagate-method/9996743#9996743">stackoverflow 1</a>, <a href="http://stackoverflow.com/questions/563827/how-do-you-set-a-tkinter-frame-size">stackoverflow 2</a>Unknownnoreply@blogger.com0tag:blogger.com,1999:blog-287268924783097490.post-69701520852345139282012-04-02T17:12:00.005-07:002012-04-05T22:12:45.758-07:00Python: [] vs. {} vs. ()Reference: <a href="http://stackoverflow.com/questions/4407873/whats-the-difference-between-vs-vs">http://stackoverflow.com/q/4407873/1276534</a><br />
Authors: <a href="http://stackoverflow.com/users/182153/zolomon">Zolomon</a>, <a href="http://stackoverflow.com/users/893/greg-hewgill">Greg Hewgill</a>, <a href="http://stackoverflow.com/users/12266/andrew-jaffe">Andrew Jaffe</a><br />
<br />
It is a good note post to make sure we remember what is [] vs. {} vs. ()<br />
<div class="post-text"><h1>() - tuple</h1>A tuple is a sequence of items that can't be changed (immutable).<br />
<h1>[] - list</h1>A list is a sequence of items that can be changed (mutable).<br />
<h1>{} - dictionary or set</h1>A dictionary is a list of key-value pairs, with unique keys (mutable). From Python 2.7/3.1, <code>{}</code> can also represent a set of unique values (mutable).</div>Unknownnoreply@blogger.com0tag:blogger.com,1999:blog-287268924783097490.post-10184729990720186992012-04-02T05:19:00.006-07:002012-04-05T21:53:49.898-07:00Python: Regular Expression 101 Example CodeReference: <a href="http://stackoverflow.com/q/9980381/1276534">http://stackoverflow.com/q/9980381/1276534</a><br />
Authors: <a href="http://stackoverflow.com/users/277603/rajeev">Rajeev</a>, <a href="http://stackoverflow.com/users/1276534/george">George</a><br />
<br />
In computer science theory class, we learned about regular expression. But it is unclear what exactly can it do at first, today I would like to introduce data validation as an example that uses the concept of regular expression. Python itself, like other language I assume (heard), has an implementation of regular expression. It comes standard from python too, see: <a href="http://docs.python.org/library/re.html">http://docs.python.org/library/re.html</a><br />
<br />
For example, you would like to ask the user for a telephone number, in the format of: 917-222-1234, if it is not in the format of XXX-XXX-XXXX, it will ask the user again until it is store. Let's take a look at the sample code.<br />
<pre class="brush: python">import re
while True:
# Get the user's input into the string
myString = input('Enter your telephone number: ')
# Matching it with the regular expresssion
# isGoodTelephone will return True if it matches
isGoodTelephone = re.match('^[0-9]{3}-[0-9]{3}-[0-9]{4}$', myString)
if (isGoodTelephone):
print('Great! Got your phone number into the system')
print('Entry:', myString)
else:
print('Not in the correct format. Ex: xxx-xxx-xxxx')
print()
</pre><b>Output of the csci133rep1.py: </b><br />
<pre class="brush: python">Enter your telephone number: 917-123-1234
Great! Got your phone number into the system
Entry: 917-123-1234
Enter your telephone number: 9171231234
Not in the correct format. Ex: xxx-xxx-xxxx
</pre>Actually the basic of the regular expression is not too hard to learn, take a look at the bottom and you will able to figure out how to use it with no problem. Didn't need to put too much comment to make it understandable. Although there are much more ways to use it than just the telephone.<br />
<pre class="brush: python">^[0-9]{3}-[0-9]{3}-[0-9]{4}$
^ # mark the start of the telephone string
[0-9] # any one of the 0123456789
{3} # match it exactly three times, no less
- # a hyphen symbol
[0-9] # any one of the number between 0 and 9
{3} # exactly three copies
- # another hyphen symbol
[0-0] # any one of the number 0-9
{4} # four times
$ # mark the end of the telephone string
</pre>Unknownnoreply@blogger.com0tag:blogger.com,1999:blog-287268924783097490.post-33089886513955923232012-04-01T13:05:00.006-07:002012-04-04T15:23:36.459-07:00Python: Calculate Grade Point Average In a 4.0 ScaleThis is a simple program that take a list of grade, and then convert it to a 4.0 GPA scale with 1 decimal point, finally calculate the grade point average.<br />
<pre class="brush: python"># Take the list of grade as input, assume list is not empty
def convertGrade(myGrades):
myResult = [] # List that store the new grade
for grade in myGrades:
gpa = (grade / 20) -1
# Depending on how many deciaml you want
gpa = round(gpa, 1)
myResult.append(gpa)
return myResult
# The list of grades, can be more than 5 if you want to
grades = [88.3, 93.6, 50.2, 70.2, 80.5]
convertedGrades = convertGrade(grades)
print(convertedGrades)
total = 0
# If you want the average of them
for grade in convertedGrades:
total += grade # add each grade into the total
average = total / len(convertedGrades)
print('Average GPA is:', average)
</pre>Output:<br />
<pre class="brush: python">[3.4, 3.7, 1.5, 2.5, 3.0]
Average GPA is: 2.82
</pre>Unknownnoreply@blogger.com0tag:blogger.com,1999:blog-287268924783097490.post-87041606814404637542012-03-31T19:02:00.007-07:002012-04-05T22:28:25.079-07:00Python: Get the most frequent elements from list when there is more than oneReference: <a href="http://stackoverflow.com/questions/9961077/python-max-with-same-number-of-instances">stackoverflow </a><br />
Authors: <a href="http://stackoverflow.com/users/1020706/james-kansas">james_kansas</a>, <a href="http://stackoverflow.com/users/916657/niklas-b">Niklas B.</a><br />
<br />
The question is: When you are given a list that is unsorted, how do you get the most frequent appeared element, in particular, when there is more than one.<br />
<pre class="brush: python">from collections import Counter
def myFunction(myDict):
myMax = 0 # Keep track of the max frequence
myResult = [] # A list for return
for key in myDict:
# Finding out the max frequence
if myDict[key] >= myMax:
if myDict[key] == myMax:
myMax = myDict[key]
myResult.append(key)
# Case when it is greater than, we will delete and append
else:
myMax = myDict[key]
del myResult[:]
myResult.append(key)
return myResult
foo = ['1', '1', '5', '2', '1', '6', '7', '10', '2', '2']
print('The list:', foo)
myCount = Counter(foo)
print(myCount)
print(myFunction(myCount))
</pre>Output<br />
<pre class="brush: python">The list: ['1', '1', '5', '2', '1', '6', '7', '10', '2', '2']
Counter({'1': 3, '2': 3, '10': 1, '5': 1, '7': 1, '6': 1})
['1', '2']
</pre>More Reading: <a href="http://stackoverflow.com/questions/1518522/python-most-common-element-in-a-list">http://stackoverflow.com/questions/1518522/python-most-common-element-in-a-list</a>Unknownnoreply@blogger.com0tag:blogger.com,1999:blog-287268924783097490.post-86043861953520903482012-03-31T07:10:00.019-07:002012-04-05T22:37:14.189-07:00csci133allCombination.pyReference: <a href="http://stackoverflow.com/questions/9956315/why-is-only-the-innermost-of-these-nested-while-loops-working">http://stackoverflow.com/q/9961077/1276534</a><br />
Authors: <a href="http://stackoverflow.com/users/995068/pepe">PePe</a>, <a href="http://stackoverflow.com/users/1191425/li-aung-yip">Li-aung Yip</a> <br />
<br />
Overview: Example of this nested while loop is a bad idea, and noting the while loop in python require resetting the loop counter to be 0. And for usage of getting the combination of everything, use either nested for loop with range() function, or itertools, which takes list and return every possible combination from each element in the list you give as argument. And also, xrange() is replaced by range() at 3.0.<br />
<br />
In C++, although it might not be recommended, we can write a nested while loop and the following code will work. Because of unknown reason. <br />
<pre class="brush: python">a = 0
b = 0
c = 0
while a <= 5:
while b <=3:
while c <= 8:
print(a , b , c)
c += 1
b += 1
a += 1
</pre>Output is the following<br />
<pre class="brush: python">0 0 0
0 0 1
0 0 2
0 0 3
0 0 4
0 0 5
0 0 6
0 0 7
0 0 8
</pre><b>Answer</b> Because we need to remember to reset the loop's counter, a, b, c respectively on each iteration. But this method is kind of funky.<br />
<pre class="brush: python">a = 0
b = 0
c = 0
while a <= 5:
while b <=3:
while c <= 8:
print(a , b , c)
c += 1
b += 1
c = 0 # reset
a += 1
b = 0 # reset
c = 0 # reset
</pre>I think most python programmer would prefer using the for loop over the range() function. It is interesting also to note and learn that, xrange() is the range() function, if you are using python 2.x. From 3.0 on, use range instead. :) <br />
<pre class="brush: python">for a in range(5+1): # Note xrange(n) produces 0,1,2...(n-1) and does not include n.
for b in range (3+1):
for c in range (8+1):
print(a, b, c)
</pre>But then wait... from the Li-aung Yip, there is a better way. Check out this solution which involve using <i>itertools.product()</i> <br />
<pre class="brush: python">import itertools
for a, b, c in itertools.product(range(5+1), range(3+1), range(8+1)):
print a,b,c</pre>For even more reading: <a href="http://python.net/%7Egoodger/projects/pycon/2007/idiomatic/handout.html">Dan Goodger's "Code Like a Pythonista: Idiomatic Python"</a> Thought: I think 2 second way resemble C++ the most to me, I don't know if I want to use while loop even in C++. But it is great to learn another function from the itertools, the itertools.product(). And nice to see the use for for a, b, c. I think it is powerful, but never use it in my code yet, should practice using it. <br />
<pre class="brush: python">import itertools
colors = ['red', 'green', 'blue']
vehicles = ['car', 'train', 'ship', 'boat']
numbers = [1, 2, 3, 4, 5]
"""Pints out all the possible combination of number of color vehicles"""
for color, vehicle, number in itertools.product(colors, vehicles, numbers):
print(number, color, vehicle)
</pre>More reference: <a href="http://docs.python.org/library/itertools.html">http://docs.python.org/library/itertools.html</a>Unknownnoreply@blogger.com0tag:blogger.com,1999:blog-287268924783097490.post-53197544038835027972012-03-28T13:35:00.031-07:002012-04-04T06:55:40.686-07:00csci133c7.pyor known as csci133cleanup.py <br />
<br />
In this tutorial we will write a program that clean up the string, it is one of the most classic program. Almost every student will be given a novel text file or input text file and ask them to do something on the data. So the first thing is to "open and load" the text file, and get the English letters into a new string. This tutorial looks long, because I included the full source code of every single program, but in fact it is only minor changes. Read on!<br />
<pre class="brush: python"># Version 1 of csci133cleanup.py
# Full implementation of cleanup
wordList = [] # Create a list to store our words
abc = 'abcdefghijklmnopqrstuvwxyz'
with open('novel.text') as book:
for line in book:
cleanline = ''
for character in line.tolower():
if character in abc:
cleanline += character
else:
# Important! We have append a space!
cleanline += ' '
for word in cleanline.split():
if word not in wordList:
wordList.append(word)
</pre>The first version we are only cleaning up the string text, so there are nothing too special about it. But notice, on line 18, we appended a space to it. Why? Take a moment to think about it, or try to clean 'Doctor--John' on a piece of paper. <br />
<br />
<b>Answer: </b>Because we need this mechanism to separate possible words, for example, here is a string Doctor--John. If we did not append a space, we will get 'DoctorJohn' in one word. When we want every single word in the file, we want to separate them instead of keeping them as the same one.<br />
<pre class="brush: python"># without space append: Doctor--John, result in DoctorJohn
# with space append: Doctor--John, result in Doctor John (YES!)
</pre>Of course this is not without its problem, for example, we will be left with a lot of 's', so we will want to check if it is already in the list or not. (See line 16), if they are in the list, we might not want to append it again. *Depend on your need, maybe you can add a line number to it. See the next example.<br />
<pre class="brush: python"># Version 2 of csci133cleanup.py
# Insert the line numbers into the dictionary
wordList = {} # Create a dictionary to store them
abc = 'abcdefghijklmnopqrstuvwxyz'
with open('novel.text') as book:
for line in book:
lineNumber = 1 # Starting at line 1
cleanline = ''
for character in line.tolower():
if character in abc:
cleanline += character
else:
# Important! We have append a space!
cleanline += ' '
for word in cleanline.split():
if word in wordList:
wordList[word].append(lineNumber)
else:
# Store the value as a list that contain 1 item
wordList[word] = [lineNumber]
lineNumber += 1
</pre>Take a moment to read and compare the code. The very first line is different. We are using a dictionary instead of list. Because when we want to check if the item is in the dictionary already or not, we want to use its build in function, instead of going them one by one. And the other difference is, we are now appending the line number into a list of them. There is an interesting part to it, See line 21.<br />
<pre class="brush: python">wordList[word] = [lineNumber]</pre>Notice, we can not use wordList[word] = lineNumber. Because we are creating the first value for the dictionary's key. We instead will create this value as a list that contain one integer. I actually did not aware of this when I was learning python, I keep running into error, because I only used a single interger. And when I try to append to this single integer, it does not work.<br />
<br />
The last version we want to search it, we want to look up our dictionary we just created. Take a look at the last couple of lines. <br />
<pre class="brush: python"># Version 3 of csci133cleanup.py
# This version include part 1 - 3
wordList = {}
abc = 'abcdefghijklmnopqrstuvwxyz'
with open('novel.text') as book:
lineNumber = 1
for line in book:
cleanline = ''
for character in line.tolower():
if character in abc:
cleanline += character
else:
cleanline += ' '
for word in cleanline.split():
if word in wordList:
# do something, such as append line number
wordList[word].append(lineNumber)
else:
wordList[word] = [lineNumber]
lineNumber += 1
while True:
word = input('Enter a word here: ' )
if word in wordList:
print('Found on lines:, wordList[word])
else:
print('Not found.')
</pre><pre class="brush: python">wordList = {'apple':[2, 25, 55, 100], 'banana':[5, 10, 36, 90]' ...}
</pre>This is the first time we see a while statement in python, the structure of the while loop is simple. while (<i>condition is true</i>), it will execute all the code within it once, and then check if the condition is true, if it is true, do it again, if it is not, it will exist and go to the next statement. See we have '<i>True</i>' as the condition, that means this loop will run forever, until we kill it with <a href="http://en.wikipedia.org/wiki/Signal_%28computing%29">keyboard interrupt</a>. <br />
<br />
<b>Keyboard interrupt hot key: </b>Control + C <br />
<ul></ul>Unknownnoreply@blogger.com0tag:blogger.com,1999:blog-287268924783097490.post-70764713223174397462012-03-27T13:52:00.016-07:002012-04-04T06:53:56.114-07:00csci133ifelif.pyReference: <a href="http://stackoverflow.com/questions/7052393/python-elif-or-new-if">http://stackoverflow.com/questions/7052393/python-elif-or-new-if</a><br />
Today when I am reading on the python exercises, I came across one of the exercise program it uses elif (in chapter 10). For a second I am not sure what does it mean because it is called differently. But when I read closely to the source file. It looks like it is trying to replaces some of the other if else statements. Finally I look it up <a href="http://docs.python.org/tutorial/controlflow.html#if-statements">online</a>, I found out it is a little bit more than just <b>if else</b> loops.<br />
<pre class="brush: python">def foo(var):
# Check if var is 5
if var == 5:
var = 6
elif var == 6:
var = 8
else:
var = 10
return var
def bar(var):
if var == 5:
var = 6
if var == 6:
var = 8
if var not in (5, 6):
var = 10
return var
print foo(5) # 6
print bar(5) # 8
</pre>You can see the exam of foo(5), if the val is 5. Then the rest of them are treated as (else) loop. The elif is a nested else if loop. It is good (maybe) if you want a cleaner looking program, because you don't have the nested else if loops, the indent level is smaller, and faster compare to a sequence of if, if, if statements, because you are not checking explicitly for every single if statement. Note: always try to put the most common condition on the top, so things can check off the 'list of conditions' faster. <br />
<br />
<b>For example:</b> If you want to check if a string is English word or not, you would want to check if "<a href="http://docs.python.org/release/2.5.2/lib/string-methods.html">isalpha()</a>" or not, and then you start to clean up the letters. So that way, your loop will exist as soon as it knows it contain non-letter characters.Unknownnoreply@blogger.com0tag:blogger.com,1999:blog-287268924783097490.post-24196824785449243062012-03-23T13:46:00.003-07:002012-03-27T18:06:35.286-07:00csci133class.pyTkinter 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?<br />
<br />
For our ice cream store, we want to create memebership account (Object).<br />
<pre class="brush: js">standardMember = Account('George Chan')
standardMember.deposit(100)
</pre>Or, for a worker timesheet program, we can create worker that contain other datatype object)<br />
<pre class="brush: js">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())
</pre>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.<br />
<br />
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.<br />
<pre class="brush: js">member1 = iceCreamMember('George', 23)
</pre>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. <br />
<pre class="brush: js">def __init__(self, name, age):
</pre>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. <br />
<br />
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.<br />
<pre class="brush: js">self.myName = name
self.myAge = age
</pre>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. <br />
<br />
But if we try to print(member1), something weird will happen, try it. It actually let us learn another fact about how python work.<br />
<pre class="brush: js">>>>
<__main__.iceCreamMember object at 0x0000000002EE1E48>
</pre>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.<br />
<pre class="brush: js">def __str__(self):
return self.myName + ', and age ' + str(self.myAge)
</pre>So when we ask python to print, it will know what to print.<br />
<br />
<b>*Important*</b> : self vs. Deck<br />
<pre class="brush: js">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)
</pre>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.<br />
<pre class="brush: js">iceCreamMemeber.__init__(self)
</pre><b>*Important*:</b> 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.Unknownnoreply@blogger.com0United States37.09024 -95.71289100000001310.850828 -156.01284500000003 63.329652 -35.412937000000014tag:blogger.com,1999:blog-287268924783097490.post-63388772591391599402012-03-19T17:08:00.009-07:002012-03-21T12:08:20.009-07:00csci133number.pyReference: <a href="http://docs.python.org/library/stdtypes.html#numeric-types-int-float-long-complex">http://docs.python.org/library/stdtypes.html#numeric-types-int-float-long-complex</a><br />
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!<br />
<br />
There are total of 4 number type (or Numeric Type): integers, float, long, complex.<br />
<ul><li><b>Integer - </b>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..)</li>
<li><b>Floating point - </b>implemented using double in C. When you need decimal point, you can use floating point. Such as 1234.5 + 1234.5. </li>
<li><b>Long integers -</b> have unlimited amount of precisions. (See <a href="http://docs.python.org/c-api/long.html">here</a> for long integers). It is useful if you are calculating the amount of debt United States is under. (wink wink)</li>
<li><b>Complex - </b>have real and imaginary component to it. (See here for <a href="http://docs.python.org/library/functions.html#complex">Complex</a> numbers). I think it is very useful, but I am not yet familiar with it yet, I shall come back to it soon.</li>
</ul>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. <br />
<br />
The relationship is the follow: Complex > Floating point > Long Integer > Integer <br />
<pre class="brush: js"># 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)</pre><br />
There is a thing called<i> module</i>, it is a <i>package</i> 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 <i>import</i> 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.<br />
<pre class="brush: js"># Sample code for math moduele
import math
print(math.pi)
>>> 3.1415926535897931
</pre>Unknownnoreply@blogger.com0tag:blogger.com,1999:blog-287268924783097490.post-34817531993501404672012-03-19T16:14:00.015-07:002012-03-27T15:34:20.357-07:00csci133Buildin.pyEverything 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.<br />
<ol><li><b>They are easy- </b>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.</li>
<li><b>They are useful - </b>you can use them to build more complex object. They are like lego, you can stack them and form different tools.</li>
<li><b>Efficient - </b>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. </li>
<li><b>Always here - </b>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.</li>
</ol><style>
<!--
/* Font Definitions */
@font-face
{font-family:"MS 明朝";
mso-font-charset:78;
mso-generic-font-family:auto;
mso-font-pitch:variable;
mso-font-signature:1 134676480 16 0 131072 0;}
@font-face
{font-family:Verdana;
panose-1:2 11 6 4 3 5 4 4 2 4;
mso-font-charset:0;
mso-generic-font-family:auto;
mso-font-pitch:variable;
mso-font-signature:3 0 0 0 1 0;}
@font-face
{font-family:"Cambria Math";
panose-1:2 4 5 3 5 4 6 3 2 4;
mso-font-charset:0;
mso-generic-font-family:auto;
mso-font-pitch:variable;
mso-font-signature:3 0 0 0 1 0;}
@font-face
{font-family:Cambria;
panose-1:2 4 5 3 5 4 6 3 2 4;
mso-font-charset:0;
mso-generic-font-family:auto;
mso-font-pitch:variable;
mso-font-signature:-536870145 1073743103 0 0 415 0;}
/* Style Definitions */
p.MsoNormal, li.MsoNormal, div.MsoNormal
{mso-style-unhide:no;
mso-style-qformat:yes;
mso-style-parent:"";
margin:0in;
margin-bottom:.0001pt;
mso-pagination:widow-orphan;
font-size:12.0pt;
font-family:Cambria;
mso-ascii-font-family:Cambria;
mso-ascii-theme-font:minor-latin;
mso-fareast-font-family:"MS 明朝";
mso-fareast-theme-font:minor-fareast;
mso-hansi-font-family:Cambria;
mso-hansi-theme-font:minor-latin;
mso-bidi-font-family:"Times New Roman";
mso-bidi-theme-font:minor-bidi;}
.MsoChpDefault
{mso-style-type:export-only;
mso-default-props:yes;
font-family:Cambria;
mso-ascii-font-family:Cambria;
mso-ascii-theme-font:minor-latin;
mso-fareast-font-family:"MS 明朝";
mso-fareast-theme-font:minor-fareast;
mso-hansi-font-family:Cambria;
mso-hansi-theme-font:minor-latin;
mso-bidi-font-family:"Times New Roman";
mso-bidi-theme-font:minor-bidi;}
@page WordSection1
{size:8.5in 11.0in;
margin:1.0in 1.25in 1.0in 1.25in;
mso-header-margin:.5in;
mso-footer-margin:.5in;
mso-paper-source:0;}
div.WordSection1
{page:WordSection1;}
-->
</style> <br />
<table border="1" cellpadding="0" cellspacing="0" class="MsoNormalTable" style="border-collapse: collapse; border: none; mso-border-alt: solid windowtext .5pt; mso-padding-alt: 0in 5.4pt 0in 5.4pt; mso-yfti-tbllook: 1184;"><tbody>
<tr style="mso-yfti-firstrow: yes; mso-yfti-irow: 0;"> <td style="border: solid windowtext 1.0pt; padding: 0in 5.4pt 0in 5.4pt; width: 103.55pt;" valign="top" width="104"><div class="MsoNormal"><b><span style="font-family: Verdana; font-size: 10pt;">Name</span></b><span style="font-family: Verdana; font-size: 10pt;"></span></div></td> <td style="border-left: none; border: solid windowtext 1.0pt; mso-border-left-alt: solid windowtext 1.0pt; padding: 0in 5.4pt 0in 5.4pt; width: 135.0pt;" valign="top" width="135"><div class="MsoNormal"><b><span style="font-family: Verdana; font-size: 10pt;">Example</span></b><span style="font-family: Verdana; font-size: 10pt;"></span></div></td> <td style="border-left: none; border: solid windowtext 1.0pt; mso-border-left-alt: solid windowtext 1.0pt; padding: 0in 5.4pt 0in 5.4pt; width: 101.05pt;" valign="top" width="101"><div class="MsoNormal"><b><span style="font-family: Verdana; font-size: 10pt;">Sample Code</span></b><span style="font-family: Verdana; font-size: 10pt;"></span></div></td> <td style="border-left: none; border: solid windowtext 1.0pt; mso-border-left-alt: solid windowtext 1.0pt; padding: 0in 5.4pt 0in 5.4pt; width: 103.2pt;" valign="top" width="103"><div class="MsoNormal"><b><span style="font-family: Verdana; font-size: 10pt;">Reference</span></b><span style="font-family: Verdana; font-size: 10pt;"></span></div></td> </tr>
<tr style="mso-yfti-irow: 1;"> <td style="border-top: none; border: solid windowtext 1.0pt; mso-border-top-alt: solid windowtext 1.0pt; padding: 0in 5.4pt 0in 5.4pt; width: 103.55pt;" valign="top" width="104"><div class="MsoNormal"><span style="font-family: Verdana; font-size: 10pt;">Number</span></div></td> <td style="border-bottom: solid windowtext 1.0pt; border-left: none; border-right: solid windowtext 1.0pt; border-top: none; padding: 0in 5.4pt 0in 5.4pt; width: 135.0pt;" valign="top" width="135"><div class="MsoNormal"><span style="font-family: Verdana; font-size: 10pt;">12345, 1234.5</span></div></td> <td style="border-bottom: solid windowtext 1.0pt; border-left: none; border-right: solid windowtext 1.0pt; border-top: none; padding: 0in 5.4pt 0in 5.4pt; width: 101.05pt;" valign="top" width="101"><div class="MsoNormal"><a href="http://csci133number.py/"><span style="font-family: Verdana; font-size: 10pt;">csci133number.py</span></a></div></td> <td style="border-bottom: solid windowtext 1.0pt; border-left: none; border-right: solid windowtext 1.0pt; border-top: none; padding: 0in 5.4pt 0in 5.4pt; width: 103.2pt;" valign="top" width="103"><div class="MsoNormal"><span style="font-family: Verdana; font-size: 10pt;"><a href="http://docs.python.org/library/stdtypes.html#numeric-types-int-float-long-complex"><span style="color: blue;">Link</span></a></span></div></td> </tr>
<tr style="mso-yfti-irow: 2;"> <td style="border-top: none; border: solid windowtext 1.0pt; mso-border-top-alt: solid windowtext 1.0pt; padding: 0in 5.4pt 0in 5.4pt; width: 103.55pt;" valign="top" width="104"><div class="MsoNormal"><span style="font-family: Verdana; font-size: 10pt;">String</span></div></td> <td style="border-bottom: solid windowtext 1.0pt; border-left: none; border-right: solid windowtext 1.0pt; border-top: none; padding: 0in 5.4pt 0in 5.4pt; width: 135.0pt;" valign="top" width="135"><div class="MsoNormal"><span style="font-family: Verdana; font-size: 10pt;">‘Hello Python’</span></div></td> <td style="border-bottom: solid windowtext 1.0pt; border-left: none; border-right: solid windowtext 1.0pt; border-top: none; padding: 0in 5.4pt 0in 5.4pt; width: 101.05pt;" valign="top" width="101"><div class="MsoNormal"><a href="http://csci133string.py/"><span style="font-family: Verdana; font-size: 10pt;">csci133string.py</span></a></div></td> <td style="border-bottom: solid windowtext 1.0pt; border-left: none; border-right: solid windowtext 1.0pt; border-top: none; padding: 0in 5.4pt 0in 5.4pt; width: 103.2pt;" valign="top" width="103"><div class="MsoNormal"><span style="font-family: Verdana; font-size: 10pt;"><a href="http://docs.python.org/library/stdtypes.html#sequence-types-str-unicode-list-tuple-bytearray-buffer-xrange"><span style="color: blue;">Link</span></a></span></div></td> </tr>
<tr style="mso-yfti-irow: 3;"> <td style="border-top: none; border: solid windowtext 1.0pt; mso-border-top-alt: solid windowtext 1.0pt; padding: 0in 5.4pt 0in 5.4pt; width: 103.55pt;" valign="top" width="104"><div class="MsoNormal"><span style="font-family: Verdana; font-size: 10pt;">List</span></div></td> <td style="border-bottom: solid windowtext 1.0pt; border-left: none; border-right: solid windowtext 1.0pt; border-top: none; padding: 0in 5.4pt 0in 5.4pt; width: 135.0pt;" valign="top" width="135"><div class="MsoNormal"><span style="font-family: Verdana; font-size: 10pt;">[1, 2, 3] [‘a’, ‘b’, ‘c’]</span></div></td> <td style="border-bottom: solid windowtext 1.0pt; border-left: none; border-right: solid windowtext 1.0pt; border-top: none; padding: 0in 5.4pt 0in 5.4pt; width: 101.05pt;" valign="top" width="101"><div class="MsoNormal"><span style="font-family: Verdana; font-size: 10pt;">csci133list.py</span></div></td> <td style="border-bottom: solid windowtext 1.0pt; border-left: none; border-right: solid windowtext 1.0pt; border-top: none; padding: 0in 5.4pt 0in 5.4pt; width: 103.2pt;" valign="top" width="103"><div class="MsoNormal"><a href="http://docs.python.org/library/functions.html#list"><span style="font-family: Verdana; font-size: 10pt;">Link</span></a></div></td> </tr>
<tr style="mso-yfti-irow: 4;"> <td style="border-top: none; border: solid windowtext 1.0pt; mso-border-top-alt: solid windowtext 1.0pt; padding: 0in 5.4pt 0in 5.4pt; width: 103.55pt;" valign="top" width="104"><div class="MsoNormal"><span style="font-family: Verdana; font-size: 10pt;">Dictionary</span></div></td> <td style="border-bottom: solid windowtext 1.0pt; border-left: none; border-right: solid windowtext 1.0pt; border-top: none; padding: 0in 5.4pt 0in 5.4pt; width: 135.0pt;" valign="top" width="135"><div class="MsoNormal"><span style="font-family: Verdana; font-size: 10pt;">{‘username’:’password’}</span></div></td> <td style="border-bottom: solid windowtext 1.0pt; border-left: none; border-right: solid windowtext 1.0pt; border-top: none; padding: 0in 5.4pt 0in 5.4pt; width: 101.05pt;" valign="top" width="101"><div class="MsoNormal"><span style="font-family: Verdana; font-size: 10pt;">csci133dictionary.py</span></div></td> <td style="border-bottom: solid windowtext 1.0pt; border-left: none; border-right: solid windowtext 1.0pt; border-top: none; padding: 0in 5.4pt 0in 5.4pt; width: 103.2pt;" valign="top" width="103"><div class="MsoNormal"><span style="font-family: Verdana; font-size: 10pt;"><a href="http://docs.python.org/library/stdtypes.html#dictionary-view-objects"><span style="color: blue;">Link</span></a></span></div></td> </tr>
<tr style="mso-yfti-irow: 5; mso-yfti-lastrow: yes;"> <td style="border-top: none; border: solid windowtext 1.0pt; mso-border-top-alt: solid windowtext 1.0pt; padding: 0in 5.4pt 0in 5.4pt; width: 103.55pt;" valign="top" width="104"><div class="MsoNormal"><span style="font-family: Verdana; font-size: 10pt;">Boolean</span></div></td> <td style="border-bottom: solid windowtext 1.0pt; border-left: none; border-right: solid windowtext 1.0pt; border-top: none; padding: 0in 5.4pt 0in 5.4pt; width: 135.0pt;" valign="top" width="135"><div class="MsoNormal"><span style="font-family: Verdana; font-size: 10pt;">True, False</span></div></td> <td style="border-bottom: solid windowtext 1.0pt; border-left: none; border-right: solid windowtext 1.0pt; border-top: none; padding: 0in 5.4pt 0in 5.4pt; width: 101.05pt;" valign="top" width="101"><div class="MsoNormal"><span style="font-family: Verdana; font-size: 10pt;">csci133boolean.py</span></div></td> <td style="border-bottom: solid windowtext 1.0pt; border-left: none; border-right: solid windowtext 1.0pt; border-top: none; padding: 0in 5.4pt 0in 5.4pt; width: 103.2pt;" valign="top" width="103"><div class="MsoNormal"><span style="font-family: Verdana; font-size: 10pt;"><a href="http://docs.python.org/library/stdtypes.html#boolean-operations-and-or-not"><span style="color: blue;">Link</span></a></span></div></td> </tr>
</tbody></table><br />
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 <i>dynamically typed</i> (instead of declaring the type and compile the code), and <i>strongly typed</i> (means you can not perform other type function on another type). It is something to keep in mind when you are learning other languages.<br />
<table border="1" cellpadding="0" cellspacing="0" class="MsoNormalTable" style="border-collapse: collapse; border: medium none;"><tbody></tbody></table>Unknownnoreply@blogger.com0tag:blogger.com,1999:blog-287268924783097490.post-51909869077778183542012-03-16T14:36:00.031-07:002012-03-19T18:30:10.983-07:00csci133p6.pyThis 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.<br />
<br />
<i>The focus we are using in this series of tutorial is from Tkinter, or known as TK.</i><br />
<pre class="brush: js">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()
</pre>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!<br />
<br />
<div style="text-align: left;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiGCQj6lX58Kkdvl5Stwfj4TJapg6vciO7PCTXaD61YIwNyInzRXtig9HKVHJcZEkI4J1uLV5AUZbofv62ZsATvXNqINrgMZdqLcMzryED0HDYfFFQP2tOshehBN4Nx1HNe63Jztj03gEo/s1600/Screenshot-tk.png" /></div><br />
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. <br />
<br />
<div style="text-align: left;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjVFgSq5YH514cXQG0tIf92bTu3VqABK6bHKuiJQnS_KhVPjCjCvTjSx8yT07qLDSvgt8dnQ4je_BLnlwnQZXK4b11nvfguQsBKecXm94c-xOnyX6hPpt1qguu4oK8_Urdpo3slHNE6UiA/s1600/Screenshot-tk-1.png" /></div><br />
Look at line 1: <br />
<pre class="brush: js">from Tkinter import *</pre>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.<br />
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.<br />
Look at line 8:<br />
<pre class="brush: js">simpleTitle = Label(root)
simpleTitle['text'] = 'Hello Tkinter!'
simpleTitle.pack()</pre>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!<br />
<br />
<b>Reference:</b> <a href="http://docs.python.org/library/tkinter.html#packer-options">http://docs.python.org/library/tkinter.html#packer-options</a><br />
<blockquote class="tr_bq">Here is the list of possible options:<br />
<ul><li><b>expand: </b>if it is set to true, it will expand as the window's size get bigger. Ex: foo.pack(expand=YES)<br />
</li>
<li><b>fill:</b> it is to screen, there are 3 options to it, either X, Y, BOTH<br />
Ex: foo.pack(fill=BOTH)</li>
<li><b>side:</b> it get where your widget want to be positioned. TOP (default), BOTTOM, LEFT, RIGHT<br />
Ex: foo.pack(side=LEFT) </li>
<li><b>anchor:</b> which way it snaps on to, it is think as a compass, has 8 directions. "n", "ne", "e", "se", "s", "sw", "w", "nw", "center"<br />
Ex: foo.pack(anchor=w)</li>
</ul></blockquote><br />
Example of such chained options:<br />
<pre class="brush: js">foo.pack(expand=YES, side=LEFT, fill=X)</pre>Unknownnoreply@blogger.com2tag:blogger.com,1999:blog-287268924783097490.post-39119907707117885752012-03-14T03:42:00.015-07:002012-03-28T13:25:22.071-07:00csci133c5.pyIn python, there is an extremely useful data type called <b><i>dictionary</i></b>. What a dictionary is a collection of unordered (<i>key</i>, <i>value</i>) 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.<br />
<br />
Take a look at the example for the dictionary below<br />
<pre class="brush: js">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.')
</pre>Output:<br />
<pre class="brush: js">Username: george
Password: dog
Correct, welcome: george
Username: george
Password: cat
Sorry, bad password.
</pre>Reference: <a href="http://docs.python.org/tutorial/datastructures.html#dictionaries">http://docs.python.org/tutorial/datastructures.html#dictionaries</a><br />
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 <i>a pair of braces{}</i>, 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.<br />
<ul><li>keys(), which return a list of all the keys used in the dictionary</li>
<li>del dictionary[key], delete the key:value pair</li>
<li>if you store a key that is already has a value, the old value will be gone</li>
<li>the keys can be strings and numbers </li>
<li>the value can be objects of any kind</li>
</ul>When you want to look up a key and see what its value is, do this:<br />
<pre class="brush: js">passwords['george']
# Return value will be 'dog'</pre>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.<br />
<pre class="brush: js">myNum = 10
if myNum > 5:
print('My number is greater than 5') # Totally cool too
</pre>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.Unknownnoreply@blogger.com0