Projects for Beginners 6-10 - uber1337 - 01-26-2010
Well here it is, 6-10. The original post containing all the projects can be found here and my tutorial for 1-5 can be found here
6-10:
First things first, 6. To do this we will prompt our user for raw input, and use os.path.exists to see whether or not it is correct. First things first, import the os module.
That was easy! next we have to use def, and ask for input.
Code: import os
def start():
x = raw_input('What is the path and name of your file?:')
As you can see, x will be equal to the users input. Now, if the path is correct we assure the user that it exists using os.path.exists.
Code: import os
def start():
x = raw_input('What is the path and name of your file?:')
if os.path.exists(x):
print 'This is a file'
Finally, we use an "if not" to see if it doesn't exist, then we reprompt. Lastly, we call our function. We end up with this:
Code: import os
def start():
x = raw_input('What is the path and name of your file?:')
if os.path.exists(x):
print 'This is a file'
if not os.path.exists(x):
print 'This is not a file'
start() #Reprompt, back to the top
start() #Call "start"
Now for 7, It is the same idea, just switched around so that it rejects correct paths. I don't think I need to do this one step by step.
Code: import os
def start():
x = raw_input('Type in a non-existing path?:') #ask for input, = to x
if os.path.exists(x):
print 'This is path already exists'
start() #reprompt, back to the top
if not os.path.exists(x):
print 'This path does not exist'
start() # call "start”
Now for 8, we need to read a file contents, sort it, and write it back onto the file. The sort function is only available to lists, so we need to make a list containing the words in the file. First, we prompt for the file name.
Code: x = raw_input('What is the name of your file?')
x will be equal to whatever the user inputs. next lets make our list
Code: x = raw_input('What is the name of your file?')
l = [] #empty list
Now we will open the file, read each of the files letters, put them into our list, and sort them, all in 3 easy lines.
Code: x = raw_input('What is the name of your file?')
l = []
for char in open(x , 'r').read( ): #opens file, reads characters
l.append(char) #adds chars to our list
l.sort() #sorts the list
Now we convert it into a string so that we can write it back out.
Code: x = raw_input('What is the name of your file?')
l = []
for char in open(x , 'r').read( ):
l.append(char)
l.sort()
s = ''.join(l) # s is equal to a sting containing the list
last but not least, we write it out to the file. Giving us this:
Code: x = raw_input('What is the name of your file?')
l = []
for char in open(x , 'r').read( ):
l.append(char)
l.sort()
s = ''.join(l)
open(x , 'w').write(s)
This one caused me some trouble, but I got it eventually. First we will ask the user for desired columns and rows, then we will use for loops to make the desired grid. First, we import Tkinter(the standard Python GUI) and ask for some input. Also, we will make an empty list(for later)
Code: from Tkinter import *
ro = int(raw_input('How many rows?:'))
col = int(raw_input('How many columns?:'))
rows = []
Now that we have our desired rows and columns, lets make the graph using nested for loops. This will make the desired column and row for each number in the range of col and ro, by updating the list each time it runs through. We end up with this:
Code: from Tkinter import *
ro = int(raw_input('How many rows?:'))
col = int(raw_input('How many columns?:'))
rows = []
for i in range(ro): # first for loop
cols = []
for j in range(col): #second for loop
e = Entry()
e.grid(row=i, column=j, sticky=NSEW)
cols.append(e) #updates col list
rows.append(cols) #updates rows list, goes back to top level loop until it reached desired number
mainloop() #calls Tkinters mainloop
Now for the hard one. I will be using Tkinter to make a GUI that resembles a game. This will use the basic idea of using a button to update text fields and change variables. It will also use the random module to give the user a sense of an actual game. First, we will import Tkinter, the popup box module, and the random module. Also we will create two integer variables, one representing the round the user is on, the other representing the users current amount of money.
Code: from Tkinter import *
from tkMessageBox import showinfo
import random
money = 0
round = 0
Now we will use classes to start coding the GUI. Our game will contain 3 buttons, each time you press them a random event will happen, you either win or lose. Each time you press a button the round will go up 1, and depending on whether you won or lost the money will go up 100 or down 100. Lets create our entry fields and our buttons first.
Code: class gooey(Frame):
def __init__(self, parent=None):
global money
global e
global r
global round
top = Tk()
top.title('Game v1.0') # Title
Frame.__init__(self, parent)
Label(text='Money').pack(side=BOTTOM) #label our entry field with the word Money
e = Entry(money) #create our entry field with the value of our variable money
e.pack(side=BOTTOM)
Label(text='Round').pack(side=BOTTOM) #label our other entry field with the word Round
r = Entry(round) #create an entry field with the value of the round variable
r.pack(side=BOTTOM)
button1 = Button(self, text='Press me', command=self.btn1) #first button, command is btn1
button1.pack()
button2 = Button(self, text='Press me', command=self.btn2)#second button, command is btn2
button2.pack(side=RIGHT)
button3 = Button(self, text='Press me', command=self.btn3)#third button, command is btn3
button3.pack(side=LEFT)
Pretty simple, now we need to define the commands btn1 btn2 and btn3. They will all essentially be the same.
Code: def btn1(self):
global money
global e
global r
global round
a = 'You win, Congrats!'
b = 'You lose, Sorry :('
c = [a , b]
d = random.choice(c) #randomly chooses whether the person will win or lose
showinfo(title='Result', message=d) #shows whether the person won or lost, message=d
if d==a: #if the person won
money += 100 #update our variable money
e.delete(0, END) #delete whatever is in the entry field “e”
e.insert(0, money) #insert with the current money
round += 1 #update our variable round
r.delete(0, END) #delete whatever is in the entry field “r”
r.insert(0, round) #insert the current round
self #do it again so it doesn't show the same result each time
if d==b: # if the person “lost”
money -=100 #same as money = money - 100
e.delete(0, END)
e.insert(0, money)
round +=1
r.delete(0, END)
r.insert(0, round)
self
Now we finish it all off by coding the same thing for each button, and adding a “if __name__ == '__main__':” trick. Adding this at the end of your code will basically tell you program what to do if it is run, not if it is imported. This way, you can import your game and use some of the functions with executing your game. This works because Python automatically designates a “__name__” attribute to each program, but it is only equal to “__main__” if it is executed. We end up with this:
Code: from Tkinter import *
from tkMessageBox import showinfo
import random
money = 0
round = 0
class gooey(Frame):
def __init__(self, parent=None):
global money
global e
global r
global round
top = Tk()
top.title('Game v1.0')
Frame.__init__(self, parent)
Label(text='Money').pack(side=BOTTOM)
e = Entry(money)
e.pack(side=BOTTOM)
Label(text='Round').pack(side=BOTTOM)
r = Entry(round)
r.pack(side=BOTTOM)
button1 = Button(self, text='Press me', command=self.btn1)
button1.pack()
button2 = Button(self, text='Press me', command=self.btn2)
button2.pack(side=RIGHT)
button3 = Button(self, text='Press me', command=self.btn3)
button3.pack(side=LEFT)
def btn1(self):
global money
global e
global r
global round
a = 'You win, Congrats!'
b = 'You lose, Sorry :('
c = [a , b]
d = random.choice(c)
showinfo(title='Result', message=d)
if d==a:
money += 100
e.delete(0, END)
e.insert(0, money)
round += 1
r.delete(0, END)
r.insert(0, round)
self
if d==b:
money -=100
e.delete(0, END)
e.insert(0, money)
round +=1
r.delete(0, END)
r.insert(0, round)
self
def btn2(self):
global money
global e
global r
global round
a = 'You win, Congrats!'
b = 'You lose, Sorry :('
c = [a , b]
d = random.choice(c)
showinfo(title='Result', message=d)
if d==a:
money += 100
e.delete(0, END)
e.insert(0, money)
round += 1
r.delete(0, END)
r.insert(0, round)
self
if d==b:
money -=100
e.delete(0, END)
e.insert(0, money)
round += 1
r.delete(0, END)
r.insert(0, round)
self
def btn3(self):
global money
global e
global r
global round
a = 'You win, Congrats!'
b = 'You lose, Sorry :('
c = [a , b]
d = random.choice(c)
showinfo(title='Result', message=d)
if d==a:
money += 100
e.delete(0, END)
e.insert(0, money)
round += 1
r.delete(0, END)
r.insert(0, round)
self
if d==b:
money -=100
e.delete(0, END)
e.insert(0, money)
round += 1
r.delete(0, END)
r.insert(0, round)
self
if __name__ == '__main__': #our trick
window = gooey()
window.pack()
window.mainloop()
RE: Projects for Beginners 6-10 - nevets04 - 01-28-2010
I'm glad to see see you got this done. This will help a lot of people.
By the way, if your wondering why I've been so inactive, I've been grounded because of my poor grades, but I hope soon to get back programming. You probably know more of python than me now Keep up the good work
RE: Projects for Beginners 6-10 - uber1337 - 01-28-2010
(01-28-2010, 07:29 PM)nevets04 Wrote: I'm glad to see see you got this done. This will help a lot of people.
By the way, if your wondering why I've been so inactive, I've been grounded because of my poor grades, but I hope soon to get back programming. You probably know more of python than me now Keep up the good work
Ya I was wondering what happened to you. At one point I thought you gave up on Python entirely and went to Java. I'm getting better at python because I bought a book that covers system tools, GUI, CGI, Iron Python, and Jython. Soon I will be able to write programs that people can actually use!
RE: Projects for Beginners 6-10 - nevets04 - 02-18-2010
(01-28-2010, 08:30 PM)uber1337 Wrote: Ya I was wondering what happened to you. At one point I thought you gave up on Python entirely and went to Java. I'm getting better at python because I bought a book that covers system tools, GUI, CGI, Iron Python, and Jython. Soon I will be able to write programs that people can actually use!
I was trying out java, but everything I did took an hour, and I would say to myself, I could have done that in python in 5 minutes.
|