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?
Wednesday, May 15, 2013
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.
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!
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.
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).
Subscribe to:
Posts (Atom)