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!
Monday, April 29, 2013
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.
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.
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.
Wednesday, April 24, 2013
A Quick Tip - Changing Types of Numbers
I am going to tell you some functions that might be useful, float(), int(), and str().
number="33.33"
number
'33.33'
float(number)
33.33
When you printed "number" (the second line worked as a print statement), it took 33.33 as a string, and put those apostrophes around it. When you used float(), it turned it into a float, or decimal. What if you want to do this with an integer, or whole number? Well, try this:
number="33"
number
'33'
int(number)
33
Worked just like the float. Here's a question you might have: What if you did this?
number="33.33"
int(number)
Well, here is what happens:
Traceback (most recent call last):
File "<pyshell#12>", line 1, in <module>
int(number)
ValueError: invalid literal for int() with base 10: '33.33'
We get an error. What if we try it the other way around?
number="33"
float(number)
33.0
We just get a ".0" added to the end of it. But, we can do something else rather than altering numbers. Let's try this:
number=33 + 2
number
35
str(number)
'35'
Here, we went the opposite way. We changed the answer of the problem into a string.
Here, you learned how to convert numbers to strings and strings to numbers. But, before the article ends, let's do some experimenting:
number=3
number
3
number=str(number)
number
'3'
number="33 + 2"
number
'33 + 2'
int(number)
Traceback (most recent call last):
File "<pyshell#24>", line 1, in <module>
int(number)
ValueError: invalid literal for int() with base 10: '33 + 2'
I think that's all I wanted to try out. So... Yeah.
number="33.33"
number
'33.33'
float(number)
33.33
When you printed "number" (the second line worked as a print statement), it took 33.33 as a string, and put those apostrophes around it. When you used float(), it turned it into a float, or decimal. What if you want to do this with an integer, or whole number? Well, try this:
number="33"
number
'33'
int(number)
33
Worked just like the float. Here's a question you might have: What if you did this?
number="33.33"
int(number)
Well, here is what happens:
Traceback (most recent call last):
File "<pyshell#12>", line 1, in <module>
int(number)
ValueError: invalid literal for int() with base 10: '33.33'
We get an error. What if we try it the other way around?
number="33"
float(number)
33.0
We just get a ".0" added to the end of it. But, we can do something else rather than altering numbers. Let's try this:
number=33 + 2
number
35
str(number)
'35'
Here, we went the opposite way. We changed the answer of the problem into a string.
Here, you learned how to convert numbers to strings and strings to numbers. But, before the article ends, let's do some experimenting:
number=3
number
3
number=str(number)
number
'3'
number="33 + 2"
number
'33 + 2'
int(number)
Traceback (most recent call last):
File "<pyshell#24>", line 1, in <module>
int(number)
ValueError: invalid literal for int() with base 10: '33 + 2'
I think that's all I wanted to try out. So... Yeah.
Tuesday, April 23, 2013
While Loops
Now that you know about for loops, you need to learn while loops, another element of input.
While loops are loops that keep going unless a condition is false, sort of like an if statement. While loops are said in the same way as an if statement. Of course, the most common way to use while loops is with input, so we will do that. Open a new program and type this:
print("Type 3 to continue, anything else to quit.")
someInput=input()
while someInput == 3:
print("Thank you for the 3. Very kind of you.")
print("Type 3 to continue, anything else to quit")
someInput=input()
print("That's not a 3, so I'm quitting now.")
Run the program. You should get the first print statement. If you type a 3, you should get "Thank you for the 3. Very kind of you." then "Type 3 to continue, anything else to quit." If you type anything else, you should get "That's not a 3, so I'm quitting now." So, the word after while wasn't the name of a loop. That only happens with for loops. Now, what if you make a mistake with loops? That is called a runaway loop. Runaway loops are loops that keep on going forever because you made a mistake, and there's no way to get out. To get out of a runaway loop, you have to press CTRL+C. That crashes any program.
Now, what did the while loop do? Well, while loops are like for loops, except they keep going unless a condition is false. While loops always ask the program, "Am I done yet?" until it is done. I hope you get while loops already, since I can't think of anything else to help you get it.
Well... There wasn't much to talk about in this article. Here, you learned about while loops. There still isn't much you know about loops, but I can challenge you to do this; try to make a runaway loop that uses input (it's easy, trust me), and one that doesn't use input (even easier).
While loops are loops that keep going unless a condition is false, sort of like an if statement. While loops are said in the same way as an if statement. Of course, the most common way to use while loops is with input, so we will do that. Open a new program and type this:
print("Type 3 to continue, anything else to quit.")
someInput=input()
while someInput == 3:
print("Thank you for the 3. Very kind of you.")
print("Type 3 to continue, anything else to quit")
someInput=input()
print("That's not a 3, so I'm quitting now.")
Run the program. You should get the first print statement. If you type a 3, you should get "Thank you for the 3. Very kind of you." then "Type 3 to continue, anything else to quit." If you type anything else, you should get "That's not a 3, so I'm quitting now." So, the word after while wasn't the name of a loop. That only happens with for loops. Now, what if you make a mistake with loops? That is called a runaway loop. Runaway loops are loops that keep on going forever because you made a mistake, and there's no way to get out. To get out of a runaway loop, you have to press CTRL+C. That crashes any program.
Now, what did the while loop do? Well, while loops are like for loops, except they keep going unless a condition is false. While loops always ask the program, "Am I done yet?" until it is done. I hope you get while loops already, since I can't think of anything else to help you get it.
Well... There wasn't much to talk about in this article. Here, you learned about while loops. There still isn't much you know about loops, but I can challenge you to do this; try to make a runaway loop that uses input (it's easy, trust me), and one that doesn't use input (even easier).
Friday, April 5, 2013
For Loops
We've gone through the most vital elements of input, but let's learn another element of input that is optional: loops.
There are two kinds of loops: for loops and while loops. First, we will start off with for loops. For loops don't really have anything to do with input, but are used when something needs to be repeated a certain amount of times. Like the elements of input, this function only works in a program. Write this in a new window:
for loop in [1, 2, 3, 4, 5]:
print("hello")
Run the program. You should get an output like this:
hello
hello
hello
hello
hello
Hey, how did that happen? Well, "loop" in the program actually does whatever is in the block of code for each time it says in the square brackets. However, we can call "loop" whatever we want! Try changing that word to "chips" or "cow" or maybe "helicopter" and the program will still run the same. Also, there's a quicker way to use for loops in case you need one to repeat many times. This shortcut is called range().
In the square brackets of our first loop program, we started with 1, right? Well, another way that programmers have argued about is starting with 0. Most people do it that way, but you can choose which way you want to. Either way starts at 1. Oh, and remember: When telling it to go to, for example, 10, it will only do it 9 times. Remember, Python goes up to right under that number, and doesn't do the last one (this doesn't make a difference with starting with 1 or 0)! Anyway, let's try another program, this time, with range(). I will also use "i," "j," and "k" for the loop names. That's what most programmers use for loop names. Try this program:
for i in range(1, 11):
print(i, "times 8 =", i * 8)
for j in range(1, 10, 2):
print(j)
for k in range(5, 26, 5):
print(k)
for loop in range(10, 1, -1):
print(loop)
When you run the program, you should get an output like this:
1 times 8 = 8
2 times 8 = 16
3 times 8 = 24
4 times 8 = 32
5 times 8 = 40
6 times 8 = 48
7 times 8 = 56
8 times 8 = 64
9 times 8 = 72
10 times 8 = 80
1
3
5
7
9
5
10
15
20
25
10
9
8
7
6
5
4
3
2
The range seems confusing, but I will explain how the range worked each time. Let's start with the first range, which created this segment:
1 times 8 = 8
2 times 8 = 16
3 times 8 = 24
4 times 8 = 32
5 times 8 = 40
6 times 8 = 48
7 times 8 = 56
8 times 8 = 64
9 times 8 = 72
10 times 8 = 80
So, i, in this case, Went from 1 to 10, and printed each time: i, "times 8 =", i * 8. That means it takes i and the iteration it's in (each time through a loop is an iteration), multiplies it by 8 (after the string). Now, for the second loop that created this part:
1
3
5
7
9
In this part, the range had 3 numbers in it! What was the first one for? Well, j went from 1 to 10, counting by 2. Putting 3 numbers in range() means you are skip counting by something. Here is another example of skip counting, but by a different number:
5
10
15
20
25
In that segment, k started at 5, then skip counted by 5 to 25. Now, here's another skip counting loop, but this time, it goes a different way:
10
9
8
7
6
5
4
3
2
You'll notice that in the range that created that segment, it said range(10, 1, -1). It means that it started at 10, then went to 1, by subtracting 1. In the range, -1 doesn't mean negative one, it means subtract one.
Now, let's try a loop with a range!
for letter in "Hi there":
print(letter)
Press Enter, Backspace so you aren't typing in the block of code, and press Enter again.
H
i
t
h
e
r
e
What happened? Instead of saying "Hi there," it said each character of it on a single line! Here's why: each character in the string counts as and iteration, and the program takes the string as what it is printing.
Well, those are the ways you can use loops. However, these were only for loops. We still haven't learned while loops, the type involving input. Make sure you have for loops down! Loops are used many times in programming.
Now, let's try a loop with a range!
for letter in "Hi there":
print(letter)
Press Enter, Backspace so you aren't typing in the block of code, and press Enter again.
H
i
t
h
e
r
e
What happened? Instead of saying "Hi there," it said each character of it on a single line! Here's why: each character in the string counts as and iteration, and the program takes the string as what it is printing.
Well, those are the ways you can use loops. However, these were only for loops. We still haven't learned while loops, the type involving input. Make sure you have for loops down! Loops are used many times in programming.
Thursday, April 4, 2013
If, Or, and And - Elements of Input
Now we know some functions necessary to the elements of input. Now, we will learn more functions that are even more vital to input: if, or, input(), and and.
We all know what the words "if," "or," and "and" mean, and so does Python. These functions are not terribly confusing, but you may get a few terms mixed up here and there. Now, let's talk about how to use input().
Input() lets Python know when it's the user's turn to interact with the program. But, there are also ways to let Python know what kind of things the user must type. Here are some functions that determine what kind of input the user must use: int() and str().
Int is short for integer, which means a whole number. Str is short for string, which is a sentence or statement Python takes literally (we went over strings in the first article). When used as functions for input, they are int() and str(). Also, for the heck of it, let me tell you another term used in Python: float. A float is a decimal number.
There is something that is always used after an if statement is used. Something called a block of code. Remember the second article, where we wrote that program? Do you remember the lines that had the if statement in them? You'll notice that the end of all those lines had a colon (:) at the end, and the line after had an indentation of four spaces. That is a block of code. It means that if a certain statement is true, it does whatever is in the block of code. If the statement is false, Python skips that part and goes to the next line. The other two functions, or and and, are used in the same lines as if. If or is used, it means if this statement is true or this one. If and is used, it means if the statement is true and this one. If both are used, it might mean something like if this statement is true and this one or this one and this one.
The only way to experiment with these functions and to figure out how they work is to make more programs! Do what you did to make the Multiplier program from article #2, and write this:
factor1=9
factor2=12
answer=factor1 * factor2
print("What is", factor1, "X", factor2, "?")
guess=int(input())
if guess == answer:
print("Correct!")
if guess != answer:
print("That is not correct. Better luck next time!")
Save it and run it. You should see your program say, "What is 9X12?" then you should be able to put in an answer, and if you get it right, the program should say, "Correct!" and if you get it wrong, it should say "That is not correct. Better luck next time!" The program had already figured out what 9 times 12 is, and when you typed a number, Python processed your input and checked both blocks of code to see if they were true or false. If the statement was true, the program did what was in the block. If the statement was false, the program completely skipped the block. However, in the second block of code, you can also use another function called elif, which means "else if." We only used the if statement in this program. Now, let's write a program that uses or.
print("Type in any number you want.")
num=int(input())
if num == 3 or num == 8 or num == 12:
print("That's the specific number I was looking for.")
You have to be very specific with the or function, and not speak like a normal person. If you type in the program, "if num == 3 or 8 or 12," Python won't know what == 3, 8, and 12. We still haven't used and yet, so let's write another program that involves that function.
factor1=12
factor2=12
factor3=5
factor4=15
answer1=factor1 * factor2
answer2=factor3 * factor4
print("What is", factor1, "X", factor2, "?")
guess1=int(input())
print("What is", factor3, "X", factor4, "?")
guess2=int(input())
if guess1 == answer1 and guess2 == answer2:
print("You got both correct!")
If you get 144 for the first answer and 75 for the second answer, you should see "You got both correct!" displayed in Python IDLE. If you missed one or both of them, you should see nothing displayed after both problems.
So, in this article, you learned about the three commands required for input(). With such knowledge learned, I will finally give you challenges: I challenge you to add more to the third program using the and function. Try to give you a message saying which one you got wrong.
We all know what the words "if," "or," and "and" mean, and so does Python. These functions are not terribly confusing, but you may get a few terms mixed up here and there. Now, let's talk about how to use input().
Input() lets Python know when it's the user's turn to interact with the program. But, there are also ways to let Python know what kind of things the user must type. Here are some functions that determine what kind of input the user must use: int() and str().
Int is short for integer, which means a whole number. Str is short for string, which is a sentence or statement Python takes literally (we went over strings in the first article). When used as functions for input, they are int() and str(). Also, for the heck of it, let me tell you another term used in Python: float. A float is a decimal number.
There is something that is always used after an if statement is used. Something called a block of code. Remember the second article, where we wrote that program? Do you remember the lines that had the if statement in them? You'll notice that the end of all those lines had a colon (:) at the end, and the line after had an indentation of four spaces. That is a block of code. It means that if a certain statement is true, it does whatever is in the block of code. If the statement is false, Python skips that part and goes to the next line. The other two functions, or and and, are used in the same lines as if. If or is used, it means if this statement is true or this one. If and is used, it means if the statement is true and this one. If both are used, it might mean something like if this statement is true and this one or this one and this one.
The only way to experiment with these functions and to figure out how they work is to make more programs! Do what you did to make the Multiplier program from article #2, and write this:
factor1=9
factor2=12
answer=factor1 * factor2
print("What is", factor1, "X", factor2, "?")
guess=int(input())
if guess == answer:
print("Correct!")
if guess != answer:
print("That is not correct. Better luck next time!")
Save it and run it. You should see your program say, "What is 9X12?" then you should be able to put in an answer, and if you get it right, the program should say, "Correct!" and if you get it wrong, it should say "That is not correct. Better luck next time!" The program had already figured out what 9 times 12 is, and when you typed a number, Python processed your input and checked both blocks of code to see if they were true or false. If the statement was true, the program did what was in the block. If the statement was false, the program completely skipped the block. However, in the second block of code, you can also use another function called elif, which means "else if." We only used the if statement in this program. Now, let's write a program that uses or.
print("Type in any number you want.")
num=int(input())
if num == 3 or num == 8 or num == 12:
print("That's the specific number I was looking for.")
You have to be very specific with the or function, and not speak like a normal person. If you type in the program, "if num == 3 or 8 or 12," Python won't know what == 3, 8, and 12. We still haven't used and yet, so let's write another program that involves that function.
factor1=12
factor2=12
factor3=5
factor4=15
answer1=factor1 * factor2
answer2=factor3 * factor4
print("What is", factor1, "X", factor2, "?")
guess1=int(input())
print("What is", factor3, "X", factor4, "?")
guess2=int(input())
if guess1 == answer1 and guess2 == answer2:
print("You got both correct!")
If you get 144 for the first answer and 75 for the second answer, you should see "You got both correct!" displayed in Python IDLE. If you missed one or both of them, you should see nothing displayed after both problems.
So, in this article, you learned about the three commands required for input(). With such knowledge learned, I will finally give you challenges: I challenge you to add more to the third program using the and function. Try to give you a message saying which one you got wrong.
Wednesday, April 3, 2013
Gaming Elements, Changing Values, and Simple Functions
There are 3 basic elements to make an interesting program: Input, processing, and output. These elements you will find in a video game, for example. Input is the buttons the user pushes on the controller, the game system processes what the user did, and then the output is the image displayed on the television screen.
We are not at that level of programming yet, so let's start simple. The input is what the user types, the program processes what the user typed, and the output is what your program says. We will use the elements when we learn the functions needed to use them. For now, let's move on to the next thing promised in the title: variables.
We already covered what variables can do, but there is a little more you need to know about them. Type this variable in Python IDLE:
ex3='Bob'
We already know that if we say print(ex3), we will get "Bob." But, we can give ex3 a different variable, like this:
ex3='Joe'
print(ex3)
Joe
So, it printed "Joe," not "Bob." When you create a variable, and then create another variable with the exact same name, the original is deleted. That can help if you want to change variables in programs. Also, you can even change the variable by adding a number to the previous one. Try this:
num=5
print(num)
5
num=num + 1
print(num)
6
See what it did there? Before the new variable is read by Python, the variable is still 5. When you take it and add one to it, that's how you do it. It's sort of hard to explain, but now you know.
Now, I will tell you about functions and terms used in programming, which some will be used in the next few articles. Here's a list of a few functions:
< means less than.
> means greater than (duh!).
== means exactly equal to.
!= means not equal to.
<= means less than or equal to.
>= means greater than or equal to.
I will talk about even more functions in the next few articles. I won't name them now because they involve functions you don't know yet. Even the functions I named have to do with what you don't know yet. I'm just preparing you for what you need to know.
We are not at that level of programming yet, so let's start simple. The input is what the user types, the program processes what the user typed, and the output is what your program says. We will use the elements when we learn the functions needed to use them. For now, let's move on to the next thing promised in the title: variables.
We already covered what variables can do, but there is a little more you need to know about them. Type this variable in Python IDLE:
ex3='Bob'
We already know that if we say print(ex3), we will get "Bob." But, we can give ex3 a different variable, like this:
ex3='Joe'
print(ex3)
Joe
So, it printed "Joe," not "Bob." When you create a variable, and then create another variable with the exact same name, the original is deleted. That can help if you want to change variables in programs. Also, you can even change the variable by adding a number to the previous one. Try this:
num=5
print(num)
5
num=num + 1
print(num)
6
See what it did there? Before the new variable is read by Python, the variable is still 5. When you take it and add one to it, that's how you do it. It's sort of hard to explain, but now you know.
Now, I will tell you about functions and terms used in programming, which some will be used in the next few articles. Here's a list of a few functions:
< means less than.
> means greater than (duh!).
== means exactly equal to.
!= means not equal to.
<= means less than or equal to.
>= means greater than or equal to.
I will talk about even more functions in the next few articles. I won't name them now because they involve functions you don't know yet. Even the functions I named have to do with what you don't know yet. I'm just preparing you for what you need to know.
Tuesday, April 2, 2013
Deleting Items From a List
As I said in the last article, you haven't learned everything about lists yet. You know how to add to one, but not to take away from one. Now is time for you to learn remove(), del, and pop().
Now, we will finally remove that inner list. Type this in Python to get rid of it at last:
family.remove(['Jason', 'Jake'])
print(family)
['Jack', 'Tim', 'Mike', 'Nancy', 'Dad', 'Willy', 'Betty', 'Grandpa', 'Grandma', 'Alison']
We finally got the list gone. But, removing an item like that does not give a good example for someone who doesn't know this function yet. Let's take away another item in the list.
family.remove('Jack')
print(family)
['Tim', 'Mike', 'Nancy', 'Dad', 'Willy', 'Betty', 'Grandpa', 'Grandma', 'Alison']
Sorry, I forgot Louis! You might as well remove him. Anyway, remove takes away single items in the list. But, there's a slightly faster way to get rid of an item. This is the del function. Try this:
del family[5]
print(family)
['Tim', 'Mike', 'Nancy', 'Dad', 'Willy', 'Grandpa', 'Grandma', 'Alison']
Del took away the 5th index in the list, which was "Betty." Instead of saying the entire string, you can just use the index it is. But, what about pop()?
Pop() takes the last item off of the list and gives it back to you, so you can assign it to a different variable, like so:
ex1=family.pop()
print(ex1)
Alison
"Alison" was at the end of the list, and pop() took that item off and put it in ex1. But, what about the list?
print(family)
['Tim', 'Mike', 'Nancy', 'Dad', 'Willy', 'Grandpa', 'Grandma']
Pop() didn't give us a copy of the last index, it actually tore it off of family and gave it to ex1. But, what if we want to pop an item in the middle of the list? This is how we do that:
ex2=family.pop(4)
print(ex2)
Willy
That's the reason the parenthesis (()) are there. If you don't put a number in them, Python knows just to take the last item off and give it to the assigned variable. However, the number in the parenthesis must be an index in the list, or you will get an error. You can try it yourself if you don't believe me.
So, you learned about how to delete items in a list. Things will get even more complicated later on during lists, so I will go back to the easier functions so you don't get confused.
Adding to a List
There is much more about lists, and since you know a little about them, I think you should know everything, so your questions about them will be answered sooner. First, let's learn about slicing shorthand. These are not all that necessary, but programmers are lazy, and you need to know the shortcuts you use, in case if you ever look at their code. First, there is a shortcut to get everything from the beginning of the list to the part you want it to go up to. Here's how:
print(family[:2])
['Jack', 'Tim']
It doesn't seem to be much of a shortcut, but I guess it's some of one. Now, another pointless shortcut:
print(family[2:])
['Mom', 'Dad', 'Willy', 'Betty']
So, we started at item #2 in the list, and went to the end. There's a third shortcut that seems to be the fastest out of all of these.
print(family[:])
['Jack', 'Tim', 'Mom', 'Dad', 'Willy', 'Betty']
This time, there are no numbers. That tells Python to give you all items of the list. It only makes a copy of the list, so you can change it without affecting the original. Now, we will get into some more important matters of lists.
You can change items in the list, like so:
family[2]='Nancy'
print(family)
['Jack', 'Tim', 'Nancy', 'Dad', 'Willy', 'Betty']
We changed "Mom" to "Nancy." If you need to make any rearrangements, this will come in handy. You can also add things to a list using append(), extend(), or insert().
First, we will start with append(). Here is how it works:
family.append('Louis')
print(family)
['Jack', 'Tim', 'Nancy', 'Dad', 'Willy', 'Betty', 'Louis']
Remember, append() adds only one item to the list. To prove my claim, try this:
family.append(['Jason', 'Jake'])
print(family)
['Jack', 'Tim', 'Nancy', 'Dad', 'Willy', 'Betty', ['Jason', 'Jake']]
Don't take away the list in the list. We will take it away later. Now, let us move on to extend().
Although append() adds one item, extend() adds as many items as you want. Try this:
family.extend(['Grandpa', 'Grandma', 'Alison'])
print(family)
['Jack', 'Tim', 'Nancy', 'Dad', 'Willy', 'Betty', ['Jason', 'Jake'], 'Grandpa', 'Grandma', 'Alison']
That is basically all we need to know about extend(), so let's move on to insert().
Inserting an item into a list isn't adding an item to the end, but adding an item anywhere you want. Try typing this:
family.insert(2, 'Mike')
print(family)
['Jack', 'Tim', 'Mike', 'Nancy', 'Dad', 'Willy', 'Betty', ['Jason', 'Jake'], 'Grandpa', 'Grandma', 'Alison']
So, "Mike" became the second item in the list, and "Nancy," the former second item, was pushed up by one in the list.
Now you know more about lists! For now, you only know how to add to a list. There is more you can do with them. Make sure you have these functions in your head, because you will need to remember everything you can about Python and lists.
print(family[:2])
['Jack', 'Tim']
It doesn't seem to be much of a shortcut, but I guess it's some of one. Now, another pointless shortcut:
print(family[2:])
['Mom', 'Dad', 'Willy', 'Betty']
So, we started at item #2 in the list, and went to the end. There's a third shortcut that seems to be the fastest out of all of these.
print(family[:])
['Jack', 'Tim', 'Mom', 'Dad', 'Willy', 'Betty']
This time, there are no numbers. That tells Python to give you all items of the list. It only makes a copy of the list, so you can change it without affecting the original. Now, we will get into some more important matters of lists.
You can change items in the list, like so:
family[2]='Nancy'
print(family)
['Jack', 'Tim', 'Nancy', 'Dad', 'Willy', 'Betty']
We changed "Mom" to "Nancy." If you need to make any rearrangements, this will come in handy. You can also add things to a list using append(), extend(), or insert().
First, we will start with append(). Here is how it works:
family.append('Louis')
print(family)
['Jack', 'Tim', 'Nancy', 'Dad', 'Willy', 'Betty', 'Louis']
Remember, append() adds only one item to the list. To prove my claim, try this:
family.append(['Jason', 'Jake'])
print(family)
['Jack', 'Tim', 'Nancy', 'Dad', 'Willy', 'Betty', ['Jason', 'Jake']]
Don't take away the list in the list. We will take it away later. Now, let us move on to extend().
Although append() adds one item, extend() adds as many items as you want. Try this:
family.extend(['Grandpa', 'Grandma', 'Alison'])
print(family)
['Jack', 'Tim', 'Nancy', 'Dad', 'Willy', 'Betty', ['Jason', 'Jake'], 'Grandpa', 'Grandma', 'Alison']
That is basically all we need to know about extend(), so let's move on to insert().
Inserting an item into a list isn't adding an item to the end, but adding an item anywhere you want. Try typing this:
family.insert(2, 'Mike')
print(family)
['Jack', 'Tim', 'Mike', 'Nancy', 'Dad', 'Willy', 'Betty', ['Jason', 'Jake'], 'Grandpa', 'Grandma', 'Alison']
So, "Mike" became the second item in the list, and "Nancy," the former second item, was pushed up by one in the list.
Now you know more about lists! For now, you only know how to add to a list. There is more you can do with them. Make sure you have these functions in your head, because you will need to remember everything you can about Python and lists.
Subscribe to:
Posts (Atom)