[Tutor] sorting and writing to data file
Hello community, Newbie here. I have a data (.dat) file with integers (2,9,1,5,7,3,9) in it just as shown. My instructions are to sort the numbers and rewrite them back to the data file. *here is my code:** * lab3int=[2,9,1,5,7,3,9] lab3int.sort() print(lab3int) lab3int=open('lab3int.dat','w') lab3int.write() lab3int.close() *here is my error message:* [1, 2, 3, 5, 7, 9, 9] Traceback (most recent call last): File "lab3int.py", line 5, in lab3int.write() TypeError: function takes exactly 1 argument (0 given) I know that it is telling me that my error is in line #5. If I put anything in the () for lab3int.write function, then that appears in my data file. however, I am looking to just put the re-sorted integers back into the data file without having to manually type each integer manually. Is there something that i can put into the lab3int.write() to make that happen? Hope my problem is clear, Thanks people ATS ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
[Tutor] Embed python in a website
I recently created a gui form using tkinter, is it possible to integrate this form to my website page? How do i integrate? Adrian Sent from my iPad ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] binding a button to an entry
Hi all, Please can anyone tell me how i bind the activation of a button with input from an entry widget. i know i should be using classes etc. but i don't understand them fully yet.. problem here is that no matter what i enter in the entry window it displays as password incorrect. from Tkinter import * password="trial" def reveal():"""Display message based on password"""contents=sif contents=="trial":print "password correct"else:print "password wrong" #mainroot=Tk()root.title("Password entry box")root.geometry("300x100")app=Frame(root)app.grid() #labelslbl=Label(app, text="Enter your password: ")lbl.grid(row=1, column=0) #create entry widgetse = Entry(root)e.grid(row=1, column=1)s=e.get() #create a submit buttonb=Button(root, text="SUBMIT", command=reveal)b.grid(row=0, column=2) root.mainloop() thanks all,adrian ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] stuck on null values
Please can anyone tell me how to solve the problem i am having here, i am trying to loop if the value is left blank by the user but how can i then use the value and multiply it. e.g. while number_child=="" i want to multiply the input i get.??? def main():print """ Welcome to the Travel Kiosk""" adult=15child=5firstname=raw_input("Please enter your firstname: ") lastname=raw_input ("Please enter your lastname: ") number_child=raw_input("Enter the number of kids: ") number_adults=raw_input("Enter the number of adults: ")while number_child=="":number_child=raw_input("Enter the number of kids: ") price=child*number_childprint """___ Thank you, the Price will be: """,price print"""___""" main() Adrian Kelly 1 Bramble Close Baylough Athlone County Westmeath 0879495663 ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] FW: null inputs
thanks very much i get it now... > From: hugo.yo...@gmail.com > Date: Thu, 15 Mar 2012 16:03:12 +0100 > Subject: Re: [Tutor] FW: null inputs > To: eire1...@gmail.com > CC: kellyadr...@hotmail.com; tutor@python.org > > On Thu, Mar 15, 2012 at 3:56 PM, James Reynolds wrote: > > > > > > You can't prevent users from entering whatever they feel like it, but you > > can prevent your program from processing that input and force them to try > > again. > > > > The typical way this is done is through a while loop: > > > > age = '' > > > > while age != '' > > age=raw_input("what age are you? ") > > > > this will continue to loop until you give it something other than ''. > > > > Of course, you can build on this, you know, something like: > > > > checker = False > > > > while checker: > > age=raw_input("what age are you? ") > > try: > > age = int(age) > > checker = True > > except TypeError: > > print "you didn't enter an integer for an age!" > > print "try again!!! > > > > > > Small correction: the exception you're looking for in this case is a > ValueError (after all, the argument provided has the correct type, but > its value can not be converted to an integer). int will throw > TypeError, but only if you supply an argument that is not a string or > number. > > Hugo ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] FW: null inputs
Adrian Kelly 1 Bramble Close Baylough Athlone County Westmeath 0879495663 From: kellyadr...@hotmail.com To: tutor@python.org Subject: null inputs Date: Thu, 15 Mar 2012 14:19:16 + Hi guys, how do i prevent a user from leaving a blank when inputting? e.g. age=int(input("what age are you? ")).. i want to stop the user pressing enter if age==""? age=raw_input("what age are you? ") if age=="": age=int(age) print "please enter your age" else: print "your age is ",age * i have tried this but still no luck, if anyone can help i would apprecitate it Adrian Kelly 1 Bramble Close Baylough Athlone County Westmeath 0879495663 ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] null inputs
Hi guys, how do i prevent a user from leaving a blank when inputting? e.g. age=int(input("what age are you? ")).. i want to stop the user pressing enter if age==""? Adrian Kelly 1 Bramble Close Baylough Athlone County Westmeath 0879495663 ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] appending to a file on a new line
guys, its a text file i am writing to and when i write the first time its fine, i get 3 lines of input collected from a user and written to my text file, however if i run the program again the next 3 lines begin at the end of the previous users details. It works fine but starts from where the pointer left off. i dont know how to solve this. where do i put the '\n'? to be honest the .join i dont understand but otherwise it prints as a list e.g. ('name','age','etc') Adrian > Date: Thu, 19 Jan 2012 09:42:45 -0500 > Subject: Re: [Tutor] appending to a file on a new line > From: joel.goldst...@gmail.com > To: kellyadr...@hotmail.com > CC: tutor@python.org > > On Thu, Jan 19, 2012 at 9:32 AM, ADRIAN KELLY wrote: > > Hi everyone, > > is there an easy way to write to a file (that already exists with data > > contained) on a new line. I understand that the file pointer appends where > > it left off but how do i write to the next line or even skip a line if > > possible? > > > > User_info=open("C:\\Documents and > > Settings\\akelly\\Desktop\\details.txt",'a') > > User_info.write("\n".join(Details)) > > > > > > all the best, > > Adrian > > > > ___ > > Tutor maillist - Tutor@python.org > > To unsubscribe or change subscription options: > > http://mail.python.org/mailman/listinfo/tutor > > > What you wrote looks fine. When you open a file to append, it does > just that with the write method. > > You can learn more here > http://docs.python.org/tutorial/inputoutput.html#methods-of-file-objects > > When you run your code what happens? > > > -- > Joel Goldstick ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] appending to a file on a new line
Hi everyone, is there an easy way to write to a file (that already exists with data contained) on a new line. I understand that the file pointer appends where it left off but how do i write to the next line or even skip a line if possible? User_info=open("C:\\Documents and Settings\\akelly\\Desktop\\details.txt",'a') User_info.write("\n".join(Details)) all the best, Adrian___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] Defining a File path
Hi guys, I know that if i dont include any path information, python looks in the current directory for the file. My question is how do i specify a file path to open a file saved on my desktop for example. Thanks all Adrian Sent from my iPad ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] reset password program
thanks dave, just tried writing to file for the first time def main(): outfile.write('Hello this is a test') outfile.close() main() error, globalname outfile is not defined, do i need to import function to get this working? > Date: Fri, 16 Dec 2011 17:13:04 -0500 > From: d...@davea.name > To: kellyadr...@hotmail.com > CC: tutor@python.org > Subject: Re: [Tutor] reset password program > > On 12/16/2011 05:02 PM, ADRIAN KELLY wrote: > > Hi guys, > > i created a program that allows users to login using a password that i set > > at the top of the program. > > Among other things users are given the option to change their password. My > > questions is; > > > > Is it possible for me to make this new password stick, in other words when > > they shut down and > > log in again i am back to the original password.the new password only > > works while the programming > > is running. I know why this is happening, what i don't know is what to do > > about it. > > > > I am new to python and programming so if you have any ideas... > > > > please keep them simple. > > > > thanks all, > > adrian > > > Nothing in Python objects is persistent. If you want something to > survive till the next run, you have to write it to something external, > such as a file. > > If this is a serious program, with important passwords, you'll want to > encrypt the file. If it's just casual, encode the file in some obscure > way. But if it's a class assignment, then save it in a text file, in a > directory you'll be able to find next time. > > That last point is important. The program directory may be read-only to > that user. So you might not be able to store it there. One approach is > to save it in the user's home directory, so for me, it might be > /home/davea Convention is to start it with a leading period, so that > the ls command won't show it by default. Another question is whether > you want a different password per user, and if you might have more than > one user logged into your machine at the same time. > > Hope this helped, > > > > > > > > -- > > DaveA > ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] reset password program
Hi guys, i created a program that allows users to login using a password that i set at the top of the program. Among other things users are given the option to change their password. My questions is; Is it possible for me to make this new password stick, in other words when they shut down and log in again i am back to the original password.the new password only works while the programming is running. I know why this is happening, what i don't know is what to do about it. I am new to python and programming so if you have any ideas... please keep them simple. thanks all, adrian___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] list, tuple or dictionary
Sound Wayne, thank you From: waynejwer...@gmail.com Date: Tue, 29 Nov 2011 15:11:46 -0600 Subject: Re: [Tutor] list, tuple or dictionary To: kellyadr...@hotmail.com CC: tutor@python.org On Tue, Nov 29, 2011 at 3:04 PM, ADRIAN KELLY wrote: thanks guy, i was thinking of using a dictionary:- Stock_list = {"White Bread": 1.24,"Biscuits": 1.77,"Banana" : 0.23,"Tea Bags" : 2.37, "Eggs" : 1.23,"Beans" : 0.57} how would i go about adding, for example tea and eggs to get a subtotal? Why, you would add tea and eggs, of course! print("Subtotal: ", Stock_list["Tea Bags"] + Stock_list["Eggs"]) HTH, Wayne ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] list, tuple or dictionary
thanks guy, i was thinking of using a dictionary:- Stock_list = {"White Bread": 1.24,"Biscuits": 1.77,"Banana" : 0.23,"Tea Bags" : 2.37,"Eggs" : 1.23,"Beans" : 0.57} how would i go about adding, for example tea and eggs to get a subtotal? Adrian Kelly 1 Bramble Close Baylough Athlone County Westmeath 0879495663 From: waynejwer...@gmail.com Date: Tue, 29 Nov 2011 14:49:00 -0600 Subject: Re: [Tutor] list, tuple or dictionary To: kellyadr...@hotmail.com CC: tutor@python.org On Tue, Nov 29, 2011 at 2:31 PM, ADRIAN KELLY wrote: i am trying to create a program that will allow users to enter items and their prices; should i be looking at a list, tuple or what? The entering part isn't as important as how you want to display the data. For instance, here's a program that allows the user to input an unlimited amount of data (using Python 3.x): while input("Enter q to quit, or an item: ").lower() not in ('q', 'quit', 'goodbye'): input("Enter the price: ") Of course it doesn't store the data, so it's pretty useless. But it does allow the user to input whatever they want. If you wanted to simply create a collection of items you could do it as a list with alternating values: inventory = ['Crunchy Frog', 4.13, 'Anthrax Ripple', 12.999, 'Spring Surprise', 0.00] for x in range(0, len(inventory)-1, 2): print(inventory[x], inventory[x+1]) Or as a list of tuples: inventory = [('Norwegian Blue', 500.00), ('Slug', 500.00), ('Cage', 50.00)] for item in inventory:print(item[0], item[1]) Or a dictionary: inventory = {'Spam':5.00, 'Spam on eggs':10.00, 'Spam on Spam':7.50}for item, price in inventory.items():print(item, price) Or if you wanted to get ridiculous, you could go with a list of classes: class Item:def __init__(self, desc='', price=0.00):self.desc = desc self.price = pricedef __repr__(self):return str(self) def __str__(self):return "{0} - {1}".format(self.desc, self.price) inventory = [Item('Lumberjack', 5.5), Item('Tree', 50), Item('Flapjack', 0.5)]for item in inventory:print(item) It just depends on how complex you want to get! HTH,Wayne ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] list, tuple or dictionary
i am trying to create a program that will allow users to enter items and their prices; should i be looking at a list, tuple or what? many thanksadrian ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] FW: How do i show discount?(sorted)
From: kellyadr...@hotmail.com To: kellyadr...@hotmail.com Subject: RE: How do i show discount? Date: Sat, 19 Nov 2011 23:34:27 + sorted it guys, used a third function Adrian From: kellyadr...@hotmail.com To: tutor@python.org Subject: How do i show discount? Date: Sat, 19 Nov 2011 22:41:37 + def shop(total_spend):min_spend=25discount_amount=150discount=0.05 if total_spend >= min_spend and total_spend > discount_amount: checkout=total_spend-(total_spend*discount) discount=total_spend*discountelse:checkout = total_spend discount = 0return checkout def main():spend = input('Enter the amount you spent: ')while spend<25: print "Error, min spend is €25 in this shop!"spend = input('Enter the amount you spent: ')else:total = shop(spend) print 'Your bill comes to',total,"\n","your discount was",discount main () #program works but how would i show the discount in main? I saved as text file in notepad! Many thanks ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] How do i show discount?
def shop(total_spend):min_spend=25discount_amount=150discount=0.05 if total_spend >= min_spend and total_spend > discount_amount: checkout=total_spend-(total_spend*discount) discount=total_spend*discountelse:checkout = total_spend discount = 0return checkout def main():spend = input('Enter the amount you spent: ')while spend<25: print "Error, min spend is €25 in this shop!"spend = input('Enter the amount you spent: ')else:total = shop(spend) print 'Your bill comes to',total,"\n","your discount was",discount main () #program works but how would i show the discount in main? I saved as text file in notepad! Many thanks # -*- coding: cp1252 -*- def shop(total_spend): min_spend=25 discount_amount=150 discount=0.05 if total_spend >= min_spend and total_spend > discount_amount: checkout=total_spend-(total_spend*discount) discount=total_spend*discount else: checkout = total_spend discount = 0 return checkout def main(): spend = input('Enter the amount you spent: ') while spend<25: print "Error, min spend is 25 in this shop!" spend = input('Enter the amount you spent: ') else: total = shop(spend) print 'Your bill comes to',total,"\n","your discount was",discount main () ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] urgent help!!!!!!!!!!!
i know i'm stupid but i have tried everything to get one line of text working, i have written out pseudo and read every website.now i am getting this error Traceback (most recent call last): File "F:\VTOS ATHLONE\PYTHON_VTOS\foreign exchange\f_ex4 - Copy.py", line 24, in main() File "F:\VTOS ATHLONE\PYTHON_VTOS\foreign exchange\f_ex4 - Copy.py", line 14, in main while amount<50:UnboundLocalError: local variable 'amount' referenced before assignment>>> def exchange(cash_in):euro=1dollar=1.35base=50if cash_in>base: totalreturn=cash_in*dollarelse:totalreturn=0return totalreturn amount=0def main():while amount<50:amount = raw_input(float('how much do you want to change:'))if amount<50:total=0print 'enter an amount over 50: 'else:total=exchange(amount)print 'Your exchange comes to: ',total Adrian Kelly 1 Bramble Close Baylough Athlone County Westmeath 0879495663 From: waynejwer...@gmail.com Date: Thu, 17 Nov 2011 16:53:59 -0600 Subject: Re: [Tutor] please help - stuck for hours To: kellyadr...@hotmail.com CC: tutor@python.org On Thu, Nov 17, 2011 at 4:32 PM, ADRIAN KELLY wrote: thanks very much, great response really really appreciated it and now i understand. i hate to ask again but can you see why it won't print the 'enter and amount over 50' in the right place?? Computers are unfailingly stupid machines. They will do whatever wrong thing you tell them to do every single time. def main():amount=0while amount<50:amount = input('how much do you want to change:') print 'enter an amount over €50: 'else: total=exchange(amount)print 'Your exchange comes to: ',total Sometimes it helps writing out the logic in steps before you translate it to code. In this case my guess is that these are the steps you want: 1. Get a value from the user (you're still using input - stop that, it's dangerous! input is only a good function in 3.x where it replaces raw_input) 2. If the value is less than 50, tell the user to enter an amount > 50 and repeat step 1 3. Otherwise, exchange the amount and display that. Right now, these are the steps that you're doing: 1. Get a value from the user 2. Display the error message 3. If the value is < 50, go to 1 4. exchange the amount 5. display the amount. HTH,Wayne ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] please help - stuck for hours
i know i should use input but when i changed to raw_input it wouldn't recognise the word print on the next line. honestly i have tried everything to get this working..i am 6 hrs at one program Adrian Kelly 1 Bramble Close Baylough Athlone County Westmeath 0879495663 From: waynejwer...@gmail.com Date: Thu, 17 Nov 2011 16:53:59 -0600 Subject: Re: [Tutor] please help - stuck for hours To: kellyadr...@hotmail.com CC: tutor@python.org On Thu, Nov 17, 2011 at 4:32 PM, ADRIAN KELLY wrote: thanks very much, great response really really appreciated it and now i understand. i hate to ask again but can you see why it won't print the 'enter and amount over 50' in the right place?? Computers are unfailingly stupid machines. They will do whatever wrong thing you tell them to do every single time. def main():amount=0while amount<50:amount = input('how much do you want to change:') print 'enter an amount over €50: 'else: total=exchange(amount)print 'Your exchange comes to: ',total Sometimes it helps writing out the logic in steps before you translate it to code. In this case my guess is that these are the steps you want: 1. Get a value from the user (you're still using input - stop that, it's dangerous! input is only a good function in 3.x where it replaces raw_input) 2. If the value is less than 50, tell the user to enter an amount > 50 and repeat step 1 3. Otherwise, exchange the amount and display that. Right now, these are the steps that you're doing: 1. Get a value from the user 2. Display the error message 3. If the value is < 50, go to 1 4. exchange the amount 5. display the amount. HTH,Wayne ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] please help - stuck for hours
thanks very much, great response really really appreciated it and now i understand. i hate to ask again but can you see why it won't print the 'enter and amount over 50' in the right place?? # -*- coding: cp1252 -*-def exchange(cash_in):euro=1dollar=1.35 base=50if cash_in>base:totalreturn=cash_in*dollarelse: totalreturn=0return totalreturn def main():amount=0while amount<50:amount = input('how much do you want to change:')print 'enter an amount over €50: 'else: total=exchange(amount)print 'Your exchange comes to: ',total main() Adrian Kelly 1 Bramble Close Baylough Athlone County Westmeath 0879495663 From: waynejwer...@gmail.com Date: Thu, 17 Nov 2011 15:35:29 -0600 Subject: Re: [Tutor] please help - stuck for hours To: kellyadr...@hotmail.com CC: tutor@python.org On Thu, Nov 17, 2011 at 3:19 PM, ADRIAN KELLY wrote: i have tried everything, i am trying to build in a loop to my 2 functions which worked fine up until my latest sorti. please have a look if you can.. def exchange(cash_in):euro=1dollar=1.35 base=50if cash_in>base:totalreturn=cash_in*dollar else:totalreturn=0return totalreturn def main(): amount=""while amount<50:print 'Sorry, cannot convert an amount under €50 ' amount = input('how much do you want to change:')else: total=exchange(amount)print 'Your exchange comes to: ',total main() Traceback (most recent call last): File "F:\VTOS ATHLONE\PYTHON_VTOS\foreign exchange\f_ex3.py", line 27, in main() File "F:\VTOS ATHLONE\PYTHON_VTOS\foreign exchange\f_ex3.py", line 19, in main total=exchange(amount) File "F:\VTOS ATHLONE\PYTHON_VTOS\foreign exchange\f_ex3.py", line 7, in exchangetotalreturn=cash_in*dollar TypeError: can't multiply sequence by non-int of type 'float' Thank you for posting the full traceback - this last line tells you the exact problem - you're trying to multiply a sequence by a float (in this case your sequence is a string). The line right above that tells you the what you tried to do: multiply `cash_in` by `dollar`. Take a look at your code and what do you see? Well, you set `dollar = 1.35`, and you don't change the value elsewhere so that's certainly a float. What about cash_in? Well if you work your way backwards through the traceback you see that it was called with the parameter "amount". Where is amount set? Ah, on that line: amount = input() This line is extremely problematic. First, I see by your print statement that you're using Python 2.x, so input is actually executing arbitrary code. What you *want* is raw_input which returns a string and is much MUCH safer. I don't know what your input value was, but I suspect that you did something like '30' (with the quotes), because otherwise it would evaluate to an integer. It's also possible that you used `amount`, which would evaluate to "" since you already declared it. None of these things are good. Change your initial assignment to : amount = 0 and the input line to: amount = float(raw_input("How much would you like to exchange? ")) This will first get a string from the user and then convert it to a float - which I suspect you'll want, since you're dealing with monetary values.HTH,Wayne ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] infinite loop
#i am nearly there guys..please loop at the infinite loop i am getting here..PLEASE!!#ADRIAN def exchange(cash_in):euro=1dollar=float(1.35)base=50if cash_in>base:totalreturn=cash_in*dollarelse:totalreturn=0 return totalreturn amount=float()def main():amount = float(raw_input('how much do you want to change:'))while amount<50:print 'Sorry, cannot convert an amount under €50 'else:total=exchange(amount)print 'Your exchange comes to: ',total main() ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] please help - stuck for hours
i have tried everything, i am trying to build in a loop to my 2 functions which worked fine up until my latest sorti. please have a look if you can.. def exchange(cash_in):euro=1dollar=1.35base=50if cash_in>base: totalreturn=cash_in*dollarelse:totalreturn=0return totalreturn def main():amount=""while amount<50:print 'Sorry, cannot convert an amount under €50 'amount = input('how much do you want to change:')else:total=exchange(amount)print 'Your exchange comes to: ',total main() Traceback (most recent call last): File "F:\VTOS ATHLONE\PYTHON_VTOS\foreign exchange\f_ex3.py", line 27, in main() File "F:\VTOS ATHLONE\PYTHON_VTOS\foreign exchange\f_ex3.py", line 19, in main total=exchange(amount) File "F:\VTOS ATHLONE\PYTHON_VTOS\foreign exchange\f_ex3.py", line 7, in exchangetotalreturn=cash_in*dollarTypeError: can't multiply sequence by non-int of type 'float'>>> ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] local variable referenced before assignment
you are spot on. thanks very much i understand the problem now and its been solved. very clear help thanks, adrian > Date: Thu, 17 Nov 2011 14:01:19 -0500 > From: d...@davea.name > To: kellyadr...@hotmail.com > CC: tutor@python.org > Subject: Re: [Tutor] local variable referenced before assignment > > On 11/17/2011 01:47 PM, ADRIAN KELLY wrote: > > hi all,keep getting the above error, can't understand or fix it, can anyone > > help. > > def exchange():euro=1dollar=1.35base=50amount = input ('how > > much do you want to change')if amount>base: > > totalreturn=amount*dollarelse:print 'not enough'return > > totalreturn > > print exchange() > > > > > You've been doing better, but this one has lost its formatting > entirely. Are you posting in text mode? > > That's not the entire error message. If you examined the entire > traceback, it'd identify the line with the problem, and the particular > variable that's being used before it's been defined. > > > But since the function is small, i can guess my way through. The > variable is apparently "totalreturn". And when you go through the else > clause you completely miss the assignment to it. When you have a > mechanism like: > > if x > y: >newval = 49 > else: >print "error message" >#newval = -5 > return newval > > Without that second assignment, you'll get "the above error" whenever > the else condition prevails. newval has no value, and in fact doesn't > exist if you go through the else clause. > > > -- > > DaveA > ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] local variable referenced before assignment
hi all,keep getting the above error, can't understand or fix it, can anyone help. def exchange():euro=1dollar=1.35base=50amount = input ('how much do you want to change')if amount>base: totalreturn=amount*dollarelse:print 'not enough'return totalreturn print exchange() Adrian Kelly 1 Bramble Close Baylough Athlone County Westmeath 0879495663 ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] format integer to currency
print ("i own {0:.2f} {1}".format(1.1,"million")) can anyone help me with code to change the format of this to currency €1.10 million thanks for your help ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] modulus
really appreciate that answer thanks very much.. Adrian Kelly 1 Bramble Close Baylough Athlone County Westmeath 0879495663 From: waynejwer...@gmail.com Date: Wed, 16 Nov 2011 09:59:50 -0600 Subject: Re: [Tutor] modulus To: kellyadr...@hotmail.com CC: tutor@python.org On Wed, Nov 16, 2011 at 9:46 AM, ADRIAN KELLY wrote: Please can anyone tell me how i can print this without all the brackets and commas, i know i need the modulus symbol but i dont know how it works. any advice would be appreciated regards adrian def arguments(): name=raw_input ("Please enter your firstname: ") surname=raw_input ("Enter your surname: ") address1=raw_input ("Enter Address line 1: ") address2=raw_input ("Enter Address line 2: ") address3=raw_input ("Enter Address line 3: ") return name,surname,address1,address2,address3 address=arguments() print "%s %s" % address In this case it's not actually modulus, it's just the syntax for string formatting. I'm not sure *what* the reasoning behind the % was, but that's the way it is. There are two ways to do string formatting, the new (.format) and old (%). In new style formatting you use the .format method of the string: "{0} {1} {2}".format("One", 2, "Five") You don't usually have to worry about the type, though you can specify it along with some other useful modifiers for precision, spacing, and alignment. In old style formatting, you use a string with format specifiers (%s, %d, etc.) followed by a tuple of arguments. Here, the lengths have to match exactly - if you have one specifier then you must have a 1-element tuple. In your case, you're returning a 5 element tuple, so you want 5 format specifiers: print "%s %s %s %s %s" % address However, if you just want to print the data out like that you can do it a little easier like this: print ' '.join(address) Or if you are in 3.x or use `from __future__ import print_function` then you can do this: print(*address) HTH, Wayne ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] modulus
Please can anyone tell me how i can print this without all the brackets and commas, i know i need the modulus symbol but i dont know how it works. any advice would be appreciated regards adrian def arguments(): name=raw_input ("Please enter your firstname: ") surname=raw_input ("Enter your surname: ") address1=raw_input ("Enter Address line 1: ") address2=raw_input ("Enter Address line 2: ") address3=raw_input ("Enter Address line 3: ") return name,surname,address1,address2,address3 address=arguments() print "%s %s" % address ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] changing dictionary to lowercase
Ok boss point noted Sent from my iPad On 28 Oct 2011, at 19:05, bob gailer wrote: > Always reply-all so a copy goes to the tutor list. > > Always put your responses following the question rather than at the top of > the email. > > On 10/28/2011 8:28 AM, Adrian wrote: >> >> Thats the original alright bob, id like to change keys to lowercase >> Thanks >> Adrian >> >> Sent from my iPad >> >> On 27 Oct 2011, at 22:49, bob gailer wrote: >> >>> On 10/27/2011 2:25 PM, ADRIAN KELLY wrote: >>>> >>>> >>>> Hi all, >>>> is it possible to change a dictionary list to lowercase..without having to >>>> retype? >>>> e.g. definitions={"Deprecated": "No longer in use", "Depreciation": "fall >>>> in value of an asset"} >>> >>> There seems to be some confusion both in the question and the proposed >>> solutions regarding "lowercase". >>> >>> Re your e.g. - is that the original or the result? >>> >>> It's best to show both. >>> >>> I have to assume that your e.g. is the original since it contains upper >>> case letters. >>> >>> Do you want to change the case of the keys, values or both? >>> >>> -- >>> Bob Gailer >>> 919-636-4239 >>> Chapel Hill NC >> > > > -- > Bob Gailer > 919-636-4239 > Chapel Hill NC ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] changing dictionary to lowercase
Hi all, is it possible to change a dictionary list to lowercase..without having to retype? e.g. definitions={"Deprecated": "No longer in use", "Depreciation": "fall in value of an asset"} i have tried definitions=definitions.lower() regards adrian ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] printing a key not a value
if i have a dictionary called definitions is there a way of printing the keys and not the values that go with them? thanks so much Adrian___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] (no subject)
Hello world, can anyone tell me how i can perfect the program below. it works find (prints 6 random numbers within a range) but on occasions the numbers are repeated. Thanks so much everyone #program that will allow the user to generate random numbers #from a range that they select. import random #set values number=0 base=input ("Enter the bottom of the range? ") upper=input ("Enter the upper limit of your range: ") quantity=input ("How many numbers do you want to select: ") number =0 while number___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] FW: 6 random numbers(again)
> Subject: Re: [Tutor] 6 random numbers > From: shanta...@gmail.com > Date: Mon, 17 Oct 2011 01:53:18 +0530 > CC: tutor@python.org > To: kellyadr...@hotmail.com > > On 17-Oct-2011, at 1:13 AM, ADRIAN KELLY wrote: > > > hello all, > > anyone know how i would go about printing 6 random numbers, i know i could > > copy and paste 6 times (which would work) but i was thinking about a while > > loop, ie. while lottery_numbers.count is <7. > > Is it possible to code this? is it possible to count random variables? i am > > trying to keep the program as simple as possible, cheers > > > > any help would be welcome, > > > > import random > > lottery_numbers=random.randrange(1,42) > > print lottery_numbers > > > > Following example may be useful: > x = [random.randrange(1, 1+random.randrange(42) for _ in range(100)] > > Useful read: > http://docs.python.org/tutorial/datastructures.html > > -- > shantanoo > http://xkcd.com/221/ > ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] 6 random numbers
hello all, anyone know how i would go about printing 6 random numbers, i know i could copy and paste 6 times (which would work) but i was thinking about a while loop, ie. while lottery_numbers.count is <7. Is it possible to code this? is it possible to count random variables? i am trying to keep the program as simple as possible, cheers any help would be welcome, import random lottery_numbers=random.randrange(1,42) print lottery_numbers ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] basic problem
Hi all, can someone spell out to me in (simply if possible) what this programme is doing. i understand the concept of the "for" loop and what its doing with the message the user enters. i just cant understand the VOWELS and how it keeps adding 1 letter to the message. thanks for looking A # this programme will adding something to everything the user #types by using a for loop #set values new_message=" " VOWELS="AEIOU" message=raw_input ("Enter a message: ") for letter in message: if letter.lower() not in VOWELS: new_message = new_message+letter print new_message ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] guess age programme (still stuck!!!!!)
please guys still stuck on this problem and i have been at it for hours so please if anyone can help. it nearly works. am i looking at it from the wrong angle? i have tried everyone's suggestions but i am stuck still... correct code would be nice. thanksadrian (new pythoner) print("\tWelcome to 'Guess My Number'!")print("I'm thinking of a number between 1 and 100.")print("Try to guess it in as few attempts as possible.\n") # set the initial valuesage = 35guess = " "tries = 5 # guessing loopwhile guess!=age and tries>0:tries=tries-1guess = input("Take a guess: ")if guess > age and tries>0:print "Lower...",tries,"left"elif guess < age and tries>0:print "Higher...",tries,"left"elif guess == age and tries>0:print "Correct...well done!!"else:breakprint "Out of attempts" print "\n\nGood guess!!" input ("\n\nPress the enter key to exit.") Date: Fri, 30 Sep 2011 14:31:52 +0200 From: cwi...@compuscan.co.za To: kellyadr...@hotmail.com CC: tutor@python.org Subject: Re: [Tutor] guess age programme (please help) On 2011/09/30 02:04 PM, ADRIAN KELLY wrote: Hi all, can anyone help me with the attached programme. it is fairly basic (like me) i want it to ask the user to guess the age and countdown when making incorrect guesses. it doesn't seem to count the first attempt (run it and see please). i also want to know how to go about setting a condition so that when the guesses = 0, the programme closes or stops etc. any advice would be very grateful (particularly the correct code) i am learning if's and loops so please keep explanations as simple as possible. i really appreciate everyones help adrian ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor Your program does count the first guess, but you print out the remaining number of tries before you subtract the attempt from your counter so if you move your `tries=tries-1` up before your if statements it will reflect the correct number of attempts left to the user. I would suggest changing your while loop to read `while tries > 0:` so it exits when you've exhausted your attempts. You also do not test for equality of your age and the guess in your if statements so if the user guesses the correct age it will tell them that the number is higher. And if the user guesses the correct number you should `break` from the loop else it will carry on going till the number of attempts have been exhausted. -- Email Signature Christian Witts Python Developer ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] guess age programme (please help)
Hi all, can anyone help me with the attached programme. it is fairly basic (like me) i want it to ask the user to guess the age and countdown when making incorrect guesses. it doesn't seem to count the first attempt (run it and see please). i also want to know how to go about setting a condition so that when the guesses = 0, the programme closes or stops etc. any advice would be very grateful (particularly the correct code) i am learning if's and loops so please keep explanations as simple as possible. i really appreciate everyones help adrian guess age_game(broken) Description: Binary data ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] last part of my programme
can anyone tell me why the last part of my programme wont work. i want the user to have to press enter to exit but it doesn't happen through the python interface. the programme works fine otherwise but just shuts down when finished thanks all adrian def this(): print 'hello' print 'i am your computer' # set the values password='gorilla' Given_Password=' ' #password loop while Given_Password.lower() != password.lower(): Given_Password=raw_input ('please enter your password: ') if Given_Password.lower()==password.lower(): print 'Password Accepted ' else: print 'Incorrect' def STATS(): print 'hello' firstname=raw_input ('please enter your firstname: ') lastname=raw_input ('please enter your lastname: ') town=raw_input ('what town are your from? ') county=raw_input ('what county are you from? ') details=name+"\n"+town+"\n"+county print " " print details print "thank's for your time" this() STATS() input("\n\nPress the enter key to exit. ") ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] password loop
Can anyone help me with the programme below; i hope you can see what i am trying to do, if i enter the wrong password the loop goes on forever and if i enter the right one nothing is printed... i am a newbieall comments welcome thanks adrian print 'hello' print 'i am your computer' # set the values password='route' Enter_Password=raw_input ('please enter your password: ') #password loop while Enter_Password != password: if Enter_Password !=password: print 'try again' else: print 'well done' ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] guess-my-number programme
import random print("\tWelcome to 'Guess My Number'!") print("I'm thinking of a number between 1 and 100.") print("Try to guess it in as few attempts as possible.\n") # set the initial values the_number = random.randint(1, 100) guess = int(input("Take a guess: ")) tries = 1 # guessing loop while guess != the_number: if guess > the_number: print("Lower...") else: print("Higher...") guess = int(input("Take a guess: ")) tries = tries + 1 print("You guessed it! The number was", the_number) print("And it only took you", tries, "tries!\n") input("\n\nPress the enter key to exit.") *** can anyone explain the tries part of this programme to me i know its meant to count the number of guesses made by the user by adding 1 but i just cant figure out how it does this..can someone explain?? i.e. tries = 1, tries +1 etc cant get my head around it... thanks all Adrian Kelly 1 Bramble Close Baylough Athlone County Westmeath 0879495663 ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] On off Toggle
class Television(object): def __init__(self,__channel,volume,is_on): self.volume = volume self.is_on = "Power is off" power = self.is_on def toggle_power(self): if choice == "1" and power == self.is_on : power = "Power is Now on" elif choice =="1" and power =="Power is Now on" : power = self.is_on print power def instructions(): print "0 - Exit" print "1 - Toggle Power" print "2 - Change Channel" print "3 - Raise Volume" print "4 - Lower Volume" #Main choice = "" while choice != 0: choice = raw_input("Can I have a selection number? : ") tv = Television(0,50,"is_on") tv.toggle_power() I'm trying to make a toggle to turn the power on and off in the toggle_power method but I cannot figure this out. Any help would be greatly appreciated ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Delete file before function ends
I'll take a peek at the subprocess docs Steve, and see if I can learn something there... Thanks for the suggestion! I'm using WinXP as well Wayne.. Not too sure why yours works, and mine doesn't.. I'll revisit what I'm doing and also check into Steve's suggestion. Adrian On Mon, Oct 6, 2008 at 2:30 PM, W W <[EMAIL PROTECTED]> wrote: > What OS are you using, Adrian? On WinXP, this worked fine: > > import os > > def files(): > os.startfile('myfile.txt') > os.remove('myfile.txt') > > -Wayne > ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Delete file before function ends
Thanks for the input folks. Sadly, Tim's suggestion yields the same results as I was getting previously. My second program very graciously tells me that the file I'm trying to open doesn't exist. Like the code snippet I posted, the timer.sleep(x) line just waits the 'x' seconds until opening 'mytextfile.xyz", instead of opening it, and then waiting 'x' seconds to delete the file. Sorry about naming the path to my file so "poorly"!! I'm a little more careful in my programs! I'm a newbie and I was more concerned about an understandable question! As a newbie, Alan, I was kinda scared you'd say that "threads" were the answer here! (It sounds like someone is going to get sucked into a worm hole or something...) Looks like the next class in my Python education is going to be "Threads 101"... Thanks for all the input, I might even be learning something! Warmest regards, Adrian On Mon, Oct 6, 2008 at 1:31 PM, Alan Gauld <[EMAIL PROTECTED]>wrote: > > "Adrian Greyling" <[EMAIL PROTECTED]> wrote > > that creates my "problem"... What I'd like to do, is create a plain text >> file, use the associated program to open said textfile, (using >> os.startfile) >> and after the associated program has what it needs to open the file and >> then >> of course, has the current focus, I'd like to delete the text file >> > > Thats potentially going to cause the associated program to crash > but assuming you know what you are doing there... > > What happens with the code snippet below, is that it doesn't start >> the second program until the function is finished. >> > > Correct, that's what you asked it to do :-) > > time.sleep() in between the os.startfile() and os.remove(), but it just >> delays opening 'mytextfile.xyz' and actually deletes the file before my >> second program can open it up. >> > > Really? That shouldn't happen! > > path = "c:\MyFolder\mytextfile.xyz" >> > > You probably want to either use forward slashes or put > an r in front of the quotes, otherwise Python will treat > the \ as an escape character... > > #bunch of stuff here to create 'mytextfile.xyz" >> os.startfile(path) >> os.remove(path) >> > > If you want the remove to run in parallel with the startfile > you probably need to use threads to start the application > in one thread and then pause and then delete the file in > the other thread. > > Alan > > ___ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Delete file before function ends
Greetings all, Not sure if this is possible, but I'll ask anyway. Below is a code snippet that creates my "problem"... What I'd like to do, is create a plain text file, use the associated program to open said textfile, (using os.startfile) and after the associated program has what it needs to open the file and then of course, has the current focus, I'd like to delete the text file in the background, so to speak. (Please assume that the program doesn't lock 'mytextfile.xyz' when it opens it.) What happens with the code snippet below, is that it doesn't really start the second program until the function is finished. I tried using time.sleep() in between the os.startfile() and os.remove(), but it just delays opening 'mytextfile.xyz' and actually deletes the file before my second program can open it up. Any way around this?? path = "c:\MyFolder\mytextfile.xyz" #bunch of stuff here to create 'mytextfile.xyz" os.startfile(path) os.remove(path) Thanks everyone, Adrian ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] pysqlite and SQLite
Thanks for the response Chad! I'm using Python 2.5.2, so I guess I'm in the clear then, although I'm still getting an unexplained error message. I've taken my program and used GUI2exe to create a standalone executable. When I run said executable on my own WinXP machine, it works just fine. When I attempt to use the same executable (including the "dist" directory) on a (virtually) identical PC, I get the following error message: pysqlite2.dbapi2.OperationalError: near ",": syntax error I understand the error, but not why I get it on one PC and not another... Adrian On Mon, Sep 29, 2008 at 1:09 PM, Chad Crabtree <[EMAIL PROTECTED]> wrote: > If you are using Python 2.5 or newer then no you will not need to install > SQLite. > > On Mon, Sep 29, 2008 at 1:05 PM, Adrian Greyling < > [EMAIL PROTECTED]> wrote: > >> Probably a really dumb question, but... Do I have to download and install >> SQLite before pysqlite will work properly? >> Thanks, >> Adrian >> >> ___ >> Tutor maillist - Tutor@python.org >> http://mail.python.org/mailman/listinfo/tutor >> >> > ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] pysqlite and SQLite
Probably a really dumb question, but... Do I have to download and install SQLite before pysqlite will work properly? Thanks, Adrian ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Current path (of program)
Is it a faux pas to answer your own question?? I found this after I tweaked my search terms.. >From "Dive Into Python" ( http://diveintopython.org/functional_programming/finding_the_path.html)<http://diveintopython.org/functional_programming/finding_the_path.html> pathname = os.path.dirname(sys.argv[0]) currpath = os.path.abspath(pathname) "Regardless of how you run a script, sys.argv[0] will always contain the name of the script, exactly as it appears on the command line. This may or may not include any path information. os.path.dirname takes a filename as a string and returns the directory path portion. If the given filename does not include any path information, os.path.dirname returns an empty string. os.path.abspath is the key here. It takes a pathname, which can be partial or even blank, and returns a fully qualified pathname." Sorry about that folks... Adrian On Thu, Sep 25, 2008 at 3:25 PM, Adrian Greyling <[EMAIL PROTECTED]>wrote: > I've been using "os.getcwd()" to get my program's "current path". I know > it's actually returning my "current working directory", but it's been > working okay, until today... I used py2exe (and InnoSetup) to create a > standalone executable (for Windows) and then a shortcut icon on the desktop > to "MyProg.exe". Problem is, now "os.getcwd()" returns "C:\Documents and > Settings\ME\Desktop\" as it's current working directory, not the "C:\Program > Files\MyCoolProgram\" that I was expecting. > > I'm trying to use a "relative path reference" so that the user can install > the program to whatever directory he/she wants, but that my program won't > "lose track" of the subdirectories it requires for additional files. > > Anyone run into the same sort of problem? Better yet, anyone know how to > solve this? > > Thanks everyone! > Adrian > ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Current path (of program)
I've been using "os.getcwd()" to get my program's "current path". I know it's actually returning my "current working directory", but it's been working okay, until today... I used py2exe (and InnoSetup) to create a standalone executable (for Windows) and then a shortcut icon on the desktop to "MyProg.exe". Problem is, now "os.getcwd()" returns "C:\Documents and Settings\ME\Desktop\" as it's current working directory, not the "C:\Program Files\MyCoolProgram\" that I was expecting. I'm trying to use a "relative path reference" so that the user can install the program to whatever directory he/she wants, but that my program won't "lose track" of the subdirectories it requires for additional files. Anyone run into the same sort of problem? Better yet, anyone know how to solve this? Thanks everyone! Adrian ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Is this a "Class" problem?
I appreciate the feedback! I'll check out the pubsub module and see how that works out and I'll subscribe to the wxPython group too! Thanks again! On Fri, Aug 29, 2008 at 5:31 PM, Kent Johnson <[EMAIL PROTECTED]> wrote: > On Fri, Aug 29, 2008 at 12:19 PM, Adrian Greyling > <[EMAIL PROTECTED]> wrote: > > > Here's where I get fuzzy... Let's say I've got a "frame_1" object > > that opens a new "frame_2" object. As you've suggested above, I'll use > "m" > > to create an instance of a frame object. Now frame_2 opens a "dialog_1'" > > which asks for information that is sent back to 'frame_2'. How do I > > reference 'frame_2' in this case? Especially when frame_2 hasn't been > > closed and has just been waiting behind dialog_1 until dialog_1 closes. > > When I try to reference it again as "m = frame_2(self)" from a new > function > > definition, aren't I creating a brand new frame_2 object that has "blank" > > attributes, so to speak? > > Generally the way this works is something like: > - frame 2 creates dialog box > - frame 2 shows dialog box and waits for the dialog box to be dismissed > - frame 2 gets result from dialog box > > There are several examples of this in the wx demo, see > MultiChoiceDialog, SingleChoiceDialog, TextEntryDialog. If you are > writing your own custom dialog, make a method that allows the client > code to retrieve the user data from it. > > Kent > ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Is this a "Class" problem?
Thanks for the response Jeff, although your answer has spawned another question or two! In your answer, you showed that the attribute " MySecondFrame.text_ctrl_2" doesn't exist and to correct that, you suggested the code below. (What I understand from your response is that I can't reference the original object, but I must create an instance of it. Is that right??) def MainToSecond(self, event): # wxGlade: MyMainFrame. m = MySecondFrame(self) m.Show() m.text_ctrl_2.SetValue("This text was generated from the 'MainFrame' window") Here's where I get fuzzy... Let's say I've got a "frame_1" object that opens a new "frame_2" object. As you've suggested above, I'll use "m" to create an instance of a frame object. Now frame_2 opens a "dialog_1'" which asks for information that is sent back to 'frame_2'. How do I reference 'frame_2' in this case? Especially when frame_2 hasn't been closed and has just been waiting behind dialog_1 until dialog_1 closes. When I try to reference it again as "m = frame_2(self)" from a new function definition, aren't I creating a brand new frame_2 object that has "blank" attributes, so to speak? I'm sure I've made things clear as mud, but hopefully with my blathering, someone will undertand my utter confusion! Thanks everyone! Adrian On Mon, Aug 18, 2008 at 3:29 PM, Jeff Younker <[EMAIL PROTECTED]> wrote: > On Aug 18, 2008, at 9:13 AM, Adrian Greyling wrote: > > def MainToSecond(self, event): # wxGlade: MyMainFrame. > MySecondFrame(self).Show() > MySecondFrame.text_ctrl_2.SetValue("This text was generated from > the 'MainFrame' window") > > > The expression MySecondFrame(self) creates a new object. It > initializes the new object by calling the MySecondFrame's __init__ > method. > > class MySecondFrame(wx.Frame): > def __init__(self, *args, **kwds): > # begin wxGlade: MySecondFrame.__init__ > ... > > self.text_ctrl_2 = wx.TextCtrl(self, -1, "", > style=wx.TE_MULTILINE) > ... > > > > The __init__ method calls sets the variable text_ctrl_2 in the object > m. > > Your function MainToSecond is trying to get the attribute > MySecondFrame.text_ctrl_2. > This attribute does not exist. You want to get the attribute > m.text_ctrl_2. So, the method > should be: > > def MainToSecond(self, event): # wxGlade: MyMainFrame. > m = MySecondFrame(self) > m.Show() > m.text_ctrl_2.SetValue("This text was generated from the > 'MainFrame' window") > > > Also, method and function names should always start with a lower case > letter: always > mainToSecond and never MainToSecond > > -jeff > ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Is this a "Class" problem?
Hi folks! I hope I'm in the right place to ask this question. I'm new to Python and have been working through some tutorials and have made it to the GUI creation stage. All I was hoping to do with the code below, was to open a "secondary" window and have some text end up on a text_ctrl, but I get an error message that looks like this: Traceback (most recent call last): File "textbox2TEST.py", line 36, in MainToSecond MySecondFrame.text_ctrl_2.SetValue("This text was generated from the 'MainFrame' window") AttributeError: type object 'MySecondFrame' has no attribute 'text_ctrl_2' I'm using wxGlade and SPE together, so almost all of the code is generated for me. I just don't get why it doesn't work, although I think it has to do with one class referencing another class, and I'm obviously not doing that correctly... Any help is much appreciated! Here's the code that created the error: import wx class MyMainFrame(wx.Frame): def __init__(self, *args, **kwds): # begin wxGlade: MyMainFrame.__init__ kwds["style"] = wx.DEFAULT_FRAME_STYLE wx.Frame.__init__(self, *args, **kwds) self.text_ctrl_1 = wx.TextCtrl(self, -1, "", style=wx.TE_MULTILINE) self.button_1 = wx.Button(self, -1, "Click me to bring up second window and write some text") self.__set_properties() self.__do_layout() self.Bind(wx.EVT_BUTTON, self.MainToSecond, self.button_1) # end wxGlade def __set_properties(self): # begin wxGlade: MyMainFrame.__set_properties self.SetTitle("Main Frame") # end wxGlade def __do_layout(self): # begin wxGlade: MyMainFrame.__do_layout sizer_1 = wx.BoxSizer(wx.VERTICAL) sizer_2 = wx.BoxSizer(wx.VERTICAL) sizer_2.Add(self.text_ctrl_1, 1, wx.EXPAND|wx.ADJUST_MINSIZE, 0) sizer_2.Add(self.button_1, 0, wx.EXPAND|wx.ADJUST_MINSIZE, 0) sizer_1.Add(sizer_2, 1, wx.EXPAND, 0) self.SetSizer(sizer_1) sizer_1.Fit(self) self.Layout() # end wxGlade def MainToSecond(self, event): # wxGlade: MyMainFrame. MySecondFrame(self).Show() MySecondFrame.text_ctrl_2.SetValue("This text was generated from the 'MainFrame' window") # end of class MyMainFrame class MySecondFrame(wx.Frame): def __init__(self, *args, **kwds): # begin wxGlade: MySecondFrame.__init__ kwds["style"] = wx.DEFAULT_FRAME_STYLE wx.Frame.__init__(self, *args, **kwds) self.text_ctrl_2 = wx.TextCtrl(self, -1, "", style=wx.TE_MULTILINE) self.button_2 = wx.Button(self, -1, "Click me to close this frame and send some text back to the MainFrame") self.__set_properties() self.__do_layout() # end wxGlade def __set_properties(self): # begin wxGlade: MySecondFrame.__set_properties self.SetTitle("Frame Number Two") # end wxGlade def __do_layout(self): # begin wxGlade: MySecondFrame.__do_layout sizer_3 = wx.BoxSizer(wx.HORIZONTAL) sizer_4 = wx.BoxSizer(wx.VERTICAL) sizer_4.Add(self.text_ctrl_2, 1, wx.EXPAND|wx.ADJUST_MINSIZE, 0) sizer_4.Add(self.button_2, 0, wx.EXPAND|wx.ADJUST_MINSIZE, 0) sizer_3.Add(sizer_4, 1, wx.EXPAND, 0) self.SetSizer(sizer_3) sizer_3.Fit(self) self.Layout() # end wxGlade # end of class MySecondFrame if __name__ == "__main__": app = wx.PySimpleApp(0) wx.InitAllImageHandlers() frame_1 = MyMainFrame(None, -1, "") app.SetTopWindow(frame_1) frame_1.Show() app.MainLoop() ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor