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!