Saturday, December 28, 2013

Python's Standard Library

     Have you ever heard someone say Python has batteries included? Have you wondered what the heck that means? Well, I can explain.
     Screw creating your own modules all the time, Python has standard ones built in! These standard modules let you find files, tell/count time, and much more. Remember everything we used with the import function? All of those are modules. The standard ones are the ones we never created in a different program! Should there be something you want to do that isn't a standard module, you should be able to find a download for them, hopefully for free (if you do that, be very careful, as it could be a virus or have viruses attached). So, what standard modules have we been using? Well, up until this point, you never knew you were doing the things in this article all along. The standard modules we know about so far are time and random.
     We already talked about time and random and how to use them, but there's a little more. With time.sleep(), you can make the program do nothing for a certain amount of time. There's a faster way to do it, though.

from time import sleep

     When you type that, it will make things a little faster to type, like this.

sleep(5)

     We do sleep(5) instead of time.sleep(5). We can do that because we imported sleep from time.
     There's also another thing to talk about with random. We all know about random.randint, the function we used in the fortune teller program, the multiplication one, and so on. We all know how random.randint works, but there's something else: random.random().
     random.random() will give you a random number between 0 and 1. Try it!

>>> import random
>>> print(random.random())
0.19406666194760636

     If you want a number that isn't between 0 and 1, you can multiply the answer. Let's try getting a number between 0 and 10.

>>> print(random.random() * 10)
8.2903170046567

     If you don't want a super specific float, you can use the int() function or the round() function, like this.

>>> print(int(random.random() * 10))
8

     The int function took our number and turned it into an integer!
     In this article, you learned about importing from a module, and random.random(). I challenge you to go to one of the old programs and change it with these methods!

Saturday, December 14, 2013

Namespaces

     There's more about modules. This topic is pretty complicated, it's on namespaces. What are they?
     Well, let's say you were in this school. We'll just simply call it School A. There is one person in your class (Class A) named Gerry, but in another class (Class B), someone else is named Gerry. Each class is its own namespace, and the students are inside of it.
     So, if you were to say "Gerry got glasses" in Class A, everyone would assume you mean the Gerry in that class' namespace. You would have to say something like "The other Gerry" for the class to know it's not the Gerry it has. If the principal calls Gerry to come to her office over the loudspeaker, she would get everyone with that name. She'd have to be specific, like saying the last name (i.e. Gerry Vargas) or saying which class the Gerry she wants is from. To make things easier, she could just go to the classroom and tell Gerry in person. The principal has to be specific which namespace has the Gerry she wants.
     So, let's move on to importing namespaces. Let's say a class from another school (Class C) has to teach in one of School A's portables for a while. If someone from Class C is named Harry, but no one from School A is, and the principal calls for Harry, no one will come. She'd have to hook up the loudspeaker to the portables, and to do that, we have to import the namespace (Class C). We could simply do this:

from ClassC import Harry

    Or, if we want to make things faster, we could just do

from ClassC import *
   
     Ta-da! * will automatically import everything in the namespace we chose (ClassC), and now the principal can call anyone from that class whenever she wants. She can just do callToOffice(Harry) or call someone else. Something like that, at least.
     I know, my explanation is a little unclear. We should be able to give my examples a nice shine later on.

Wednesday, December 4, 2013

Modules

     Alright, first, let's say happy birthday to my friend, Aarin Panell! We'll do a birthday theme for this article.
     So, we've been talking about collecting things together for a while. Lists, objects, etc. This should be the last term on that, and then we should start doing the really fun stuff! So, the last collectible programming term we're gonna be talking about is something called a module.
     I'm sure we've gotten errors and all those, but have you ever read them? I've been able to understand what the red text says fairly well. And in EVERY error box, you will see this:

File "C:\Python33\Geometry.py", line 22, in <module>

     See? It says module right there. Line 22, in <module>? Well, we can probably take a guess at what it is. All the programs we've done are simply modules. They can be used in a bigger program. So, a module is a piece of something! If you're still a little confused, take Lego blocks for example. Each little piece represents one of the simple programs we've written during our time at Programmer's Peak. You take the blocks, and use them to build a bigger construction. This construction is an entire program, and each piece is a simple module.
     Modules are little programs that are used as pieces for big programs. Did we get that cleared up? So, why don't we try it? Let's create a new program, a simple little one. To make things easier, we might want to have the same file name. I saved mine as OurModule.py. This is where we get into Aarin's birthday theme. He said he wanted something with presents, so let's do that!



presentPossibilities=['Candy bar', 'Dragon', 'Can of beans', 'Skateboard', 'Hammer', 'Paintball gun']
chooser=0
number=5


     Ha. Getting a dragon for your birthday would be the best thing ever (or not, depending on how dangerous it is), and a can of beans would be the worst. Well, guess what? We are going to make another program and shove this module in it!
     So, how do we do that? Well, don't we understand some functions? They are normal English words. And the function we need is something we've used for quite a while now, to trigger random things and sleeping time. That function is import!
     Let's open up a new window and do this:

import OurModule, time, random

print("Hello. Welcome to Aarin Panell's basic birthday present simulator! Press enter to continue.")
thing=input()
print("And the present is...")
time.sleep(2)
print("A", presentPossibilities[chooser], "!")

     Well, what're you waiting for? Let's run it!

Hello. Welcome to Aarin Panell's basic birthday present simulator! Press enter to continue.

And the present is...
Traceback (most recent call last):
  File "C:/Python33/AarinParty.py", line 7, in <module>
    print("A", presentPossibilities[chooser], "!")
NameError: name 'presentPossibilities' is not defined

     That was a disappointment.
     Why'd this happen? Well, computers are dumb. You have to be this specific to make them work. Well, more specific. We never told our big program that presentPossibilities and chooser are part of Module.py! We'll have to fix it, like this:

print("A", OurModule.presentPossibilities[OurModule.chooser], "!")

     Yay! Run the program and you should get this:

Hello. Welcome to Aarin Panell's basic birthday present simulator! Press enter to continue.

And the present is...
A Candy bar !

     It works! Wait... Try running the program more than once...

Hello. Welcome to Aarin Panell's basic birthday present simulator! Press enter to continue.

And the present is...
A Candy bar !

Hello. Welcome to Aarin Panell's basic birthday present simulator! Press enter to continue.

And the present is...
A Candy bar !

Hello. Welcome to Aarin Panell's basic birthday present simulator! Press enter to continue.

And the present is...
A Candy bar !

     Here's a problem! It doesn't stop doing a candy bar! That's my challenge. Try to debug Aarin's birthday party! Here's a tip: this is very similar to the program in the

A Quick Tip - The Randint of a List

article. It may point you in the right direction!
P.S. Don't be surprised if the modules article keeps going on. I may not have completely covered the topic yet.

Thursday, November 28, 2013

Inheritance

     So, last time, I wrote an article focusing on the one word computer programs don't know is a word: Polymorphism. Well, before I started talking about it, I mentioned something called inheritance. Let's get to that!
Inheritance: class.__init__(self, classValue)
     Explaining inheritance is a little difficult, as those bold words make no sense, really. Well, we all know what inheritance is. It's what you get from someone else, like red hair from your parents, or maybe the family income, or whatever.
     Well, the programming term is like that. A class inherits attributes/methods from another class. Well, since it's Thanksgiving, I'll give an example related to that holiday. Let's say we were making a game. In this game, you could collect items, like turkeys, coins, pilgrim hats, etc. When the player touches the coin (or turkey/pilgrim hat), there would be a pickUp() method triggered, and it would be added to their bag or whatever is storing everything. We should also have the coins be used to buy things at shops. Well, here is what we might do.

class GameObject: #this is the variable of all the items picked up
    def __init__(self, name):
        self.name = name #name is changed to one of the item classes

    def pickUp(self, player): #here's the function that lets the player pick up the item
        #insert code here to add the object
        #to the player's bag

class Coin(GameObject): #this is known as a subclass, which inherits the attributes (etc.) of a class
    def __init__(self, value):
        GameObject.__init__(self, "coin") #this is what changes name to coin!
        self.value = value

    def spend(self, buyer, seller):
        #insert code here to remove the coin from buyer and give to seller

     Well, this obviously won't work, since we don't have all of the mechanics required to make a game using these objects. You'll just get an error trying to run it.
     Well, this is my example of inheritance. Happy Thanksgiving!

Sunday, November 24, 2013

Polymorphism

     We've talked about __init__(), we've talked about __str__(), but something we haven't talked about are two of the most important parts in the object world. Just two big words, and those words are polymorphism and inheritance.
Polymorphism: >= 2
     Polymorphism means you can have at least 2 methods that are the same in different classes that do different things. Confused? Here's an example, and look at the function getArea().
     So, if you wanted to do geometry, here's an example of finding the area.

class Rectangle:
    def __init__(self, width, height):
        self.width = width
        self.height = height

    def getArea(self):
        area = self.width * self.height
        return area

class Cube:
    def __init__(self, size):
        self.size = size

    def getArea(self):
        area = self.size * self.size * self.size
        return area

RectArea = Rectangle(5, 8)
CubeArea = Cube(4)

     Now run the program, and type this in:

>>> RectArea.getArea()
40
>>> CubeArea.getArea()
64
>>>

     Ta-da! Both classes used getArea(), but did different things and had different outcomes. That is polymorphism.
     Next time, we will study inheritance. Brace yourself, these articles will never be simple again!

Thursday, November 14, 2013

A Quick Tip - Alphabetical Order

     As I was looking through one of my old list articles, I realized that there's a function I don't remember writing about. This function is known as sort().

     Sort() is a function that sorts all items in a list in alphabetical order. Isn't that neat? Let's show an example of this. If you need to sort a bunch of words in alphabetical order, you can do it in a snap! Let's make a list:

words=['Exuberant', 'Philosophy', 'Pterodactyl', 'Potato', 'Avenue', 'Boulevard', 'Rendezvous', 'Embryonic']

     (Yes, those are real words)
     So, we use sort() like this:

words.sort()

     Now, let's print(words):

['Avenue', 'Boulevard', 'Embryonic', 'Exuberant', 'Philosophy', 'Potato', 'Pterodactyl', 'Rendezvous']

     Takes the pressure of of things, eh? Now I know you know the sort() function. Sorry it took so long to figure out that I didn't tell you this earlier!

Saturday, November 9, 2013

Timer

     Remember that short article that talked about sleeping time? I figured we should practice it! The only things we've been doing with time is giving the user some time to read a message before the next one comes up. There is way more to it than that, though! Here's another program I wrote a very long time ago. It's a timer (that figures, since the title of this article is "Timer").
     Let's see the program:

import time, easygui

choices=easygui.buttonbox("Do you want the time to go in seconds, minutes, or hours?", choices=['Seconds', 'Minutes', 'Hours'])
if choices == 'Seconds':
    time2=easygui.integerbox("Seconds. OK. How many seconds?")
    for i in range(time2, 0, -1):
        print(time2)
        print(time2 * "*")
        time.sleep(1)
        time2=time2-1
elif choices == 'Minutes':
    time3=easygui.integerbox("How many minutes?")
    for j in range(time3, 0, -1):
        print(time3)
        print(time3 * "*")
        time.sleep(1*60)
        time3=time3-1
else:
    time4=easygui.integerbox("Long times. How many hours?")
    for k in range(time4, 0, -1):
        print(time4)
        print(time4 * "*")
        time.sleep(1*60*60)
        time4=time4-1

easygui.msgbox("Time's up!")

     It may seem a little complicated, but let's just see what happens when it runs.


10
**********
9
*********
8
********
7
*******
6
******
5
*****
4
****
3
***
2
**
1
*
     Not too complicated, really. The asterisks were mainly for fun, so let's just move on to the real numbers.

for i in range(time2, 0, -1):

     We already know about this part, we talked about it in the For Loops article.

        print(time2)
        print(time2 * "*")
        time.sleep(1)
        time2=time2-1

     Well, we print time2. And then we print as many asterisks as time2 is. Then we wait a second, and then we recreate the variable.
     So, this is another part of the world of time. Now you can use this program to your heart's content! I challenge you to find out if time2=time2-1, time3=time3-1, and time4=time4-1 are pointless!

Friday, November 1, 2013

Debugging Part 3 - Pumpkin Carving

     So, as you remember in the last article, our program had an error. When you get accustomed to them, you can figure out what they are saying. It's the last line that gives you the reason the program crashed.

Traceback (most recent call last):
  File "C:/Python33/Pumpkins.py", line 79, in <module>
    easygui.msgbox("A pumpkin with", Pumpkin.eyes, "eyes, a", Pumpkin.nose, "nose, and a", Pumpkin.mouth, " ", Pumpkin.expression, ".")
TypeError: msgbox() takes from 0 to 5 positional arguments but 9 were given

     Let's take a look at the last line.

TypeError: msgbox() takes from 0 to 5 positional arguments but 9 were given

     So, EasyGUI messagebox had too many variables to work with, or something. I'm not sure, so let's just figure it out. Let's start by changing the msgbox into a print statement.

print("The pumpkin has", Pumpkin.eyes, "eyes, a", Pumpkin.nose, "nose, and a", Pumpkin.mouth, " ", Pumpkin.expression, ".")

     Did that work?

