a way to keep track of # of clicks
Is there a way to keep track of the number of times someone clicks on a menu item in a prorgam? What I want to do is make the rectangle disappear after they click on it at the main menu 3 times so visually show them they can't do it any longer. Since I appended the button to a main menu list, I would think undrawing it would have something like pop.mainMenuList[8] in it after they click on it three times. (not in succession, after it takes them to the questions screen and then back to the main menu) Any suggestions? thx -- http://mail.python.org/mailman/listinfo/python-list
Re: a way to keep track of # of clicks
Is there a way to keep track of the number of times someone clicks on a menu item in a prorgam? What I want to do is make the rectangle disappear after they click on it at the main menu 3 times so visually show them they can't do it any longer. > > Since I appended the button to a main menu list, I would think > undrawing it would have something like pop.mainMenuList[8] in it after > they click on it three times. (not in succession, after it takes them > to the questions screen and then back to the main menu) > > Any suggestions? > > thx > -- http://mail.python.org/mailman/listinfo/python-list
Highscores list
I'm writing a game that uses two functions to check and see if a file called highScoresList.txt exists in the main dir of the game program. If it doesn, it creates one. That part is working fine. The problem is arising when it goes to read in the high scores from the file when I play again. > > This is the error msg python is giving me > > Traceback (most recent call last): > File "", line 1, in > main() > File "I:\PYTHON\PROJECT #3\PROJECT3.PYW", line 330, in main > if(hasHighScore(wins) == True): > File "I:\PYTHON\PROJECT #3\PROJECT3.PYW", line 175, in hasHighScore > scores[i],names[i] = string.split(line,"\t") > ValueError: need more than 1 value to unpack > > Here's the relavant code: > > def hasHighScore(score): >#opens highScoresList.txt >infile = open("highScoresList.txt",'r') >scores = [0,0,0] >names = ["","",""] > >#reads in scores from highScoresList.txt >i=0 >for line in infile.readlines(): >scores[i],names[i] = string.split(line,"\t") >names[i]=string.rstrip(names[i]) >i += 1 >infile.close() > #compares player's score with those in highScoresList.txt >i=0 >for i in range(0,len(scores)): >if(score > int(scores[i])): >return True >else: >return False > > > def setHighScores(score,name): >#opens highScoresList.txt >infile = open("highScoresList.txt",'r') >scores = [0,0,0] >names = ["","",""] > >#reads in scores from highScoresList.txt >i=0 >for line in infile.readlines(): >scores[i],names[i] = string.split(line,"\t") >scores[i]=int(scores[i]) >names[i]=string.rstrip(names[i]) >i += 1 >infile.close() > #shuffles thru the highScoresList.txt and inserts player's score > if higher then those in file >i=len(scores) >while(score > scores[i-1] and i>0): >i -= 1 > >scores.insert(i,score) >names.insert(i,name) >scores.pop(len(scores)-1) >names.pop(len(names)-1) > #writes new highScoresList.txt >outfile = open("highScoresList.txt","w") > >outfile.write (" High Score Name \n") >outfile.write ("-\n") > >i=0 >for i in range(0,len(scores)): >outfile.write("\t" + str(scores[i]) + "\t\t\t" + names[i] + "\n") >outfile.close() > > And here's the call to the functions at the end of my game, included > in the error msg. > >#adds player's score to high score list if high enough >if(hasHighScore(wins) == True): >setHighScores(wins,getName(wins)) > > And this is what the text file looks like when it happens. > > High Score Name 15 SHAWN 0 0 > The answer is probably simple, I've just been working on this program > so long that my brain has turned to mush. Any help would be much > appreciated...thanks. > > -- http://mail.python.org/mailman/listinfo/python-list
highscores list
I'm writing a game that uses two functions to check and see if a file called highScoresList.txt exists in the main dir of the game program. If it doesn, it creates one. That part is working fine. The problem is arising when it goes to read in the high scores from the file when I play again. This is the error msg python is giving me Traceback (most recent call last): File "", line 1, in main() File "I:\PYTHON\PROJECT #3\PROJECT3.PYW", line 330, in main if(hasHighScore(wins) == True): File "I:\PYTHON\PROJECT #3\PROJECT3.PYW", line 175, in hasHighScore scores[i],names[i] = string.split(line,"\t") ValueError: need more than 1 value to unpack Here's the relavant code: def hasHighScore(score): #opens highScoresList.txt infile = open("highScoresList.txt",'r') scores = [0,0,0] names = ["","",""] #reads in scores from highScoresList.txt i=0 for line in infile.readlines(): scores[i],names[i] = string.split(line,"\t") names[i]=string.rstrip(names[i]) i += 1 infile.close() #compares player's score with those in highScoresList.txt i=0 for i in range(0,len(scores)): if(score > int(scores[i])): return True else: return False def setHighScores(score,name): #opens highScoresList.txt infile = open("highScoresList.txt",'r') scores = [0,0,0] names = ["","",""] #reads in scores from highScoresList.txt i=0 for line in infile.readlines(): scores[i],names[i] = string.split(line,"\t") scores[i]=int(scores[i]) names[i]=string.rstrip(names[i]) i += 1 infile.close() #shuffles thru the highScoresList.txt and inserts player's score if higher then those in file i=len(scores) while(score > scores[i-1] and i>0): i -= 1 scores.insert(i,score) names.insert(i,name) scores.pop(len(scores)-1) names.pop(len(names)-1) #writes new highScoresList.txt outfile = open("highScoresList.txt","w") outfile.write (" High Score Name \n") outfile.write ("-\n") i=0 for i in range(0,len(scores)): outfile.write("\t" + str(scores[i]) + "\t\t\t" + names[i] + "\n") outfile.close() And here's the call to the functions at the end of my game, included in the error msg. #adds player's score to high score list if high enough if(hasHighScore(wins) == True): setHighScores(wins,getName(wins)) And this is what the text file looks like when it happens. High Score Name - 15 SHAWN 0 0 The answer is probably simple, I've just been working on this program so long that my brain has turned to mush. Any help would be much appreciated...thanks. -- http://mail.python.org/mailman/listinfo/python-list
RE project - trivia game
Sorry, 4got to send it in html for the bold parts. thx def drawMainMenu(win): #define and draw the buttons mainMenuList = [] mainMenuList.append (CreateRect(4,6,7,8,"grey",win)) mainMenuList.append (CreateRect(3.5,6.5,5,6,"grey",win)) mainMenuList.append (CreateRect(3.5,6.5,3,4,"grey",win)) mainMenuList.append (CreateRect(3.1,7,1,2,"grey",win)) mainMenuList.append (CreateRect(8,10,0,1,"grey",win)) #define and draw the main menu mainMenuList.append (CreateText(5,9.5,"MAIN MENU","times roman", 30, "normal", "red",win)) mainMenuList.append (CreateText(2,8.5,"Please pick a subject from below: ","times roman", 14, "normal", "purple",win)) mainMenuList.append (CreateText(5,7.5,"MATH","times roman", 28, "italic", "blue",win)) mainMenuList.append (CreateText(5,5.5,"SCIENCE","times roman", 28, "italic", "yellow",win)) mainMenuList.append (CreateText(5,3.5,"HISTORY","times roman", 28, "italic", "pink",win)) mainMenuList.append (CreateText(5,1.5,"GEOGRAPHY","times roman", 28, "italic", "green",win)) mainMenuList.append (CreateText(9,.5,"Quit","times roman", 20, "italic", "black",win)) return(mainMenuList) def UndrawMenu (menulist): for i in range(len(menulist)): menulist[i].undraw() def CreateText(x,y,myString,myFace,mySize, myStyle, myColor,win): myText = Text(Point(x,y), myString) myText.setFace(myFace) myText.setSize(mySize) myText.setStyle(myStyle) myText.setTextColor(myColor) myText.draw(win) return myText def CreateRect(x1,x2,y1,y2,myFill,win): myRect = Rectangle(Point(x1,y1,), Point(x2,y2)) myRect.setFill(myFill) myRect.draw(win) return myRect def isValidClick(x1,x2, y1, y2, p1, win): if p1.getX()>=x1 and p1.getY()>=y1 and p1.getX()<=x2 and p1.getY()<=y2: return True else: return False def drawQuestion (subject, question, answers, win): menuList = [] #define and draw the entry boxes entchoice = Entry(Point(6.4,6.5), 1) entchoice.setText("A") entchoice.setTextColor ("blue") entchoice.draw(win) menuList.append(entchoice) menuList.append(CreateText(5,9.5,question,"times roman", 18, "normal", "red",win)) menuList.append(CreateText(2,8.5,"A. " + answers[0],"times roman", 16, "normal", "purple",win)) menuList.append(CreateText(7.5,8.5,"B. " + answers[1],"times roman", 16, "normal", "purple",win)) menuList.append(CreateText(2,7.5,"C. " + answers[2],"times roman", 16, "normal", "purple",win)) menuList.append(CreateText(7.5,7.5,"D. " + answers[3],"times roman", 16, "normal", "purple",win)) menuList.append(CreateText(4.7,6.5,"Please enter your choice:","times roman", 16, "normal", "purple",win)) #draw answer box and text answerButton = Rectangle(Point(7,5.5), Point(3,4)) answerButton.setFill("grey") answerButton.draw(win) answerButton = Text(Point(5,4.8),"Answer") answerButton.setTextColor("black") answerButton.setSize(22) answerButton.draw(win) menuList.append(answerButton) return(menuList) def main(): #Declare and initialize variables #make math question list mathlist = [] question = ["An equilateral triangle has how many sides?", "3", "4" , "1", "5"] mathlist.append(question) question = ["How many inches are in a foot?", "12", "6", "3", "9"] mathlist.append(question) question = ["One Kilogram equals how many grams?", "1000", "230", "450", "100"] mathlist.append(question) question = ["Which means nine hundred sixty three thousandths?", ".963", ".0963", ".0.0963", "9.63"] mathlist.append(question) question = ["A fathom is a unit of measurement for which of the following?", "depth", "space", "time", "distance"] mathlist.append(question) question = ["What is 111, plus 112, plus 113?", "336", "332", "331", "333"] mathlist.append(question) #show the rules of the game window win = GraphWin("RULES OF THE GAME",600,600) win.setBackground("orange") win.setCoords(0.0,0.0,10.0,10.0) txtrules1 = CreateText(5,9.5,"The rules of the game are as follows:","times roman", 16, "normal", "red",win) txtrules2 = CreateText(5,8.5,"The game will be made up of 10 questions, 2 from each grade 1-5.","times roman", 12, "normal", "black",win) txtrules3 = CreateText(5,7.5,"You will be able to pick 2 subjects you want to answer for each grade.","times roman", 12, "normal", "black",win) txtrules4 = CreateText(5,6.5,"The subjects you can pick from are Math, Science, History and Geography.","times roman", 12, "normal", "black",win) txtrules5 = CreateText(5,5.5,"No more then 3 questions can be answered from each subject.","times roman", 12, "normal", "black",win) txtrules6 = CreateText(5,2.5,"HAVE FUN AND GOOD LUCK!","times roman", 26, "normal", "yellow",win) #define window and set coords win =GraphWin("Are You Smarter Then a Fifth Grader???",800,800) win.setBackground("orange") win.setCoords(0.0,0.0,10.0,10.0) mainM
project - trivia game
For my final project, I'm trying to do a GUI based game similar to are you smarter then a 5th grader. I've been working on it and am stuck with some code someone helped me with to randomize the A,B,C,D letters that the correct answer is assigned too. The code that does this is highlighted in bold and the code that assigns it to a variable is also in bold so I can test it in the console window. Problem is, it's always stuck at letter A and doesn't always give the correct answer. The correct answer is always position 1 in my make math question list. Could someone please help? thanks BTW, to whoever asked me why I don't use functions b4, I'm using them now that I've learned how to... :P ;) from graphics import * from random import * def drawMainMenu(win): #define and draw the buttons mainMenuList = [] mainMenuList.append (CreateRect(4,6,7,8,"grey",win)) mainMenuList.append (CreateRect(3.5,6.5,5,6,"grey",win)) mainMenuList.append (CreateRect(3.5,6.5,3,4,"grey",win)) mainMenuList.append (CreateRect(3.1,7,1,2,"grey",win)) mainMenuList.append (CreateRect(8,10,0,1,"grey",win)) #define and draw the main menu mainMenuList.append (CreateText(5,9.5,"MAIN MENU","times roman", 30, "normal", "red",win)) mainMenuList.append (CreateText(2,8.5,"Please pick a subject from below: ","times roman", 14, "normal", "purple",win)) mainMenuList.append (CreateText(5,7.5,"MATH","times roman", 28, "italic", "blue",win)) mainMenuList.append (CreateText(5,5.5,"SCIENCE","times roman", 28, "italic", "yellow",win)) mainMenuList.append (CreateText(5,3.5,"HISTORY","times roman", 28, "italic", "pink",win)) mainMenuList.append (CreateText(5,1.5,"GEOGRAPHY","times roman", 28, "italic", "green",win)) mainMenuList.append (CreateText(9,.5,"Quit","times roman", 20, "italic", "black",win)) return(mainMenuList) def UndrawMenu (menulist): for i in range(len(menulist)): menulist[i].undraw() def CreateText(x,y,myString,myFace,mySize, myStyle, myColor,win): myText = Text(Point(x,y), myString) myText.setFace(myFace) myText.setSize(mySize) myText.setStyle(myStyle) myText.setTextColor(myColor) myText.draw(win) return myText def CreateRect(x1,x2,y1,y2,myFill,win): myRect = Rectangle(Point(x1,y1,), Point(x2,y2)) myRect.setFill(myFill) myRect.draw(win) return myRect def isValidClick(x1,x2, y1, y2, p1, win): if p1.getX()>=x1 and p1.getY()>=y1 and p1.getX()<=x2 and p1.getY()<=y2: return True else: return False def drawQuestion (subject, question, answers, win): menuList = [] #define and draw the entry boxes entchoice = Entry(Point(6.4,6.5), 1) entchoice.setText("A") entchoice.setTextColor ("blue") entchoice.draw(win) menuList.append(entchoice) menuList.append(CreateText(5,9.5,question,"times roman", 18, "normal", "red",win)) menuList.append(CreateText(2,8.5,"A. " + answers[0],"times roman", 16, "normal", "purple",win)) menuList.append(CreateText(7.5,8.5,"B. " + answers[1],"times roman", 16, "normal", "purple",win)) menuList.append(CreateText(2,7.5,"C. " + answers[2],"times roman", 16, "normal", "purple",win)) menuList.append(CreateText(7.5,7.5,"D. " + answers[3],"times roman", 16, "normal", "purple",win)) menuList.append(CreateText(4.7,6.5,"Please enter your choice:","times roman", 16, "normal", "purple",win)) #draw answer box and text answerButton = Rectangle(Point(7,5.5), Point(3,4)) answerButton.setFill("grey") answerButton.draw(win) answerButton = Text(Point(5,4.8),"Answer") answerButton.setTextColor("black") answerButton.setSize(22) answerButton.draw(win) menuList.append(answerButton) return(menuList) def main(): #Declare and initialize variables #make math question list mathlist = [] question = ["An equilateral triangle has how many sides?", "3", "4" , "1", "5"] mathlist.append(question) question = ["How many inches are in a foot?", "12", "6", "3", "9"] mathlist.append(question) question = ["One Kilogram equals how many grams?", "1000", "230", "450", "100"] mathlist.append(question) question = ["Which means nine hundred sixty three thousandths?", ".963", ".0963", ".0.0963", "9.63"] mathlist.append(question) question = ["A fathom is a unit of measurement for which of the following?", "depth", "space", "time", "distance"] mathlist.append(question) question = ["What is 111, plus 112, plus 113?", "336", "332", "331", "333"] mathlist.append(question) #show the rules of the game window win = GraphWin("RULES OF THE GAME",600,600) win.setBackground("orange") win.setCoords(0.0,0.0,10.0,10.0) txtrules1 = CreateText(5,9.5,"The rules of the game are as follows:","times roman", 16, "normal", "red",win) txtrules2 = CreateText(5,8.5,"The game will be made up of 10 questions, 2 from
get mouse
I'm just trying to test and see if the get mouse statements are working in my program. If they are, in the console window, it should go back to the prompt. It doesn't for all of them, just the last rectangle...sometimes. Am I setting them up correctly? here's the relevant code...thx The first two numbers are x1,x2 and the last two are y1, y2. rectMathButton = CreateRect(4,6,7,8,"grey") rectMathButton.draw(win) rectScienceButton = CreateRect(3.5,6.5,5,6,"grey") rectScienceButton.draw(win) rectHistoryButton = CreateRect(3.5,6.5,3,4,"grey") rectHistoryButton.draw(win) rectGeographyButton = CreateRect(3.1,7,1,2,"grey") rectGeographyButton.draw(win) #math p1 = win.getMouse() while p1.getX()> 6 or p1.getX()< 4 or p1.getY()> 8 or p1.getY()< 7: p1 = win.getMouse() #science p2 = win.getMouse() while p2.getX()> 6.5 or p2.getX()< 3.5 or p2.getY()> 6 or p2.getY()< 5: p2 = win.getMouse() #history p3 = win.getMouse() while p3.getX()> 6.5 or p3.getX()< 3.5 or p3.getY()> 4 or p3.getY()< 3: p3 = win.getMouse() #geography p4 = win.getMouse() while p4.getX()> 7 or p4.getX()< 3.1 or p4.getY()> 2 or p4.getY()< 1.1: p4 = win.getMouse() -- http://mail.python.org/mailman/listinfo/python-list
a few questions.
1. whats the best way to round a result to 4 decimal places? I tried round, but then read that it only works with exponents of 10. I'm trying to do it on this piece of code. time = (distance / 4900) 2. What direction would I go in if I'm getting 5 inputs from the user and want to make a bar table out of them where a * represents a 100 of the total number? For example, Store 1: * * Store 2: * Store 3: * * * ect, I already know I'm going to be expecting to use a for loop (0,4) since there are 5 inputs, but how to get from say, 200 to the output of * * I'm a little lost. thx -- http://mail.python.org/mailman/listinfo/python-list
Re: clear shell screen
Hmm...it works fine within the command line but then when I import os in python and then try os.system("cls"), i get that very fast opening/closing window and 0 inside the shell. Gabriel Genellina wrote: > En Mon, 29 Oct 2007 00:08:14 -0300, Shawn Minisall > <[EMAIL PROTECTED]> escribi�: > > >> Does anyone know how to clear the shell screen completely ? I tried >> import os and then os.system("clear") was said to have worked in Windows >> XP, but it's just bringing up another window, then it turns black and >> then it closes in within about a second moving the prompt at the >> os.system("clear") line . I've also tried os.system("cls") with the >> same results. >> > > Try running cls from a command prompt. If it works, it should work from > inside Python, using os.system("cls") > > > -- http://mail.python.org/mailman/listinfo/python-list
clear shell screen
Does anyone know how to clear the shell screen completely ? I tried import os and then os.system("clear") was said to have worked in Windows XP, but it's just bringing up another window, then it turns black and then it closes in within about a second moving the prompt at the os.system("clear") line . I've also tried os.system("cls") with the same results. thx -- http://mail.python.org/mailman/listinfo/python-list
Re: while within while
Thanks a lot for your suggestions. Unfortunately, a lot of the issues brought up were simply the way I was taught by my professor and the way she wants things done,having to use a numbered menu as opposed to entering r, p or s, being taught just to use one main function for the entire program, having to init all variables in the program b4 the actual program starts or else points off for each program, while statements surrounding every input statement for input validation purposes... Going beyond those things, would look like someone else wrote my program since we didn't talk about or ever cover them in class. I think we get to true statements in the next chapter next week. It turns out that my problem was with indentation, as soon as I fixed it, it's working perfectly now. thx Dennis Lee Bieber wrote: > On Sat, 27 Oct 2007 15:11:37 -0400, Shawn Minisall > <[EMAIL PROTECTED]> declaimed the following in comp.lang.python: > > Smells like homework -- so this week I won't be supplying a working > program (even one with no documentation -- requiring the student to > study the reference manuals to figure out what is being done) I'm going > to more focus on some stylistic features. > >> import random >> >> >> def main(): >> >> #define and initialize variables >> #choice as int >> choice = 0 >> > > Please note that one cannot define /type/ for a variable NAME. the > name is just a name that is attached to an object, and can be attached > to some other object later... It is the object on the RHS of the > assignment that has a type. > > The above binds the name "choice" to an object of type integer -- a > 0... The type is part of the 0, not of the name. > > >> #play again loop >> again = "no" >> > > > >> >> #Menu loop >> while choice != 4: >> #display menu >> print "Please choose from the following menu: " >> print "1. See the rules" >> print "2. Play against the computer" >> print "3. Play a two player game" >> print "4. Exit" >> >> #prompt user for their menu choice >> choice = input("Please enter your choice here: ") >> print >> >> > Rather than having to pre-initialize your loop conditional (and > notice that you can use ANY value EXCEPT 4 to initialize it) just for > the pleasure of using a while loop (I'm guessing being taught from the > "go to is forbidden" crowd, and not knowing of structured loop exits..) > that you go out of your way to avoid duplicating code (Pardon my > phrasing -- I'm not quite sure what my point was trying to be...) Let me > just mention that in Ada, what you are trying would be formulated as: > > loop > --display menu > -- prompt for choice > exit when choice = 4 > -- process other choices > end loop > > No need to preload the condition variable, since the first time it > is used is when it receives a value from the user. > > Python can produce the same formulation... (hint: the naked "loop" > in Ada is "while True" in Python). > > >> >> >> #if statements to determine which choice >> if choice == 1: >> print >> print "The rules of the game are as follows: " >> print >> print "Rock Covers Rock" >> print >> print "Rock Smashes Scissors" >> print >> print "Scissors Cuts Paper" >> print >> print >> >> > Python triple quoted strings can be split over multiple lines: > > print """ > The rules of the game are as follows: > > Paper Covers Rock > > Scissors Cut Paper > > Rock Breaks Scissors > > """ > even better -- This should be an initialized item at the start of the > program: > > rules = """ > The rules... etc. > """ > and then you just use one > > print rules > > > >> >> elif choice == 2: >> while again[0] == "y": >> > > I'd suggest same concern as prior while loop... don't preload > choices when the real determination can only be made after first > entering the loop. > >
while within while
K I've since fixed the UnboundLocalError: local variable 'ai' referenced before assignment error, I forgot to include decision = (1, 2, 3) inside " " for each number. Now when I run it, I get this.. >>> main() READY TO PLAY ROCK, PAPER, SCISSORS??? Please choose from the following menu: 1. See the rules 2. Play against the computer 3. Play a two player game 4. Exit Please enter your choice here: 2 = you choose scissors I choose YOU LOSE! Rounds Won: 0 Rounds Lost: 1 Rounds Tied: 0 Would you like to play again? y Please choose from the following menu: 1. See the rules 2. Play against the computer 3. Play a two player game 4. Exit Please enter your choice here: 2 Please choose a weapon from the following menu: 1. Rock 2. Paper 3. Scissors Please choose a weapon: 1 and then the weapon submenu repeats over and over. It's also like the program is ignoring if ai == "1": ai = "rock" if ai == "2": ai = "paper" if ai == "3": ai = "scissors" since it says I choose -- http://mail.python.org/mailman/listinfo/python-list
while within while
I've been having some problems with using a while statement for one menu within another while statement for the main menu, first time I've done it. It's with choice number two from the menu. When I run the program, I get a UnboundLocalError: local variable 'ai' referenced before assignment. I initialize ai as "", but then it just skips to the you choose scissors I choose and nothing shows up. As soon as I take away the while again[0] == "y": statement, the program is fine again which leads me to think I'm just placing it in the wrong place. I just want to ask the user if they would like to play again and loop them back to the weapons menu if they choose yes. If they choose no, loop them back to the main menu. I've placed the question again=raw_input("Would you like to play again? ") at the end the tasks for menu choice two. Ignore threeone step at a time. ;) thx import random def main(): #define and initialize variables #choice as int choice = 0 #weapon choice as int weaponchoice = 0 #number of wins win = 0 #number of loses lose = 0 #number of ties tie = 0 #number of rounds rounds = 0 #play again loop again = "no" #intro print "READY TO PLAY ROCK, PAPER, SCISSORS???" print #Menu loop while choice != 4: #display menu print "Please choose from the following menu: " print "1. See the rules" print "2. Play against the computer" print "3. Play a two player game" print "4. Exit" #prompt user for their menu choice choice = input("Please enter your choice here: ") print #if statements to determine which choice if choice == 1: print print "The rules of the game are as follows: " print print "Rock Covers Rock" print print "Rock Smashes Scissors" print print "Scissors Cuts Paper" print print elif choice == 2: while again[0] == "y": #display menu print "Please choose a weapon from the following menu: " print "1. Rock" print "2. Paper" print "3. Scissors" while weaponchoice != 1 and weaponchoice != 2 and weaponchoice != 3: weaponchoice = input("Please choose a weapon: ") if weaponchoice != 1 and weaponchoice != 2 and weaponchoice != 3: print print "Error. Please enter a number from 1-3." decision = (1, 2, 3) ai = str((random.choice(decision))) if ai == "1": ai = "rock" if ai == "2": ai = "paper" if ai == "3": ai = "scissors" if weaponchoice == 1: weaponchoice = "rock" elif weaponchoice == 2: weaponchoice = "paper" else: weaponchoice = "scissors" print "=" print "you choose " + weaponchoice print print "I choose " + ai print if weaponchoice == "rock" and ai == "scissors": win += 1 print "You WIN by SMASHING those SCISSORS!" elif weaponchoice == "paper" and ai == "rock": win += 1 print "You WIN by COVERING that ROCK!" elif weaponchoice == "scissors" and ai == "paper": win += 1 print "You WIN by CUTTING that PAPER!" elif weaponchoice == ai: tie += 1 print "YOU TIE!" else: lose += 1 print "YOU LOSE!" print "\nRounds Won: ", + win print "\nRounds Lost: ", + lose print "\nRounds Tied: ", + tie print print again=raw_input("Would you like to play again? ") elif choice == 3: print "test" elif choice == 4: print "Have a great day!" print print "Thanks for playing!" else: #invalid print "Invalid selection. Please enter a number from 1 - 4." print -- http://mail.python.org/mailman/listinfo/python-list
Re: for loop
I agree, but if I want to get a A on the program, thats how my professor wants the output. :) [EMAIL PROTECTED] wrote: > On Oct 22, 9:12?pm, Shawn Minisall <[EMAIL PROTECTED]> wrote: > >> Thanks, everyone! Using everyone's suggestions and points, the program >> is working great now. >> > > Actually, it's not. I assume not printing the population > was a copy error. > > But, by adding the "if (p>1):", you have now made > day 1 the initial population, so if you ask for > 8 days of multiplication, you actually only get 7. > > Although your code is working, it's not giving you > the correct answer. Most of the time in these kinds > of problems, days means elapsed days. That means for > 100 organisms @ 25% growth/day, there will be 125 > after 1 elapsed day. But that "if (p>1):" means you > show 100 at day 1, which is wrong. You have 100 after > 0 elapsed days (or day 0). > > > >> Here's the updated code. >> >> :) >> >> import math >> >> def main(): >> #Declare and initialize variables >> #starting number of organisms >> organisms = 0 >> #average daily population increase as % >> increase = 0.0 >> #number of days they will multiply >> days = 0 >> #population prediction >> population = 0.0 >> >> #Intro >> print "*" >> print "WELCOME TO THE POPULATION GROWTH CALCULATOR" >> print "*" >> >> print "This program will predict the size of a population of organisms." >> print >> print >> while organisms <=1: >> organisms=input("Please enter the starting number of organisms: ") >> if organisms <=1: >> print "Error. Population must be at least two." >> >> while increase <=0: >> increase=input("Please enter the average daily population >> increase as a percentage (20% = .20): ") >> if increase <=0: >> print "The percent of increase must be positive." >> >> while days <=0: >> days=input("Please enter the number of days that they will >> multiply: ") >> if days <=0: >> print "The number of days must be positive." >> >> print " DayPopulation" >> print "--" >> population = organisms >> >> for p in range (1,days+1): >> if( p > 1 ): >> population = population + ( population * increase ) >> >> print "\t",p, >> >> >> >> [EMAIL PROTECTED] wrote: >> >>> On Oct 22, 5:37 pm, "[EMAIL PROTECTED]" <[EMAIL PROTECTED]> wrote: >>> >>>> On Oct 22, 5:22 pm, Marc 'BlackJack' Rintsch <[EMAIL PROTECTED]> wrote: >>>> >>>>> On Mon, 22 Oct 2007 18:17:56 -0400, Shawn Minisall wrote: >>>>> >>>>>> #Intro >>>>>> print "*" >>>>>> print "WELCOME TO THE POPULATION GROWTH CALCULATOR" >>>>>> print "*" >>>>>> >>>>>> print "This program will predict the size of a population of >>>>>> organisms." >>>>>> print >>>>>> print >>>>>> organisms=input("Please enter the starting number of organisms: ") >>>>>> >>>>>> increase=input("Please enter the average daily population increase >>>>>> as a percentage (20% = .20): ") >>>>>> >>>>>> days=input("Please enter the number of days that they will multiply: >>>>>> ") >>>>>> >>>>>> print " DayPopulation" >>>>>> print "--" >>>>>> >>>>>> for p in range (days): >>>>>> >>>>>> population
greatest and least of these...
I just wrote a program to let the user input a series of whole numbers and tell them which is least and which is greatest based off of a menu. However, the menu isn't kicking in after they pick a number. I included a while statement for a loop just for the menu and compared it to my other programs that have a similar setup and are working, but I'm stumped. Here's the program... def main(): #define and initialize variables #choice as int choice = 0 #number as int number = 0 #intro print "WELCOME TO THE GREATEST AND LEAST NUMBER PROGRAM!" print #Menu loop while choice != 2: #display menu print "Please choose from the following menu: " print "1. Enter a number" print "2. Exit" print #prompt user for their menu choice choice = input("Enter your choice here: ") #if statements to determine which choice if choice == 1: nums = [] while number >=0: nums.append(number) number = input("Please enter a number.") elif choice == 2: print "Have a great day!" if len(nums) > 0: print "The smallest number that you entered was:",min(nums) print "The largest number that you entered was:",max(nums) else: #invalid print "Invalid selection. Enter either one or two." print Also, if they quit the program with choice #2 and entered numbers, it should display the greatest and least of them. If they just started and didn't enter anything and want to quit, I get an error message saying UnboundLocalError: local variable 'nums' referenced before assignment. Isn't the if statement supposed to keep python from going there since if they didn't enter any input, the length of the list should just be zero. -- http://mail.python.org/mailman/listinfo/python-list
Re: for loop
Thanks, everyone! Using everyone's suggestions and points, the program is working great now. Here's the updated code. :) import math def main(): #Declare and initialize variables #starting number of organisms organisms = 0 #average daily population increase as % increase = 0.0 #number of days they will multiply days = 0 #population prediction population = 0.0 #Intro print "*" print "WELCOME TO THE POPULATION GROWTH CALCULATOR" print "*" print "This program will predict the size of a population of organisms." print print while organisms <=1: organisms=input("Please enter the starting number of organisms: ") if organisms <=1: print "Error. Population must be at least two." while increase <=0: increase=input("Please enter the average daily population increase as a percentage (20% = .20): ") if increase <=0: print "The percent of increase must be positive." while days <=0: days=input("Please enter the number of days that they will multiply: ") if days <=0: print "The number of days must be positive." print " DayPopulation" print "--" population = organisms for p in range (1,days+1): if( p > 1 ): population = population + ( population * increase ) print "\t",p, [EMAIL PROTECTED] wrote: > On Oct 22, 5:37 pm, "[EMAIL PROTECTED]" <[EMAIL PROTECTED]> wrote: > >> On Oct 22, 5:22 pm, Marc 'BlackJack' Rintsch <[EMAIL PROTECTED]> wrote: >> >> >> >> >> >> >>> On Mon, 22 Oct 2007 18:17:56 -0400, Shawn Minisall wrote: >>> >>>> #Intro >>>> print "*" >>>> print "WELCOME TO THE POPULATION GROWTH CALCULATOR" >>>> print "*" >>>> >>>> print "This program will predict the size of a population of >>>> organisms." >>>> print >>>> print >>>> organisms=input("Please enter the starting number of organisms: ") >>>> >>>> increase=input("Please enter the average daily population increase >>>> as a percentage (20% = .20): ") >>>> >>>> days=input("Please enter the number of days that they will multiply: ") >>>> >>>> print " DayPopulation" >>>> print "--" >>>> >>>> for p in range (days): >>>> >>>> population = organisms * population * increase >>>> >>>> print days, >>>> >>>> print "\t\t\t\t",population >>>> >>>> I'm having problems with my for loop here to calculate estimated >>>> population output to a table. Instead of knowing how much I want to >>>> loop it, the loop index is going to be whatever number of days the user >>>> enters. When I run my program, it asks the 3 questions above but then >>>> just dead stops at a prompt which leads me to believe there's something >>>> wrong with my loop. >>>> >>> It should not run at all as it is indented inconsistently. If that >>> problem is corrected it will stop with a `NameError` because you try to >>> read `population` before anything was assigned to it. >>> >>> Ciao, >>> Marc 'BlackJack' Rintsch >>> >> Also, I would guess that you want to print p, not days >> > > Oh, and your calculation is incorrect. You don't multiply by > organisms in every loop iteration, organisms is the initial > value of population, so you can solve the "Name" error by doing > population = organisms before the for..loop. > > And since you're asking for an increase, you don't multiply by the > percent (as that would decrease the population), but instead by > 1+increase. > > Also, does day==0 represent the first day of increase or t
for loop
#Intro print "*" print "WELCOME TO THE POPULATION GROWTH CALCULATOR" print "*" print "This program will predict the size of a population of organisms." print print organisms=input("Please enter the starting number of organisms: ") increase=input("Please enter the average daily population increase as a percentage (20% = .20): ") days=input("Please enter the number of days that they will multiply: ") print " DayPopulation" print "--" for p in range (days): population = organisms * population * increase print days, print "\t\t\t\t",population I'm having problems with my for loop here to calculate estimated population output to a table. Instead of knowing how much I want to loop it, the loop index is going to be whatever number of days the user enters. When I run my program, it asks the 3 questions above but then just dead stops at a prompt which leads me to believe there's something wrong with my loop. I have the exact same setup in another program, but the loop index has a specific value. I tried (0,days), (1,days) ect. and I don't think for loops need accumulators, I've tried it with one anyways and it still stops. Any idea's? thx -- http://mail.python.org/mailman/listinfo/python-list
while statements
I just learned about while statements and get why you place them around inputs for validation, but I'm a little lost on exactly where to place it with what condition in this program where the number of fat grams exceeds the total number of calories so that it loops back and asks you the two questions again instead of just saying The calories or fat grams were incorrectly entered. Any idea's? thx while cal <=0: #Prompt for calories cal = input("Please enter the number of calories in your food: ") if cal <=0: print "Error. The number of calories must be positive." #Prompt for fat fat = input("Please enter the number of fat grams in your food: ") if fat <=0: print "Error. The number of fat grams must be positive." #Calculate calories from fat calfat = float(fat) * 9 #Calculate number of calories from fat caldel = calfat / cal #change calcent decimal to percentage calcent = caldel * 100 #evaluate input if calfat > cal: print "The calories or fat grams were incorrectly entered." elif calcent > 0 and calfat < cal: if caldel <= .3: print "Your food is low in fat." elif caldel >= .3: print "Your food is high in fat." #Display percentage of calories from fat print "The percentage of calories from fat in your food is %", calcent -- http://mail.python.org/mailman/listinfo/python-list
if then elif
I just learned about if, then elif statements and wrote this program. The problem is, it's displaying all of the possibilities even after you enter a 0, or if the fat grams are more then the total number of calories , that is supposed to stop the program instead of continuing on with the print statements that don't apply. Any idea's? thanks #Prompt for calories cal = input("Please enter the number of calories in your food: ") #Prompt for fat fat = input("Please enter the number of fat grams in your food: ") #Input validation if cal or fat <= 0: #Display message print "Error. The number of calories and/or fat grams must be positive" print else: #Calculate calories from fat calfat = float(fat) * 9 #Calculate number of calories from fat caldel = calfat / cal #change calcent decimal to percentage calcent = caldel * 100 if calfat > cal: print "The calories or fat grams were incorrectly entered." else: #evaluate input if caldel <= .3: print "Your food is low in fat." elif caldel >= .3: print "Your food is high in fat." #Display percentage of calories from fat print "The percentage of calories from fat in your food is %", calcent Here's an example of the output... Please enter the number of calories in your food: 50 Please enter the number of fat grams in your food: 30 Error. The number of calories and/or fat grams must be positive Your food is low in fat. The percentage of calories from fat in your food is % 0.0 It was supposed to print The calories or fat grams were incorrectly entered since the calories from fat was greater then the total number of calories. -- http://mail.python.org/mailman/listinfo/python-list
Re: ValueError: too many values to unpack,>>>
Fredrik Lundh wrote: > Shawn Minisall wrote: > > >> Sorry, it looks like it's on the fourth line with the 3 values on line >> 4...its reading line 3 fine >> >> Traceback (most recent call last): >> File "", line 1, in >> main() >> File "I:\COMPUTER PROGRAMMING CLASS\PROJECT #1\project1.py", line 33, >> in main >> deposit1, deposit2, deposit3 = string.split(line, "\t") >> ValueError: too many values to unpack >> > > instead of fumbling around in the dark, try inserting a print statement > before the offending line, so you can see what you're trying to unpack: > > print string.split(line, "\t") # see what it is > deposit1, deposit2, deposit3 = string.split(line, "\t") > > > I did and it printed everything up until the 3rd line with 3 numbers for deposits. I have since figured it out...the teacher put in an extra tab after the last value so python thought it was 4 values for three. I went back into the file and deleted the extra tab after the 3rd number and saved it...now it's working fine. I'm going to kill her... ;) -- http://mail.python.org/mailman/listinfo/python-list
Re: ValueError: too many values to unpack,>>>
Marc 'BlackJack' Rintsch wrote: > On Thu, 27 Sep 2007 12:36:58 -0400, Shawn Minisall wrote: > > >> With the multiple value lines, python says this "ValueError: too many >> values to unpack" >> >> I've googled it and it says that happens when you have too few or too >> many strings that don't match with the variables in number your trying >> to assign them too. Below are the lines in reading in: >> >> line 3 - 19.1829.1578.75212.10 >> line 4 - 10020410.29 >> >> And this is the code I'm using: >> >> #read withdrawls from file on line3 >> line = infile.readline() >> >> #split withdrawls up >> withdraw1, withdraw2, withdraw3, withdraw4 = string.split(line, "\t") >> >> #read deposits from file on line4 >> line = infile.readline() >> #split deposits up >> deposit1, deposit2, deposit3 = string.split(line, "\t") >> >> I have 4 strings to match line 3 and 3 to match the 3 on line 4...any >> thoughts? >> > > First thought is to find out which of the two lines triggers the > exception. This information is part of the full traceback. > > Ciao, > Marc 'BlackJack' Rintsch > Sorry, it looks like it's on the fourth line with the 3 values on line 4...its reading line 3 fine Traceback (most recent call last): File "", line 1, in main() File "I:\COMPUTER PROGRAMMING CLASS\PROJECT #1\project1.py", line 33, in main deposit1, deposit2, deposit3 = string.split(line, "\t") ValueError: too many values to unpack -- http://mail.python.org/mailman/listinfo/python-list
ValueError: too many values to unpack
I am trying to read a few lines of a file with multiple values, the rest are single and are reading in fine. With the multiple value lines, python says this "ValueError: too many values to unpack" I've googled it and it says that happens when you have too few or too many strings that don't match with the variables in number your trying to assign them too. Below are the lines in reading in: line 3 - 19.1829.1578.75212.10 line 4 - 10020410.29 And this is the code I'm using: #read withdrawls from file on line3 line = infile.readline() #split withdrawls up withdraw1, withdraw2, withdraw3, withdraw4 = string.split(line, "\t") #read deposits from file on line4 line = infile.readline() #split deposits up deposit1, deposit2, deposit3 = string.split(line, "\t") I have 4 strings to match line 3 and 3 to match the 3 on line 4...any thoughts? thx -- http://mail.python.org/mailman/listinfo/python-list
ValueError: too many values to unpack,>>>
I am trying to read a few lines of a file with multiple values, the rest are single and are reading in fine. With the multiple value lines, python says this "ValueError: too many values to unpack" I've googled it and it says that happens when you have too few or too many strings that don't match with the variables in number your trying to assign them too. Below are the lines in reading in: line 3 - 19.1829.1578.75212.10 line 4 - 10020410.29 And this is the code I'm using: #read withdrawls from file on line3 line = infile.readline() #split withdrawls up withdraw1, withdraw2, withdraw3, withdraw4 = string.split(line, "\t") #read deposits from file on line4 line = infile.readline() #split deposits up deposit1, deposit2, deposit3 = string.split(line, "\t") I have 4 strings to match line 3 and 3 to match the 3 on line 4...any thoughts? thx -- http://mail.python.org/mailman/listinfo/python-list
too many values with string.split
I'm trying to unpack a list of 5 floats from a list read from a file and python is telling me 5 variables are too many for the string.split statement. Anyone have any other idea's? NOTE: the only reason I convert it to a float instead of just leaving it as a string in the loop is because I have to have it printed out as a float besides the names and then the average displayed underneath thx #read in data line by line for line in infile: mylist = string.split(line) firstName[counter] = mylist[0] lastName[counter] = mylist[1] grades[counter] = float(mylist[2]) print firstName[counter], lastName[counter],":","\t\t",grades[counter] #increment counter counter = counter + 1 #calculates and prints average score grades = str(grades) num1, num2, num3, num4, num5 = string.split(grades,",") average = float(num1 + num2 + num3 + num4 + num5) / 5 print print "Average:" -- http://mail.python.org/mailman/listinfo/python-list
Re: acronym program
That was it! Thanks a lot! I was also trying to output the acronym in caps so I was entering string.upper (acronym) like whats in the book and kept getting a "'tuple' object is not callable" error message. Just for the heck of it I tried it acronym.upper() and it worked! I thought it could work both ways? Paul Rudin wrote: > Shawn Minisall <[EMAIL PROTECTED]> writes: > > >> I'm trying to write a program that gets the first letter of every word >> of a phrase and prints it on screen. I'm having problems with it. >> I'm thinking a for loop would be good since I don't know the exact >> number of words the user is going to enter, but after that I get >> confused. How do I tell python to just goto the beg of each word in >> the phrase and include it in the acronym? Am I on the right track? >> >>for a in string.split(phrase) >>acronym = phrase [0] >>acronym = acronym + 1 >> > > > How about: > > for a in phrase.split(): > print a[0] > > > > -- http://mail.python.org/mailman/listinfo/python-list
acronym program
I'm trying to write a program that gets the first letter of every word of a phrase and prints it on screen. I'm having problems with it. I'm thinking a for loop would be good since I don't know the exact number of words the user is going to enter, but after that I get confused. How do I tell python to just goto the beg of each word in the phrase and include it in the acronym? Am I on the right track? for a in string.split(phrase) acronym = phrase [0] acronym = acronym + 1 thx -- http://mail.python.org/mailman/listinfo/python-list
qa
I'm trying to get a space in between these two strings but it's ignoring the space in between when it prints. >>> string.capwords (string.join([s1 + " " + s2])) * 3 'Spam Ni!Spam Ni!Spam Ni!' >>> -- http://mail.python.org/mailman/listinfo/python-list
thanks everyone for your replies!
:) -- http://mail.python.org/mailman/listinfo/python-list
string questions
Hi everyone, I'm a beginning programming student in Python and have a few questions regarding strings. If s1 = "spam" If s2 = "ni!" 1. Would string.ljust(string.upper(s2),4) * 3 start it at the left margin and move it 12 spaces to the right because of the 4 *3? If so, why is it in the parathesis for the upper command and not the ljust? I already know that it would cap it to NI! 2. To get the output "Spam Ni! Spam Ni! Spam Ni!" I could do something like this string.join ([s1, s2]), But I'm a little lost how to get it repeated three times on one line. Would I just have to put the same command on the next two lines? 3. To change spam to spm, the string.replace seems to be the best function to use. However, when I use string.replace(s1, "a", " ") in python to replace a with an empty space, it doesn't work...I just get spam back when I print s1. Any ideas? Thanks. -Shawn -- http://mail.python.org/mailman/listinfo/python-list