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!