Time to carve some pumpkins!
First things first...
The pumpkin has Fire eyes.
Okay, let's do the nose.
The pumpin has a Arrowhead nose.
Now, the mouth! But first...
The pumpkin has a Smile .
Now...
The pumpkin has a Round mouth.
Here's your entire combination:
The pumpkin has Fire eyes, a Arrowhead nose, and a Round   Smile .


     Really, that was it? Wow. It pays off to actually read the errors, doesn't it? There must be some way around that arguments thing on EasyGUI, but that's probably gonna be extremely hard to find. Well, I guess Halloween is over, but if I do search for that way around, Halloween will spring back up!
     I challenge you to find a way around the error while still using EasyGUI (if that's even possible)!

Thursday, October 31, 2013

Pumpkin Carving

     Let's do a little more object practice before moving on. Since it's Halloween, let's do pumpkin carving!

First, let's make our pumpkin and its properties.

class Pumpkin:
    def __init__(self):
        self.eyes="No eyes"
        self.nose="No nose"
        self.mouth="No mouth"
        self.misc="No extras"
        self.expression="No expression"

     So, basically, this program is where you carve a pumpkin, and you can choose the shape of your face. Let's go the simple way, and start the visual part of the program now. But, first, I want to practice an old thing I wrote a long time ago. Put this at the top of your program:

import easygui, time

     Alright, now you know I want to practice EasyGUI again! Well, here's what I did under the def __init__(self): block:

print("Time to carve some pumpkins!")
time.sleep(4)
print("First things first...")
time.sleep(4)
choices=easygui.buttonbox("How do you want to shape the eyes?", choices=["Triangles", "Circles", "Squares", "Fireballs", "Stars", "Ovals", "Swirls"])

     So, you should get this when you run the program so far:

Time to carve some pumpkins!
First things first...

     Then a window that says:


     Well, once you click a button, the program just ends (since there's no lines after the EasyGUI). Well, just to prove that EasyGUI actually did something, add this to the program:

if choices == "Triangles":
    Pumpkin.eyes='Triangle'
elif choices == "Circles":
    Pumpkin.eyes='Round'
elif choices == "Squares":
    Pumpkin.eyes='Square'
elif choices == "Fireballs":
    Pumpkin.eyes='Fire'
elif choices == "Stars":
    Pumpkin.eyes='Star'
elif choices == "Ovals":
    Pumpkin.eyes='Oval'
else:
    Pumpkin.eyes='Swirly'
print("The pumpkin has", Pumpkin.eyes, "eyes.")

     This is what I got when I picked Swirls.

Time to carve some pumpkins!
First things first...
The pumpkin has Swirly eyes.

     So, there you go. The process repeats for the nose, so here's the rest of the program.

time.sleep(4)
print("Okay, let's do the nose.")
time.sleep(3)
choices=easygui.buttonbox("What shape do you want the nose to be?", choices=["Triangle", "Circle", "Arrowhead", "Fireball", "Swirl", "Square", "Oval", "Star"])
if choices == "Triangles":
    Pumpkin.nose='Triangle'
elif choices == "Circles":
    Pumpkin.nose='Round'
elif choices == "Squares":
    Pumpkin.nose='Square'
elif choices == "Fireballs":
    Pumpkin.nose='Fire'
elif choices == "Stars":
    Pumpkin.nose='Star'
elif choices == "Ovals":
    Pumpkin.nose='Oval'
elif choices == "Arrowhead":
    Pumpkin.nose="Arrowhead"
else:
    Pumpkin.nose='Swirly'
print("The pumpin has a", Pumpkin.nose, "nose.")
time.sleep(4)
print("Now, the mouth! But first...")
choices=easygui.buttonbox("What expression do you want the mouth to have?", choices=["Smile", "Laugh", "Scowl"])
if choices == "Smile":
    Pumpkin.expression='Smile'
elif choices == "Laugh":
    Pumpkin.expression='Laughing face'
else:
    Pumpkin.expression='Scowl'
print("The pumpkin has a", Pumpkin.expression, ".")
time.sleep(4)
print("Now...")
choices=easygui.buttonbox("What do you want the mouth to look like?", choices=["Round, banana-like", "Spiky", "Curly", "Square", "Flaming"])
if choices == "Round, banana-like":
    Pumpkin.mouth='Round'
elif choices == "Spiky":
    Pumpkin.mouth='Spiky'
elif choices == "Curly":
    Pumpkin.mouth='Curly'
elif choices == "Square":
    Pumpkin.mouth='Square'
else:
    Pumpkin.mouth='Flaming'

print("The pumpkin has a", Pumpkin.mouth, "mouth.")
time.sleep(4)
print("Here's your entire combination:")
time.sleep(3)
easygui.msgbox("A pumpkin with", Pumpkin.eyes, "eyes, a", Pumpkin.nose, "nose, and a", Pumpkin.mouth, " ", Pumpkin.expression, ".")
easygui.msgbox("Happy Halloween!")

When I ran the program, I got this:

Time to carve some pumpkins!
First things first...

The pumpkin has Fire eyes.
Okay, let's do the nose.

The pumpin has a Arrowhead nose.
Now, the mouth! But first...

The pumpkin has a Smile .
Now...

The pumpkin has a Round mouth.
Here's your entire combination:
Traceback (most recent call last):
  File "C:/Python33/Pumpkins.py", line 79, in <module>
    easygui.msgbox("A pumpkin with", Pumpkin.eyes, "eyes, a", Pumpkin.nose, "nose, and a", Pumpkin.mouth, " ", Pumpkin.expression, ".")
TypeError: msgbox() takes from 0 to 5 positional arguments but 9 were given

     Uh oh... It seems that you'll always run into problems when you program. This article is getting too long. Looks like Halloween is going to continue tomorrow!
     I challenge you to turn all the button boxes into enter boxes!
     HAPPY HALLOWEEN!

Tuesday, October 29, 2013

A Quick Tip - The Randint of a List

     You'll notice that in our hot dog program, it said this:

print(condimentlist[randomCondiments])

     In this article, we will be focusing on that. So, what the heck did we do here? Well, for starters, the only kind of random function I know so far is randint, so I had to get a little complicated. But, this is the randint of a list. We might be able to see this better if we have a simpler program that focuses mainly on that. Here's a program I wrote a long time ago for an online site, but then I realized it doesn't run Python.

import random
question=0
questionsAsked=0
fortune=0
fortune2=37
theOutput=["Yes.", "Call me AskIt!", "No.", "Maybe.", "Yes. Now go die in a hole.", "Impossible!", "Those who say impossible accomplish nothing.", "Listen to your heart and you will know the right answer.", "No way.", "Stay healthy, pet a squirrel, and wash your hair with blue cheese.", "You need to take a break off of the computer.", "If I had a body, I would strangle you.", "NU WAI!!! TEL MEE MOAR!!!!!!111!!", "NU NORBZ AWR LIEK TOTEZEZ EPIK LIEK UR BEEG TOEZ!!!!1", "I am not sure how to respond to that.", "...", "Without a doubt.", "[ Content Deleted ] JK! Try asking again.", "Just... No.", "Erik Cassel made it.", "Try asking again, and use proper grammar.", "i nu undirstandz ur grammarz.", "I can't hear you! Speak up!", "Ummm... No.", "Hey, you should do that!", "Certainly.", "It is uncertain.", "As Babe Ruth always said, 'Go home and die.'", "It is very unlikely.", "It is very likely.", "NO WAY!!", "Gross!", "Please be appropriate", "No, hackers suck.", "Errrrrrrrrrrrrrr...", "Have a fun time!", "You should not do it", "He who lacks confidence never achieves his goal."]

print("Hello, there!")
while questionsAsked < 9001:
    question=input()
    fortune=random.randint(0, fortune2)
    print(theOutput[fortune])
    theOutput.append(question)
    fortune2=fortune2 + 1
    fortune=random.randint(0, fortune2

     I know, that are some weird lines. I just wrote those to be funny. Unfortunately, I couldn't figure out how to let the user ask unlimited questions, so I made the limit 9,000. Anyway, the variables we'll be focusing on are fortune, fortune2, and theOutput.
     I guess this wasn't the best example, because I made it repeat whatever you type, but let's just go with it. So, fortune's value is 0. And fortune2's value is 37. And theOutput is a big, long list, consisting of around 36 strings. So, in Python, from 0 to the amount of items in the list +1, It is 0 to 37. Either that, or I just made a mistake and fortune2 is supposed to be 36, but I haven't seen a problem with the program yet. So, you know that when you want to print a specific item in a list, you do print(VAR[NUM])? Well, since fortune is a randint function, it counts as an integer, which qualifies as the NUM in the previous statement. So, when you run the program, you get a random item from theOutput each time! And that explains our hot dog program. Anyway, now you can have fun with AskIt!
     I realized something. Do I really need to have while questionsAsked < 9001:? I challenge you to take that line out and see how the program runs!

Sunday, October 13, 2013

Debugging Part 2 - Condiments

     Alright, let's recap: We wrote a program to help study objects, but it ended up a little complicated. We have worked out some problems in the last article, but now we have to face another problem:


mayonnaise
mayonnaise
mayonnaise
Here are the condiments:
[ERROR]

     Let's see how we can fix this... Well, first, we can try doing 2 other variables. randomCooktime2 and randomCooktime3. Let's also add in another list, so now our condiment section looks like this:

condimentlist=["ketchup", "mustard", "relish", "mayonnaise"] #Used for randomCondiments
condimentlist2=["ketchup", "mustard", "relish", "mayonnaise", " "] #Used for randomCondiments 2 and randomCondiments 3
randomCondiments=random.randint(0, 3)
randomCondiments2=random.randint(0, 4)
randomCondiments3=random.randint(0, 4)

     Yes, I used the comments, because finding everything was getting confusing. Now, let's work our magic with the other condiments!

print("Here are the condiments:")
time.sleep(3)
#The first condiment
if randomCondiments == 0:
        print(condimentlist[randomCondiments])
elif randomCondiments == 1:
        print(condimentlist[randomCondiments])
elif randomCondiments == 2:
        print(condimentlist[randomCondiments])
elif randomCondiments == 3:
        print(condimentlist[randomCondiments])

#The second condiment
if randomCondiments2 == 0:
    print(condimentlist2[randomCondiments2])
elif randomCondiments2 == 1:
    print(condimentlist2[randomCondiments2])
elif randomCondiments2 == 2:
    print(condimentlist2[randomCondiments2])
elif randomCondiments2 == 3:
    print(condimentlist2[randomCondiments2])
elif randomCondiments2 == 4:
    print(condimentlist2[randomCondiments2])

#The third condiment
if randomCondiments3 == 0:
    print(condimentlist2[randomCondiments3])
elif randomCondiments3 == 1:
    print(condimentlist2[randomCondiments3])
elif randomCondiments3 == 2:
    print(condimentlist2[randomCondiments3])
elif randomCondiments3 == 3:
    print(condimentlist2[randomCondiments3])
elif randomCondiments3 == 4:
    print(condimentlist2[randomCondiments3])
time.sleep(2)
print("Now our hot dog is complete!")

     Now, run the program. It should do something like this:

Your hot dog has been cooked for 0 minutes.
Your dog is raw .
Your wiener has ['no condiments'] .
How about we cook the hot dog? I'll cook it for a random amount of time.
I have cooked the weiner for 5 minutes.
The dog is now a well wiener .
Does it taste better?
Wait, we need condiments!
Let's cook another hot dog...
I have cooked another hot dog for 9 minutes.
So, that means the hot dog is burnt & black .
Now, perfect or not, let me put the condiments on it.
Here are the condiments:
mustard
mustard
mayonnaise
Now our hot dog is complete!

     Well, we got mustard twice. Debugging is obviously very difficult, so we can just say you got extra mustard. But if you want to make it so it never says the same condiment twice, we'll get into things so difficult I might not even be able to state them.

     So, our final program has come out like this:

import random, time


class hotDog:
    def __init__(self):
        self.cookedLevel=0
        self.cookedName="raw"
        self.condiments=["no condiments"]

    def __str__(self):
        msg="A hot dog"
        if len(self.condiments) != "no condiments":
            msg=msg + " with "
        for i in self.condiments:
            msg=msg+i+", "
        msg=msg.strip(", ")
        msg=self.cookedName + " " + msg + "."
        return msg

    def cook(self, time):
        self.cookedLevel=self.cookedLevel + time
        if self.cookedLevel > 8:
            self.cookedName="burnt & black"
        elif self.cookedLevel > 5:
            self.cookedName="perfect & pure"
        elif self.cookedLevel > 3:
            self.cookedName="a well wiener"
        else:
            self.cookedName="raw & repulsive"

def addCondiment(self, condiment):
    self.condiments.append(condiment)

theDog=hotDog()
print("Your hot dog has been cooked for", theDog.cookedLevel, "minutes.")
time.sleep(3)
print("Your dog is", theDog.cookedName, ".")
time.sleep(3)
print("Your wiener has", theDog.condiments, ".")
time.sleep(2)

print("How about we cook the hot dog? I'll cook it for a random amount of time.")
time.sleep(3)
condimentlist=["ketchup", "mustard", "relish", "mayonnaise"] #Used for randomCondiments
condimentlist2=["ketchup", "mustard", "relish", "mayonnaise", " "] #Used for randomCondiments 2 and randomCondiments 3
randomCondiments=random.randint(0, 3)
randomCondiments2=random.randint(0, 4)
randomCondiments3=random.randint(0, 4)
randomCookTime=random.randint(1, 9)
theDog.cook(randomCookTime)
time.sleep(randomCookTime)
print("I have cooked the weiner for", theDog.cookedLevel, "minutes.")
time.sleep(3)
print("The dog is now", theDog.cookedName, ".")
time.sleep(3)
print("Does it taste better?")
time.sleep(3)
print("Wait, we need condiments!")
time.sleep(3)
print("Let's cook another hot dog...")
randomCookTime2=random.randint(1, 9)
theDog.cook(randomCookTime2)
time.sleep(randomCookTime2)
print("I have cooked another hot dog for", randomCookTime2, "minutes.")
time.sleep(3)
print("So, that means the hot dog is", theDog.cookedName, ".")
time.sleep(3)
print("Now, perfect or not, let me put the condiments on it.")
time.sleep(3)
print("Here are the condiments:")
time.sleep(3)
#The first condiment
if randomCondiments == 0:
        print(condimentlist[randomCondiments])
elif randomCondiments == 1:
        print(condimentlist[randomCondiments])
elif randomCondiments == 2:
        print(condimentlist[randomCondiments])
elif randomCondiments == 3:
        print(condimentlist[randomCondiments])

#The second condiment
if randomCondiments2 == 0:
    print(condimentlist2[randomCondiments2])
elif randomCondiments2 == 1:
    print(condimentlist2[randomCondiments2])
elif randomCondiments2 == 2:
    print(condimentlist2[randomCondiments2])
elif randomCondiments2 == 3:
    print(condimentlist2[randomCondiments2])
elif randomCondiments2 == 4:
    print(condimentlist2[randomCondiments2])

#The third condiment
if randomCondiments3 == 0:
    print(condimentlist2[randomCondiments3])
elif randomCondiments3 == 1:
    print(condimentlist2[randomCondiments3])
elif randomCondiments3 == 2:
    print(condimentlist2[randomCondiments3])
elif randomCondiments3 == 3:
    print(condimentlist2[randomCondiments3])
elif randomCondiments3 == 4:
    print(condimentlist2[randomCondiments3])
time.sleep(2)
print("Now our hot dog is complete!")

     I actually think some lines in this program are never used... Oh well.
     That's it for this article. I challenge you to see if the block of code that begins with def __str__(self): really is pointless!
     Also, if you look in that block of code, you will see a function known as len(). What does this one mean?

Friday, October 4, 2013

Debugging

     Alright, let's recap. We wrote a new article called Wieners.py (at least, that's what I named it), but...

I have cooked the wiener for 6 minutes.
The dog is now perfect & pure .

     And then...

I have cooked another hot dog for 6 minutes.
So, that means the hot dog is burnt & black .

     If the dog was cooked for 6 minutes, it shouldn't be burnt & black! That's a bad sign. Well, looks like it's time to do some debugging!
     For the oblivious, a bug is not a real bug in the program. It's a problem with the program. So, to get rid of that bug is called debugging.
     Alright, as I thought about it, I realized that once randomCookTime has chosen a random number, it keeps that number. But why did the status change? Well... I honestly don't know, but I'm guessing that it did choose a different number, it just didn't display it. So, how do we fix this? My first plan is to do randomCookTime=randomCookTime.

print("Wait, we need condiments!")
time.sleep(3)
print("Let's cook another hot dog...")
randomCookTime=randomCookTime
theDog.cook(randomCookTime)
time.sleep(randomCookTime)
print("I have cooked another hot dog for", randomCookTime, "minutes.")

     Will that work? Let's just see:

Your hot dog has been cooked for 0 minutes.
Your dog is raw .
Your wiener has ['no condiments'] .
How about we cook the hot dog? I'll cook it for a random amount of time.
I have cooked the weiner for 1 minutes.
The dog is now raw & repulsive .
Does it taste better?
Wait, we need condiments!
Let's cook another hot dog...
I have cooked another hot dog for 1 minutes.
So, that means the hot dog is raw & repulsive .
Now, perfect or not, let me put the condiments on it.
Traceback (most recent call last):
  File "C:\Python33\Wieners.py", line 69, in <module>
    if theCondiment==0:
NameError: name 'theCondiment' is not defined

     Oh no! randomCookTime=randomCookTime broke the condiments! But do we give up? No! Never! I didn't expect this kind of error to happen, but I anticipated this to not work. I have a backup plan: randomCookTime2.

print("Wait, we need condiments!")
time.sleep(3)
print("Let's cook another hot dog...")
randomCookTime2=random.randint(1, 9)
theDog.cook(randomCookTime2)
time.sleep(randomCookTime2)
print("I have cooked another hot dog for", randomCookTime2, "minutes.")

     Will this work? I hope so, this is my only backup plan.

Your hot dog has been cooked for 0 minutes.
Your dog is raw .
Your wiener has ['no condiments'] .
How about we cook the hot dog? I'll cook it for a random amount of time.
I have cooked the weiner for 3 minutes.
The dog is now raw & repulsive .
Does it taste better?
Wait, we need condiments!
Let's cook another hot dog...
I have cooked another hot dog for 7 minutes.
So, that means the hot dog is burnt & black .
Now, perfect or not, let me put the condiments on it.
Here are the condiments:
relish

     Success! But, we still face one problem.
     Only one condiment ends up on the list. What if we want 2, 3, or all the condiments? This is where things get more complicated.
     Plan A is... I got it, we have to do 3 ranges!

print("Now, perfect or not, let me put the condiments on it.")
time.sleep(3)
if randomCondiments == 1:
    for i in range(0, 1):
        print(condimentlist[randomCondiments])
if randomCondiments == 2:
    for i in range(0, 2):
        print(condimentlist[randomCondiments])
if randomCondiments == 3:
    for i in range(0, 3):
        print(condimentlist[randomCondiments])
if randomCondiments == 4:
    for i in range(0, 4):
        print(condimentlist[randomCondiments])
print("Here are the condiments:")

     Will this work? We'll just see.

Your hot dog has been cooked for 0 minutes.
Your dog is raw .
Your wiener has ['no condiments'] .
How about we cook the hot dog? I'll cook it for a random amount of time.
I have cooked the weiner for 4 minutes.
The dog is now a well wiener .
Does it taste better?
Wait, we need condiments!
Let's cook another hot dog...
I have cooked another hot dog for 9 minutes.
So, that means the hot dog is burnt & black .
Now, perfect or not, let me put the condiments on it.
mayonnaise
mayonnaise
mayonnaise
Here are the condiments:
Traceback (most recent call last):
  File "C:\Python33\Wieners.py", line 81, in <module>
    print(theCondiment)
NameError: name 'theCondiment' is not defined

     That's a bad sign. This article has gone on long enough. We'll have to fix our mayonnaise next time!

Saturday, September 28, 2013

Hot Dogs

     Alright, I think we should tinker around more with objects for practice. I admit, it's getting sort of confusing!
     This time we'll work with meat tubers, or hot dogs.

class hotDog:

     The attributes we will give the hot dog are how long we cooked the hot dog, if it's raw, medium, well-done, or burnt, and what condiments it has.

    def __init__(self):
        self.cookedLevel=0
        self.cookedName="raw"
        self.condiments=["no condiements"]

     Yep, that's a pretty good tasting hot dog right there.
     Well, it may not be cooked or have any condiments, but before we do anything, we should program the levels from raw meat to charcoal.

    def cook(self, time):
        self.cookedLevel=self.cookedLevel + time
        if self.cookedLevel > 8:
            self.cookedName="burnt & black"
        elif self.cookedLevel > 5:
            self.cookedName="perfect & pure"
        elif self.cookedLevel > 3:
            self.cookedName="a well wiener"
        else:
            self.cookedName="raw & repulsive"

     There's our levels. Now, let's cook those dogs!
     Here is the full program. The sleeping time parts are just so the words don't go by so quickly. Here is the full program:

import random, time


class hotDog:
    def __init__(self):
        self.cookedLevel=0
        self.cookedName="raw"
        self.condiments=["no condiments"]

    def cook(self, time):
        self.cookedLevel=self.cookedLevel + time
        if self.cookedLevel > 8:
            self.cookedName="burnt & black"
        elif self.cookedLevel > 5:
            self.cookedName="perfect & pure"
        elif self.cookedLevel > 3:
            self.cookedName="a well wiener"
        else:
            self.cookedName="raw & repulsive"

theDog=hotDog()
print("Your hot dog has been cooked for", theDog.cookedLevel, "minutes.")
time.sleep(3)
print("Your dog is", theDog.cookedName, ".")
time.sleep(3)
print("Your wiener has", theDog.condiments, ".")
time.sleep(2)

print("How about we cook the hot dog? I'll cook it for a random amount of time.")
time.sleep(3)
randomCookTime=random.randint(1, 9)
theDog.cook(randomCookTime)
time.sleep(randomCookTime)
print("I have cooked the weiner for", theDog.cookedLevel, "minutes.")
time.sleep(3)
print("The dog is now", theDog.cookedName, ".")
time.sleep(3)
print("Does it taste better?")


     Alright! Save this in a new program, and run it. This is what I got:

Your hot dog has been cooked for 0 minutes.
Your dog is raw .
Your wiener has ['no condiments'] .
How about we cook the hot dog? I'll cook it for a random amount of time.
I have cooked the wiener for 7 minutes.
The dog is now perfect & pure .
Does it taste better?

     You should get something like that (but you might get a different time at line 5 and a different title at line 6). But, we're not finished just yet! This hot dog has no condiments! Things are about to get trickier...
     Here's the new and improved program:

import random, time


class hotDog:
    def __init__(self):
        self.cookedLevel=0
        self.cookedName="raw"
        self.condiments=["no condiments"]

    def __str__(self):
        msg="A hot dog"
        if len(self.condiments) != "no condiments":
            msg=msg + " with "
        for i in self.condiments:
            msg=msg+i+", "
        msg=msg.strip(", ")
        msg=self.cookedName + " " + msg + "."
        return msg

    def cook(self, time):
        self.cookedLevel=self.cookedLevel + time
        if self.cookedLevel > 8:
            self.cookedName="burnt & black"
        elif self.cookedLevel > 5:
            self.cookedName="perfect & pure"
        elif self.cookedLevel > 3:
            self.cookedName="a well wiener"
        else:
            self.cookedName="raw & repulsive"

def addCondiment(self, condiment):
    self.condiments.append(condiment)

theDog=hotDog()
print("Your hot dog has been cooked for", theDog.cookedLevel, "minutes.")
time.sleep(3)
print("Your dog is", theDog.cookedName, ".")
time.sleep(3)
print("Your wiener has", theDog.condiments, ".")
time.sleep(2)

print("How about we cook the hot dog? I'll cook it for a random amount of time.")
time.sleep(3)
condimentlist=["ketchup", "mustard", "relish", "mayonnaise"]
randomCondiments=random.randint(0, 3)
randomCookTime=random.randint(1, 9)
theDog.cook(randomCookTime)
time.sleep(randomCookTime)
print("I have cooked the weiner for", theDog.cookedLevel, "minutes.")
time.sleep(3)
print("The dog is now", theDog.cookedName, ".")
time.sleep(3)
print("Does it taste better?")
time.sleep(3)
print("Wait, we need condiments!")
time.sleep(3)
print("Let's cook another hot dog...")
theDog.cook(randomCookTime)
time.sleep(randomCookTime)
print("I have cooked another hot dog for", randomCookTime, "minutes.")
time.sleep(3)
print("So, that means the hot dog is", theDog.cookedName, ".")
time.sleep(3)
print("Now, perfect or not, let me put the condiments on it.")
time.sleep(3)
for i in range(randomCondiments):
    theCondiment=i
if theCondiment==0:
    theCondiment="ketchup"
elif theCondiment==1:
    theCondiment="mustard"
elif theCondiment==2:
    theCondiment="relish"
else:
    theCondiment="mayonnaise"
print("Here are the condiments:")
time.sleep(3)
print(theCondiment)

     There is really an easier way to explain this, but I'm going the creative way to make a fun hot dog program that doesn't do the same thing every time.
     When I ran the program, I got this:

Your hot dog has been cooked for 0 minutes.
Your dog is raw .
Your wiener has ['no condiments'] .
How about we cook the hot dog? I'll cook it for a random amount of time.
I have cooked the weiner for 6 minutes.
The dog is now perfect & pure .
Does it taste better?
Wait, we need condiments!
Let's cook another hot dog...
I have cooked another hot dog for 6 minutes.
So, that means the hot dog is burnt & black .
Now, perfect or not, let me put the condiments on it.
Here are the condiments:
ketchup

     Ta-da! Wait...
     When the hot dog was cooked for 6 minutes, it was perfect & pure. I get that, but there's one problem that happened here...
     The wiener was cooked for the same amount of time, and the hot dog ended up burnt & black!
     This article's been going on a bit too long. We'll do some debugging next time!

Sunday, September 8, 2013

__str__()

     __init__(), a __xxxx__() function is a special method that initializes an object when it's created. All objects have an automatic one, so when you don't use __init__(), it will automatically initialize anyway. And then there is __str__(), which let's Python know what you want it to say. What do I mean? Try printing the object in one of our previous programs:

Ball2.py

print(Ball2) -- <class '__main__.Ball2'>
print(theBall) -- <__main__.Ball2 object at 0x02BD9570>

Ball.py

print(Ball) -- <class '__main__.Ball'>
print(theBall) -- <__main__.Ball object at 0x02AD2E90>

     As you saw here, Python told you where the instance is defined (or __main__, A.K.A. the main part of the program), the class name (Ball2/Ball), and where Python stores it in its memory (0x02BD9570/0x02AD2E90).
     If you want Python to say something you actually want to understand, you would use __str__() like this:

class Ball3:
    def __init__(self, color, size, direction):
        self.color = color
        self.size = size
        self.direction = direction

    def __str__(self):
        msg="This ball is a " + self.size + ", " + self.color + " ball."
        return msg

theBall=Ball3("purple", "big", "down")
print(theBall)

     What's with the plus signs (+)? Well, I'm not exactly sure, but you need this for a tuple. Otherwise...

Traceback (most recent call last):
  File "C:/Python33/Ball3.py", line 12, in <module>
    print(theBall)
TypeError: __str__ returned non-string (type tuple)

     Anyway, after debugging it, it should end up doing this:

This ball is a big, purple ball.

     Seems to be a lot of trouble to go through as you can always just do

print("This ball is a big, purple ball.")

     But this way is an option, because you might need to describe the attributes thousands of lines of code later, and you just don't want to go back and look for it if you forget it. That's the beauty of computers: You can forget all you want.
     I think I've rambled on long enough for one article. See ya later!

Saturday, August 31, 2013

A Quick Tip - What is __init__()?

     In the last program we did, we used a function known as __init__(). To help make programming easier, we have to know what the functions even mean. So, what in the heck does this one mean?
     Alright, you could actually just look back an article and figure it out. But, if you don't want to or still don't get it, here's what I would say:
     An instance of theBall (in the last article) is Ball2. __init__() will run whenever an instance is created, so Ball2 activates it. You are able to pass arguments to __init__() to make the instance with the properties set any way you want it to be. You could always look at the Ball2.py program to help jog your memory, too. I'm not gonna lie, this is sort of confusing. But, we only used it to set the object's properties, and that's probably the only thing it is used for.
     There's not just __init__(), there are many functions of that type. What I'm talking about are __xxxx__() functions. We will cover them next time!

Tuesday, August 6, 2013

A Quick Tip - Initializing

     In our Ball.py program, we created the attributes after the object was created. However, there's a way to create the attributes, or properties, when the object is being created. It's called initializing, with the __init__() function.

     I'm not quite sure (yet) how useful adding properties to an object when it's created is, But we might find a use for it in future articles.

     Remember: this function uses four underscores (_) and not just two!

     Alright, let's make a copy of our ball program, but this time, we will use __init__().

class Ball2:

    def __init__(self, color, size, direction):
        self.color=color
        self.size=size
        self.direction=direction

    def bounce(self):
        if self.direction == "down":
            self.direction = "up"

theBall=Ball2("yellow", "large", "down")

print("The ball has been loaded.")
print("The ball is", theBall.color)
print("The ball is", theBall.size)
print("The ball is going", theBall.direction)
print("Let's bounce the ball.")
theBall.bounce()
print("The ball is now going", theBall.direction)

     It will run exactly the same as our first ball program. This will be a handy tip later on! I'm sure of it!

Sunday, July 28, 2013

Objects

     Lists gather variables and values together to use repeatedly. Functions gather code together to use repeatedly. And then there's objects. No, not the chair or couch you may be sitting on or the computer you're using, but objects which collect functions and other data together.
     Real world objects have things you can do with them, or actions. They also have certain attributes, or properties.  This same rule applies with Python as well.
     In Python, characteristics you know about an object are attributes. Things you can do with them are methods.
     Let's say we were making a ball in Python. The ball would have attributes and methods. The attributes would look like this:

ball.color
ball.size
ball.weight

     The methods would look like this:

ball.kick()
ball.throw()

     Etc.
     The attributes of the object are whatever you know, or will know about it. They're bits and pieces of information, which are numbers, strings, etc. Variables. Variables that are inside the object.
     The methods of the object are something you can call to do something. Functions. Functions that are inside an object.
     So, attributes are information, and methods are actions. Objects collect those two together. Alright, now that you hopefully understand what objects are by now, let's start making some!
     We need to make an object with these steps: first, we make the class. The class keyword tells Python IDLE you are making an object. We use the class to make an instance, or the object. You define what the object looks like, and then you put your object to use. Let's write this program in a new window!

     class Ball:

    def bounce(self):
        if self.direction == "down":
            self.direction = "up"

     Alright, here's our object. That self keyword is a big thing in making games. This is a hint that we're getting to the big stuff soon!
     So, all we have right now is a class definition for a ball with one method, bounce(). There are no attributes because they really don't belong to the class, but its instance. Hey, speaking of instances, why don't we give our object some?
     If we want an instance of our Ball, we'd do something like this:

theBall=Ball()

     We have no attributes for our ball, so let's get that taken care of.

theBall.size="small"
theBall.color="purple"
theBall.direction="down"

     Alright, we've got the attributes covered. Now, let's see our bounce() method again.
     This is how we would use it.

theBall.bounce()

     Okay, looking good. Let's put all of this in our program. We will also add in some print statements so we'll know what's happening.

class Ball:

    def bounce(self):
        if self.direction == "down":
            self.direction = "up"
         
theBall=Ball()
theBall.size="small"
theBall.color="purple"
theBall.direction="down"


print("The ball has been loaded.")
print("The ball is", theBall.size)
print("The ball is", theBall.color)
print("The ball is going", theBall.direction)
print("Let's bounce the ball.")
theBall.bounce()
print("The ball is now going", theBall.direction)

     Now let's test this. Run the program and see what happens.

>>> ================================ RESTART ================================
>>>
The ball has been loaded.
The ball is small
The ball is purple
The ball is going down
Let's bounce the ball.
The ball is now going up

     The bounce() function changed our balls direction! That's pretty cool, don't you think?
     That's about it for this article. See you later!

Friday, July 19, 2013

Global

     So, global variables are variables that can be used outside of a function. But what happens when we use them inside a function? Well, let's create a new program, and write this:

def groceries(oranges):
    orangePrice = 1.53
    print("Orange price inside function: ", orangePrice)
    orangeTotal=orangePrice * oranges
    return orangeTotal

print("Enter a price for the oranges")
orangePrice=float(input())

totalPrice = groceries(3)

print("Orange price outside function: ", orangePrice)

print("Orange total: ", totalPrice)

     Now, let's save the program and run it. Let's say, each orange costs $3, so type "3" when you run the program. So, here's what should happen.

Enter a price for the oranges
3
Orange price inside function:  1.53
Orange price outside function:  3.0
Orange total:  4.59

     Hold on a second, $3 times $3 doesn't equal $4.59! $1.59 times 3 equals $4.59! What about our oranges that cost $3 each? Well, this program here has a bug.
     No, not a real bug. There's a problem that doesn't make it run right. How did we get this bug, though? Well, orange price is $1.59 when it's being used inside the function, and is the user's input outside of the function. The user's input doesn't even exist during the function! It's a little confusing, but all we have to do to fix this is with the global function. Retry the program, instead with this code:

def groceries(oranges):
    global orangePrice
    print("Orange price inside function: ", orangePrice)
    orangeTotal=orangePrice * oranges
    return orangeTotal

print("Enter a price for the oranges")
orangePrice=float(input())

totalPrice = groceries(3)

print("Orange price outside function: ", orangePrice)

print("Orange total: ", totalPrice)

     The program should be debugged now and you should get this:

Enter a price for the oranges
3
Orange price inside function:  3.0
Orange price outside function:  3.0
Orange total:  9.0

     The program has now calculated the price correctly! You see, the user's input didn't exist in the function because it was created after the function. I know, still confusing, but that's the best explanation I can think of. But with the global keyword, the function knew there was a variable somewhere in the program it needed to use. This can be very useful when you need to use something in a function and somewhere else!

     That's just about it for this article. I challenge you to edit the program so it takes several different prices inputted by the user!

Thursday, July 11, 2013

Local

     Can the functions only have 1 argument? The answer is no. You can have as many as you want! You simply do this:

>>> def randomwords(randomword, otherRandomWord):
print(randomword)
print(otherRandomWord)
print("CHEESE")

>>> randomwords("Pickles", "Cow")
Pickles
Cow
CHEESE


     Remember to do the values in order! Otherwise they will be switched around.
     That was only 2 arguments, but that's not all you can do. You can do over 9,000 arguments (if you have the patience, not to mention time, to do that) if you want to. Although... If you want to do at least five or six arguments, you might want to think of doing a list instead of a bunch of variables.

     It's possible for a function to return things to us. It's called a result.
     In order to get results, you use the return function. Try this:

>>> def groceries(oranges):
            orangeCost=9
            orangeTotal=orangeCost * oranges
            return oranges

>>> groceries(3)
27
>>> groceries(8)
72
>>> groceries(19)
171
>>> groceries(9001)
81009

     So, our block of code used the parameter (or argument) to figure something out, then gave us what it figured. That's how the return function works. If you want to do stuff with the return value, you can simply call it inside a variable.
     orangeCost, oranges, and orangeTotal are all in the same block of code. The same line, even. Being variables, these are called local variables.
     Local variables only exist while the function is running. Try printing each variable:

>>> print(orangeCost)
Traceback (most recent call last):
  File "<pyshell#22>", line 1, in <module>
    print(orangeCost)
NameError: name 'orangeCost' is not defined
>>> print(orangeTotal)
Traceback (most recent call last):
  File "<pyshell#23>", line 1, in <module>
    print(orangeTotal)
NameError: name 'orangeTotal' is not defined
>>> print(oranges)
Traceback (most recent call last):
  File "<pyshell#24>", line 1, in <module>
    print(oranges)
NameError: name 'oranges' is not defined

     Right. That's what a local variable is. If a variable is in the main part of a program, and not in a function, that is called a global variable.
     We will continue global variables in the next article. See you next time!

Thursday, July 4, 2013

Def and Arguments

     Hopefully you still have the list from the last article, because we're doing a bit more with it!
     Alright, we have a list of lists here named traits. What if we want an item inside an item of the list? Okay, lemme just explain what I said, if you find it a bit too confusing; We have 3 lists in a list. What if we want a single item from 1 of those lists? We know that we can get an entire list (because each list is an item in traits) like this;

>>> print(traits[0])

['Blue', 'No', 'Yes', 'No']

     But what if we want only one of those items? Well, we add a second index.

print(traits[0] [3])

No

     There you have it. That's the last thing about tables I have to talk about, so let's move on to the next thing:  def.

     Def basically skips a block of code. You use it before a variable, just like for and while loops. Write this:

>>> def randomwords():
print("Hi")
print("Pears")
print("CHEESE")


>>> randomwords()
Hi
Pears
CHEESE

     We'll get to why there are parenthesis after randomwords in a second. When we used def, it skipped the entire block of code and did nothing. Doing this allowed us to activate the block whenever we wanted, just by repeating the variable after def. Of course we didn't type the colon (:), because that's not part of the variable. It tells Python you are making a block of code.
     Alright, now why are the parenthesis there? Well, without the parenthesis, you wouldn't be able to call (or activate) the block of code, because Python doesn't understand you if you just typed "randomwords." Python wouldn't know whether it's a string or an integer or anything, so you get an error. With the parenthesis, Python knows you're calling for the block of code and activates it. Also, as always, we might put things in parenthesis.
     A good thing about the def function is that you can print it over and over as many times as you like, like a loop. However, instead of printing it several times at once, you can print it anywhere you want in the program. But, that's not what we're focusing on in this paragraph. That statement set aside... What can we put in the parenthesis? A little something I like to call (okay, everyone calls it this), arguments!
     Not arguments like two people disagreeing, computers never argue. In programming, argument means a piece of information you give to a function. If you don't want a def function to be the same every time you activate it, you put an argument in the parenthesis. Arguments are variables, so you can call them whatever you want.
     Arguments are tricky to understand unless you get an example with a program. I'll change the first print statement in randomwords to an argument named randomword. Here's my example:

>>> def randomwords(randomword):
print(randomword)
print("Pears")
print("CHEESE")


>>> randomwords("Pie")
Pie
Pears
CHEESE

     When you put a variable in the parenthesis, then somewhere in your block of code, you can change that variable to something every time you call it. Pretty neat, huh? That way you don't have to print the same thing (with something slightly changed, of course) over and over again.
     In this article, you learned about def and arguments. What programs can you make now with you knowledge? After we get through all the functions, objects, and modules, we will be moving onto making our own computer games! But for now, bye!
     Oh, I almost forgot, happy 4th of July!

Wednesday, July 3, 2013

Mutable, Immutable, and Tables

     If I haven't mentioned this already, it's impossible to change numbers and strings. Not unless a variable (or name) is assigned to them. With lists, you can change whatever's in it. Appending, deleting, sorting, reversing, all that stuff. These things are called mutable and immutable.
     Mutable means something can be changed. It is "changeable." Immutable means it can't be changed.
     Is there such a thing as an immutable list? Yes there is. It's called a tuple. Type this in Python IDLE:

tuple1=("Apples", "Bananas", "Watermelon")

     Instead of square brackets ([]), we used parenthesis (()). Once you make this list, you can't change it. Well, you could change it if you write it in a program, but that's not the point. You can't append, pop, delete, extend, insert, sort, reverse, or any of those things you can do with a normal list. This is an immutable list.



     It's useful to visualize how data is stored in a program.

     A variable has a single value.         person --> 'Bob'
     A list is like a bunch of values assigned to one variable. family --> 'Jack', 'Tim', 'Mom', 'Dad', 'Willy', 'Betty'
     Sometimes you need to make a table, a chart with rows and columns.
     traits --> Eye color   Widow's peak   Freckles   Left handed
     Jack      | Blue         | No                  | Yes        | No
     Tim       | Green       | No                  | No         | Yes
     Willy     | Blue         | Yes                  | No        | No

     Wait, what? A table? In order to do that, we make a series of lists.
     We could make a list of traits for each person, like so:

>>> jackTraits=['Blue', 'No', 'Yes', 'No']
>>> timTraits=['Green', 'No', 'No', 'Yes']
>>> willyTraits=['Blue', 'Yes', 'No', 'No']

     Or we could organize the table in columns, like this:

>>> eyeColor=['Blue', 'Green', 'Blue']
>>> widowsPeak=['No', 'No', 'Yes']
>>> freckles=['Yes', 'No', 'No']
>>> leftHanded=['No', 'Yes', 'No']

     We might want to collect this data together in a little something called a data structure.
     I'll be using the rows, just so you know. It doesn't really make a difference, except the layout will be different in the end. First, let's make another list.

traits=[jackTraits, timTraits, willyTraits]
print(traits)

[['Blue', 'No', 'Yes', 'No'], ['Green', 'No', 'No', 'Yes'], ['Blue', 'Yes', 'No', 'No']]

     That is a list of lists. Each item in the list is a list itself. Now, to display it in a table...

for allTraits in traits:
    print(allTraits)

['Blue', 'No', 'Yes', 'No']
['Green', 'No', 'No', 'Yes']
['Blue', 'Yes', 'No', 'No']

     There we go. Doesn't quite look like a table, but it helps to visualize it like one.
     This article is getting a bit too long! Keep those lists ready, because we'll continue this in the next one!

Tuesday, June 11, 2013

A Quick Tip - Sorting Copies

     When you sort a list, the original is lost. If you want to keep the original and sort a copy, you have to do this:

numbers=['5', '3', '6', '1', '4', '2']
numbers2=numbers[:]

numbers2.sort()

print(numbers)

['5', '3', '6', '1', '4', '2']

print(numbers2)

['1', '2', '3', '4', '5', '6']

     If you want to know why you need the "[:]," keep reading. If you are not interested, you can skip the next paragraph.

     "numbers2=numbers" means that "numbers2" is "numbers." But, as you learned when you first started lists, "[:]" means all the items in a list, so "numbers2=numbers[:]" makes "numbers2" a list of all the items in "numbers."



     Alright, that was kind of complicated, right? Well there's another way to sort lists--sorted().
      Let's make a new variable:

numbers3=sorted(numbers)

     Now, what did we do?

print(numbers)

['5', '3', '6', '1', '4', '2']

print(numbers3)

['1', '2', '3', '4', '5', '6']

     So that's what sorted() does. It gives you a sorted copy of the list, like before.

Sunday, June 2, 2013

Looping and Sorting Lists

     There's still more about lists, and here's one of the next tricks in the book: looping.
     When you loop through a list, IDLE displays every item in the list on separate lines, and here's how to make that happen:

for i in numbers:
    print(i)

1
2
3
4
5
6

     So that happens. Just for fun, what happens when you do:

for i in numbers:
    print(numbers.index)

<built-in method index of list object at 0x02DA5AD0>
<built-in method index of list object at 0x02DA5AD0>
<built-in method index of list object at 0x02DA5AD0>
<built-in method index of list object at 0x02DA5AD0>
<built-in method index of list object at 0x02DA5AD0>
<built-in method index of list object at 0x02DA5AD0>

     I just wanted to show you that. Now, let's move on to sorting, as you know from the title.
     Let's mix up the items in our list:

numbers=['4', '1', '6', '2', '5', '3']

     sort() rearranges the list alphabetically and/or numerically. Let's try it with this list.

numbers.sort()

print(numbers)

['1', '2', '3', '4', '5', '6']

     Magic! No, not really.
     Now, what if we wanted to sort in reverse order? We use reverse().

numbers.reverse()

print(numbers)

['6', '5', '4', '3', '2', '1']

     More magic! No, it's not magic. It's technology. There's another way we can reverse lists:

numbers.sort(reverse=True)

print(numbers)

['1', '2', '3', '4', '5', '6']

     People would probably prefer reverse() because it's a little faster to type and easier to remember, but you can choose what you want.

Wednesday, May 15, 2013

Finding Items in a List

     Now that you know enough about Python, it's about time we get back to lists.
     What if we have a really long list, and we want to find an item in it? To search a list, we have to use the in function.
     You probably got rid of the family list from the other articles, so let's make a different one.

numbers=['1', '2', '3', '4', '5', '6']

     Let's say we don't know if the number 3 is in the list. This is where the function comes in:

if '3' in numbers:
    print("3 is in the numbers.")
else:
    print("3 is not in the numbers.")

     You should get "3 is in the numbers." Let's try this again, but with a number that really isn't in the list.

if '10' in numbers:
    print("10 is in the numbers.")
else:
    print("10 is not in the numbers.")

     You should get "10 is not in the numbers." The in statement basically debates if an item being in the list is true or false.
     There's even a kinda faster way to do this:

'1' in numbers

     This should appear:

True

     But if you do a false one:

'99' in numbers

False

     So if you do a quick thing like that, it just says "True" or "False."
     You can even do a group of numbers at a time, like this:

'1' in numbers and '2' in numbers and '3' in numbers and '4' in numbers and '5' in numbers

True

     But if 1 number is not in the list...

'1' in numbers and '2' in numbers and '7' in numbers

False

     There you have it. We can even remove items we found in the list, like this:

if '6' in numbers:
    numbers.remove('6')

print(numbers)

['1', '2', '3', '4', '5']

     You can even remove a number if a different one is in the list.

if '1' in numbers:
    numbers.remove('5')

print(numbers)

['1', '2', '3', '4']

     Now that we have that covered, what if we want to find an item's index?

numbers.extend(['5', '6'])

     (I had to put the numbers back in since I was running out.)

print(numbers.index('5'))

4

     That is the index of the number, not the number itself (duh). You can do the same thing with index() that you can do with remove().

if '6' in numbers:
    print(letters.index('6'))

5

     You can also do the other thing I explained with remove(), if a certain number is in the list, then remove a different number.
     Well, that's all there is to searching a list. That was a lot to cover in this article, wasn't it?

Saturday, May 4, 2013

Randint

     Another function I have deciphered is random.randint().
     First, you have to type:

import random

     Now, what does randint mean? It actually means random integer. Now, type this:

print(random.randint(1, 12))

     The output should be a random number. Keep typing the same thing, and you'll notice that the number keeps changing.
     You can also use random.randint with lists! Type this:

list=["Hi", "Bye", "Die"]
listInt=random.randint(0, 2)
print(list[listInt])

     You should get one of the items from the list. Remember, lists start with 0, not 1. You tell Python to print list, but then listInt in the square brackets tells it to take a random item from the list and print it. What if we did one that's out of range?

listInt=random.randint(0, 15)
print(list[listInt])

Traceback (most recent call last):
  File "<pyshell#10>", line 1, in <module>
    print(list[listInt])
IndexError: list index out of range

     So, it has to be the limit of items in the list.
     That's all I know about random.randint, so... That's it.

Monday, April 29, 2013

Sleeping Time

     Here is another quick tip about a new function called time.sleep().
     I'm not sure yet if this is the only function for time, but it is an important function for time.
     Now, in order to use time, you have to type:

import time

     But, we might want to do this in a New Window, not IDLE. Type "import time" in a New Window (I bet I got you there, didn't I?). Now, type the following:

time.sleep(4)
print("Hi.")

     Now, run the program. At first, you won't get anything... But, then, "Hi." finally appears. How did that happen? Time.sleep() actually pauses the program for the amount of seconds in the parenthesis (()).
     I guess that's all we had to talk about here. I challenge you to try to write a countdown program (hint: you will need to use a for loop)! You don't have to make the program ask the user how many seconds and/or what kind of time they want (seconds, minutes, or hours), but you can try!

Saturday, April 27, 2013

Resizing the Choice Box

     As I said, I was going to tell you how to resize the enter box. It's a bit complicated, so be careful!
     1: Find the section in the easygui.py file that starts with def __choicebox, maybe around line 613. Remember that most editors, including SPE, show you the code line numbers somewhere near the bottom of the window.
     2: About 30 lines down from that (around line 645), you'll see some lines that look like this:

root_width = int((screen_width * 0.8))
root_height = int((screen_height * 0.5))

     3: Change the 0.8 to 0.4 and the 0.5 to 0.25. Save the changes to easygui.py. The next time try the choice box, it will be smaller.

GUI: Graphical User Interface

     So far, everything we've done doesn't have an image displayed. Weird to think, right? You always thought you were displaying images, weren't you? Well, you weren't. All the pictures you see on every site, every game, even this blog and Python IDLE, uses something that displays images called GUIs.
     Now, what is a GUI? It stands for Graphical User Interface. Those are big words, so let me simplify it: images on the screen the person playing the game (or anything else) interacts with. If you don't know what "interacts" means... Oh well.
     GUI is an acronym, but it's pronounced "gooey."
     Now, to use a GUI in Python, you need to have a GUI program. We will start out with EasyGui. And, before you download it, let me tell you that you need to put it in a folder Python can find. It should automatically do that, but, just in case, check where the file will be, and put it in a Python file. I recommend putting the file where Python itself is, which is called Python33. Alright, now that you have been informed, the link to the EasyGui download is here.
     Now, let's start with the basics of GUIs. You actually don't need to write a program to use EasyGui, so just type this:

import easygui

     Saying that allows you to use EasyGui! Now, do this:

easygui.msgbox("Hi!")

     A window should pop up saying "Hi!," and under that is a button that says "OK." Press that, and in Python, it will display what you pressed, which was 'OK'
     Msgbox is message box, a window that has only one button to press, "OK." After you press that button, you should get this in Python IDLE:

'OK'

     Python displays what you select. However, this is not the only thing you can do with GUIs. Another type of GUI window called button box.
     Button boxes may be a little bit tricky, but you will get used to them. Type this:

easygui.buttonbox("Hi!")

     A window should pop up saying, "Hi!" and 3 options to click: Button1, Button2, and Button3. Let's say, if you click Button2, Python will say:

'Button2'

     Like the message box, Python displays your answer. However, what if we want to rename the buttons? Do this:

choices=easygui.buttonbox("Hi!", choices=["Hi!", "GO AWAY"])

     Choose either button. This time, it does not display your choice. Now, to make EasyGui respond to the button you selected, try this:

if choices == "Hi!":
    easygui.msgbox(":)")
elif choices == "GO AWAY":
    easygui.msgbox(":(")

     If you chose the first button, you should get a window that says, ":)." If you chose the other option, you should get ":(." Hopefully you remember how to use button boxes. Maybe it's just me that always forgets how to use them.
     There's another way button boxes work. This one is less complicated or however you think of it.

easygui.buttonbox("Hi!",
    choices=["Hi!", "GO AWAY"])

     This works exactly like the other way. You can choose which way you want to do it, but I prefer the first way.
     There's also a type of window called a choice box. It works like a button box, but has a different layout. Type this:

choices=easygui.choicebox("Hi!", choices=["Hi!", "GO AWAY"])

     You should get a large box with a big white area. The topmost line will say "GO AWAY" and be highlighted. Under that should be "Hi!" When you select one of the choices, that line is highlighted. Nothing will happen when you click OK, but, if you want, you can do what we did with the button box and make it respond. Also, if you don't want the GUI to be so big, we will discuss that in the next article.
     Yet another way to use EasyGui is with an enter box. Type this in Python:

easygui.enterbox("Hi!")

     You should get a window that says "Hi!" and a white bar under it, where you can type anything you want. When you type in what you want to say and click OK, Python will display what you typed. If you want the GUI to respond to a certain thing you typed, you have to do this:

input=easygui.enterbox("Hi!")

     The window will pop up. Now say something, like, "Hi!"

if input == "Hi!":
    easygui.msgbox("Nice to meet you!")

     An enter box isn't the best choice to do if you want a certain input, considering the trillions of things people could type, but it is good for a game where you have to figure out a code.
     Finally, there's the integer box. There is no float box that I've heard of (yet), but this box allows you to type in a whole number. Type this:

easygui.integerbox("What is 1 + 1?")

     You can type in whatever you want, but if it's not an integer, it will display the window again. If you want a certain response, you will have to do the same thing we did with the enter box.
     In this article, we learned about the 5 kinds of GUI boxes. There's no limit to GUIs! As promised, the next article will pertain to how you can make the enter box smaller.