I tried it on my Windows XP and it works as Vega says. What operating system you have? The control uses different audio drivers for each OS.
Does it play sound at all?
I tried it on my Windows XP and it works as Vega says. What operating system you have? The control uses different audio drivers for each OS.
Does it play sound at all?
Could be different level of XP upgrade. Early version of Window XP quite buggy!
>>> a = "string"
>>> b = "string"
>>> id(a)
11147264
>>> id(b)
11147264
"string" is really the object here, an immutable object, so both a and b reference the same object. Now, if you use "string ", then string with a space is a different and new object.
In the case with the two lists, you have a mutable object that can be changed in place, like you could reverse list1 but not list2. For that reason list1 and list2 have different references.
Hey vega, that works pretty smooth!
If you have two lists like
list1 = [1, 2, 3]
list2 = [1, 2, 3]
then
list1 == list2 is True, they have equal content
but
list1 is list2 would give False, they are not the same object.
The Python module threading allows you to run a function in the background, as your main program executes. This example adds another feature of Python, called function decoration, the @decorator is added to just above the function you want to run in the background, as example shows:
# running a function in the background with threading
# (apply threading to a function with a function @decorator)
import time
import threading
def background(f):
def bg_f(*a, **kw):
threading.Thread(target=f, args=a, kwargs=kw).start()
return bg_f
# the @decorator forces this function to run in the background
@background
def counter(n):
i = 0
while i < n:
print i
i += 1
time.sleep(0.5) # 0.5 second delay
counter(7)
time.sleep(0.4)
print 'hello' # prints hello, before counter prints 1 ...
time.sleep(1.2)
print 'world' # prints world, before counter prints 4 ...
Output looks like:
0
hello
1
2
3
world
4
5
6
If you bind GUI event to a function you use a callback function, alas, callback functions are not allowed to have arguments. To remedy situation you can use currying or lambda. Here is an examples of both:
# currying allows GUI callback functions to have arguments
# an alternative is lambda
from Tkinter import *
class Curry:
"""adds arguments to callback function"""
def __init__(self, callback, *args, **kwargs):
self.callback = callback
self.args = args
self.kwargs = kwargs
def __call__(self):
# needs Python23 or higher
return self.callback(*self.args, **self.kwargs)
def callback(what=None):
print "callback =", what # for testing
if what == 'red':
b1.config(bg="#ff0000")
if what == 'blue':
b2.config(bg="#0000ff")
root = Tk()
# uses class Curry, since command=callback("red") will not work
b1 = Button(root, text="red", width=6, command=Curry(callback, "red"))
b1.pack(side=LEFT, padx=2, pady=2)
# uses lambda instead of Curry
b2 = Button(root, text="blue", width=6, command=lambda: callback("blue"))
b2.pack(side=LEFT, padx=2, pady=2)
mainloop()
Editor's Note:
command uses a function object rather then a function call, so arguments have to be added with a lambda or curry wrapper.
You can use Python program to extract picture from web page and save it. I have tested this with Windows XP, might work with other OS:
# load given picture from web page and save it
# (you have to be on the internet to do this)
import urllib2
import webbrowser
import os
# find yourself a picture on a web page you like
# (right click on the picture, look under properties and copy the address)
picture_page = "http://www.google.com/intl/en/images/logo.gif"
#webbrowser.open(picture_page) # test
# open the web page picture and read it into variable
opener1 = urllib2.build_opener()
page1 = opener1.open(picture_page)
my_picture = page1.read()
# open file for binary write and save picture
# picture_page[-4:] extracts extension eg. .gif
# (most image file extensions have three letters, otherwise modify)
filename = "my_image" + picture_page[-4:]
print filename # test
fout = open(filename, "wb")
fout.write(my_picture)
fout.close()
# was it saved correctly?
# test it out ...
webbrowser.open(filename)
Thanks for answer, for complete pyhthon n00b , this is pretty complex coding!!!
Which Python GUI kit are you using?
What is your operating system?
Well, I can help with the startButton text:
def dieSimulator():
startButton.configure(text="Restart")
# rest of your code .......
Have you checked into function reload(my_module)?
What happened to your indentations?
Give me an example of your list.
Also, wouldn't use list as variable name since list() is built-in function, just as len().
Could you enlighten me, what is this all used for?
Works great, thank you!
I would just cancel the tread.
Actually, I like your friend's solution. You can easily expand it to bring up the widget's name:
# which widget has been clicked?
from Tkinter import *
root = Tk()
root.title('Click on ovals')
canvas1 = Canvas()
canvas1.pack()
def func1(event):
print widget_list[canvas1.find_withtag(CURRENT)[0]-1]
oval1 = canvas1.create_oval(10, 30, 40, 50, fill='red', tags='click')
oval2 = canvas1.create_oval(50, 70, 80, 90, fill='blue', tags='click')
oval3 = canvas1.create_oval(90, 110, 120, 130, fill='green', tags='click')
widget_list = ['oval1', 'oval2', 'oval3']
# left mouse click = '<1>'
canvas1.tag_bind('click', '<1>', func1)
mainloop()
How do I best get a full display screen window using wxPython?
What operating system do you have?
Did you install proper version of wxPython?
I have Windows XP and my wx package is in
C:\Python24\Lib\site-packages\wx-2.6-msw-unicode\wx\__init__.py
Here is a simple sample of wxPython code:
import wx
class MyFrame(wx.Frame):
def __init__(self):
# create a frame/window, no parent, default to wxID_ANY
wx.Frame.__init__(self, None, wx.ID_ANY, 'wxPython', pos=(300, 150), size=(300, 350))
self.SetBackgroundColour('green')
# show the frame
self.Show(True)
application = wx.PySimpleApp()
# call class MyFrame
window = MyFrame()
# start the event loop
application.MainLoop()
You have to set widget for name to come up. At the moment I don't quite know how, I don't have my notes along.
Given featureList = what do you expect as result?
Please give complete result.
Python allows you to combine a number of statements into one-liner:
str1 = "we willing women want warm winter woollies"
list1 = str1.split()
print list1 # ['we', 'willing', 'women', 'want', 'warm', 'winter', 'woollies']
list2 = [frag[:2] for frag in list1]
print list2 # ['we', 'wi', 'wo', 'wa', 'wa', 'wi', 'wo']
str2 = "".join(list2)
print str2 # wewiwowawawiwo
# combine all three statements
print "".join([frag[:2] for frag in str1.split()])
Here you have it, but watch out it becomes hard to read and understand at times. Me thinks, me just invented a new word "wewiwowawawiwo". Has nifty ring to it!
Make financial calculator that would show you monthly payments on a loan, or how long you would take to pay off your debts with certain monthly payments, or how many years it would take for your savings to double.
Ever wrote a Python program and wanted to use passwords? What good is password, if the user can simply look at your code and see it?
The module md5 comes to the rescue! It converts the password string to string containing series of hexadecimal numbers. You do that in program1, then copy and paste this hex string into your program (program2).
Here is program1 (keep that to yourself in save place):
# program 1, code to generate a hashed password
# the result is a series of hexadecimal numbers
# it is saved to one text file, so you can
# copy and paste it to program2 from any editor
import md5
# pick a password you can remember
password = "gummy"
pw_hashed = md5.md5(password).hexdigest()
print pw_hashed # just testing
fout = open("MyHashedPassword.txt", "w")
fout.write(pw_hashed)
fout.close()
This is program2, showing only hex string hashed password, but user has to enter password 'gummy' for md5 to match:
# program2, copy hashed password from program1 and assign
# it to MYPASSWORDHASH as string, this is all user would see,
# if looking at your code
import md5
MYPASSWORDHASH = "c1944508a0d871c55b501624c36e0f68"
def get_password():
# give it three tries
for i in range(3):
password = md5.md5(raw_input("Enter your password: "))
password = password.hexdigest()
if password == MYPASSWORDHASH:
return True
return False
def main():
if get_password():
print "Success"
# do something here with rest of the program code
else:
print "Failure"
# do something else here
if __name__ == "__main__":
main()
Can you give sample of the first ten lines of each file?
If the lines match (word and number), then you can read in one line from each file at a time, process and write/append back out.
I started playing with code from you and came to this conclusion:
# want 'abc' to generate a list [['a','bc'],['bc','a'],['c','ab'],['ab','c'],['b','ac'],['ac','b']]
def gensubset(colocation):
rulesList= []
length = len(colocation)
for i in range(0,length):
rule1 = [colocation[i:i+1],colocation[i+1:length]]
rule2 = [colocation[i+1:length],colocation[i:i+1]]
rulesList.append(rule1)
rulesList.append(rule2)
return rulesList
colocation = 'abc'
sublist = gensubset(colocation)
# not quite there yet, also when i+1 exceeds index you get empty elements ''
print sublist # [['a', 'bc'], ['bc', 'a'], ['b', 'c'], ['c', 'b'], ['c', ''], ['', 'c']]
To use slicing to create for example 'ab' or 'ac' you need to add more to rules you use:
str1 = 'abc'
length = len(str1)
i = 0
print str1[i:length-1] # 'ab'
print str1[i:i+1] + str1[i+2:length] # 'ac'
I don't see these type of slices in rules you have written.
This is cool, so initially list1[0] is zero to start the count!
How can you wrap that into a normal bread and butter function?
You put program code in a loop and designate one key to break out of loop:
while True:
# this is an example of your program:
print
print "My program! Really!"
print
choice = raw_input("Enter r (repeat) or q (quit): ")
if 'q' in choice:
break # exits the while loop, any other key repeats loop
Sorry, this is little clumsy, but I am using good friend's notebook in busy coffee shop. I hope this explains what you want to do:
# list of lists
list1 = [['a', 1], ['b', 2]]
# list of numbers
list2 = [44, 77]
# convert list of lists to a tuple of tuples using list comprehension
tuple1 = tuple([tuple(sublist) for sublist in list1])
print tuple1 # (('a', 1), ('b', 2))
# create a dictionary from a tuple and a list using zip()
# the tuple forms the key and the list forms the value
dict1 = dict(zip(tuple1, list2))
print dict1 # {('a', 1): 44, ('b', 2): 77}
is an invalid construct and gives a syntax error!
Do you mean dictionary {'a': 1,'b': 2} ?
If you want the same data/info in a tuple you could use (('a', 1),('b', 2)) and later on ...
# convert tuple of tuples to dictionary
print dict((('a', 1),('b', 2))) # {'a': 1, 'b': 2}
Here is a possible way to create tuples from lists:
list1 = [1, 2, 3]
tuple1 = tuple(list1)
print list1 # [1, 2, 3]
print tuple1 # (1, 2, 3)
list2 = [[1, 2], [3, 4]]
tuple2 = tuple([tuple(sublist) for sublist in list2])
print list2 # [[1, 2], [3, 4]]
print tuple2 # ((1, 2), (3, 4))
You need to give more details of what you want to accomplish.
At first look, there are quite a few errors in your code. Your indentations are a mess (they are not cosmetic, they actually form statement blocks in Python!), if needs == as comparison operator, for needs colon at the end of line, and pruned_new has to be initiated as empty list.
Indentations are the bread and butter of Python. Yours are all messed up! Did you mix tabs and spaces in your code? Avoid the mix!
This is corrected code:
def get_colocations(filename):
sentences = open(filename).read().split("\n")
colocations = []
for sent in sentences:
colocations.append(sent)
return colocations
def main():
colocations = get_colocations("colocations.txt") # !!!!!!!!!
print "Colocations are",colocations
main()
Dictionary keys have to be immutable objects. Lists are mutable objects. Comvert all the lists to tuples.
I don't have linux OS on my machine, but fail to understand why wxPython should bring up a gtk error?
Also, is gdk and gtk a mix up?
Please use code tags around your Python code to show proper indentations, take a look here:
http://www.daniweb.com/techtalkforums/announcement114-3.html
All statement lines that belong to while loop get an indentation of 4 spaces (4 is traditional with Python code). I have removed main() as that is throwback to C. Also wrap your code in code tags,see:
http://www.daniweb.com/techtalkforums/announcement114-3.html
print "This program calculates how long it takes for an investment to double in size."
print
investment = 1000 #initial investment
rate = input("Please enter the applicable interest rate: ") #interest rate input
years = 0 #sets years to zero
value = investment
while value <= investment*2: #defines loop sentinel
value = value + value*((float(rate)/100)) #calculates investment
years = years + 1 #adds a year for every loop
print "The investment doubles in",years,"years" #prints the years it took to double the investment
raw_input("Press enter to go on ...") # optional console wait
Also, some of your statement lines are so obvious that comment is simply not needed, or is distraction at best!
OK Ene,
pretty smooth! I used
if next_day.weekday() == 4 and next_day.day == 13:
after reading through help("datetime")
How did you know my first name was Henri?
Is there a good way to access browser like IE and run an HTML file from within Python code?
Write a hex-dump program, where you read a file byte by byte and display the value as a hexadecimal number (base 16). Display about 16 bytes on each row and in a second column next to it show any printable characters, useful for text.
Hi Ene, looks like you are working on Friday the 13th project. It took me a while, but I solved it. I can give you a hint, replace the line
print next_day
with this expanded line
print next_day, "day of week =", next_day.weekday()
The week starts with Monday = 0 that means Friday = 4
Have fun!
...
Also, why are you using self.button1 = Button( ... ) and not just button1 = Button( ... )?
The self. prefix makes the button global within the class, so it can be used by methods of the class.
Im sort of new to python, and I have been looking at some tutorials, manuals, etc. and I saw how to find prime numbers, so I thought it would be a good place to start, so I added some stuff to hopefully allow for user input, and it doesnt work.
>>> z=input('please enter the lowest number to search for prime numbers from') if z<=1: z=2 print "low value changed to 2" >>> y=input('please enter the highest number to search for prime numbers to') >>> for n in range(z, y): for x in range(z, n): if n % x == 0: break else: # loop fell through without finding a factor print n, 'is a prime number'
What am I doing wrong?
Please use editor or IDE to write program, using the shell with the >>> prompts makes it hard to test your program for most of us. Here is my correction:
z = input('please enter the lowest number to search for prime numbers from ')
if z <= 1:
z = 3
print "low value changed to 3"
y = input('please enter the highest number to search for prime numbers to ')
for n in range(z, y+1): # range to include y
for x in range(2, n): # x starts with 2 !!!!!!!!!!
if n % x == 0:
break
else:
# else belongs to for, loop fell through without finding a factor
print n, 'is a prime number'
I am sorry I was out and so could not reply in time
what exactly i am looking for is in reverse way
is it possible to define test_path = "test1234" in testing module
and can be accessed by test1.pyso that i can provide some browsing interface for file path selection for
test_path in testing fileThank you for the reply
You could save test_path info in file that is opened by test1.py every time it is imported/ativated. Make sure there is default path, in case the file does not exist.
Looks more like message from lint-filter, telling you to use self. Some of the commercial IDEs have filters built in.
Try this short Tkinter code, only tested it on Windows XP:
from Tkinter import *
root = Tk()
sw = root.winfo_screenwidth()
sh = root.winfo_screenheight()
# test
print "screen width =", sw
print "screen height =", sh
# set to full screen use this:
root.geometry("%dx%d+0+0" % (sw, sh))
# more code here
root.mainloop()
Learn several languages. You may want to learn one language that runs on more than just Microsoft platform.
Use the while loop for indeterminate number of entries, for loop for fixed number. If you need to use main(), define main to call your calc_sum function. Let the user know how to stop the loop.
# while loop is used to sum an indeterminate number of integers entered, until you enter a zero
def calc_sum():
sum = 0
x = input("Enter a number (0 to stop) >> ")
while x != 0:
sum = sum + x
x = input("Enter a number (0 to stop) >> ")
print "\nThe sum of the numbers is", sum
def main():
calc_sum()
main()
Very nice effort, just a a few corrections needed to make this work.
# class.py
# tpm
# A program to calculate the volume and surface area of a sphere from its
# radius given as input.
from math import * # for pi
class Sphere:
def __init__(self, radius): # use double underline on both endes of init
self.radius = radius
def getRadius(self):
return self.radius
def surfaceArea(self):
self.area = 4.0 * pi * self.radius ** 2
return self.area
def volume(self):
self.volume = 4.0 / 3.0 * pi * self.radius ** 3
return self.volume
# main is not part of class, so indent properly
def main():
r = input('Enter the radius of the sphere ')
s = Sphere(r)
print 'The surface area of the sphere is: ', s.surfaceArea()
print 'The volume of the sphere is: ', s.volume()
main()
I commented on the problems, hope you understand them.
I can not quite figure out what you want to do. I wrote these little test files. Test1.py contains a variable I want to use in Testing1.py.
Test1.py:
# test module, save as test1.py
test_path = "test1234"
Testing1.py:
# testing module test1.py
import test1
print test1.test_path
I am thinking this would work like the situation you told. What do you like to change?