lllllIllIlllI 178 Veteran Poster

Showing images is easy with wx.StaticBitmap.
http://www.wxpython.org/docs/api/wx.StaticBitmap-class.html

NOTE:This code is borrowed from the sticky

# show  .jpg .png .bmp or .gif image on wx.Panel

import wx

class ImagePanel(wx.Panel):
  """ create the panel and put image on it """
  def __init__(self, parent, id):
    # create the panel, this will be self
    wx.Panel.__init__(self, parent, id)
    try:
        # pick your image file you have in the working folder
        # or use the full file path
        image_file = 'strawberry.jpg'
        bmp = wx.Bitmap(image_file)
        # show the bitmap, image's upper left corner anchors
        # at panel coordinates (5, 5), default is center
        wx.StaticBitmap(self, -1, bmp, (5, 5))
        # show some image information
        info = "%s  %dx%d" % (image_file, bmp.GetWidth(), bmp.GetHeight())
        # the parent is the frame 
        parent.SetTitle(info)
    except IOError:
        print "Image file %s not found" % imageFile
        raise SystemExit


# redirect=False sends stdout/stderr to the console window
# redirect=True sends stdout/stderr to a wx popup window (default) 
app = wx.App(redirect=False)
# create window/frame, no parent, -1 is the default ID
# also increase the size of the frame for larger images
frame = wx.Frame(None, -1, size = (480, 320))
# create the panel instance
imp = ImagePanel(frame, -1)
# show the frame
frame.Show(True)
# start the GUI event loop
app.MainLoop()

Hope that helps

lllllIllIlllI 178 Veteran Poster

Yeah they do, but what i do is usually find out what i need to use with the demo. Fiddle around a little bit with the declaration of the object i am using just to get a little used to it. Then i look at the api, i find that is the best learning tool for wxPython, you just have to try a little sometimes. :)

lllllIllIlllI 178 Veteran Poster

I suggest downloading the 'Docs and Demos' along with your wxPython install, as it gives you a great launch pad to start writing your own GUIs by giving you sample code of almost every single type of wx object.

It's ridiculously helpful when starting wxPython.

That is in fact a great idea, that and the api are powerful learning tools.

lllllIllIlllI 178 Veteran Poster

Okay, thats simple enough. What you would be looking at is using wx.StaticText for all of your displaying text needs.
http://www.wxpython.org/docs/api/wx.StaticText-class.html
This you can update with the SetValue("Value") function.

If you ever need user input you can use wx.Button
http://www.wxpython.org/docs/api/wx.Button-class.html

Or a wx.TextCtrl, this is basically like an input box. Kinda like the one you type your forum responses into.
You can get its data by using the GetValue() function
http://www.wxpython.org/docs/api/wx.TextCtrl-class.html

Hope that helps you on your way :)

lllllIllIlllI 178 Veteran Poster

The second one is a simple funciton

#our list
l = ['Hello','world','from','python']

#use the join() function to join the words together with spaces
string_list = ' '.join(l)
print string_list
#prints
#Hello world from python

Im pretty sure that changed for python 30. Im not how you do it there

lllllIllIlllI 178 Veteran Poster

To get the average i usually make a function

import random

def averageList(l):
    total = 0 
    for item in l:
        total += item
    return total/len(l)

#then i make my list
l = [random.rangrange(0,100) for f in range(100)]
print averageList(l)

Functions are a great way to reuse your code if you ever need to.

Hope that helps :)

lllllIllIlllI 178 Veteran Poster

Okay, start simple and understand what raw_input and input actually do:

raw_input([prompt])¶

If the prompt argument is present, it is written to standard output without a trailing newline. The function then reads a line from input, converts it to a string (stripping a trailing newline), and returns that. When EOF is read, EOFError is raised. Example:

>>> s = raw_input('--> ')
--> Monty Python's Flying Circus
>>> s
"Monty Python's Flying Circus"

If the readline module was loaded, then raw_input() will use it to provide elaborate line editing and history features.

Then understand lists:
http://docs.python.org/tutorial/datastructures.html

And then have another go at the problem, if you have any specific questions feel free to ask. But first try learn a bit more about what things do.

lllllIllIlllI 178 Veteran Poster

oh ok my bad but i still cant get it to work

Well show us your changed code so we can have a look at it then.

lllllIllIlllI 178 Veteran Poster

You can also request a free ubuntu CD be shipped to you, no shipping fees or anything. I used to use that when i had dialup internet :).

https://shipit.ubuntu.com/

Hope that helps!

lllllIllIlllI 178 Veteran Poster

I did something exactly like this when learning python. I would get the rain radar and the forecast for numerous places. The way i did this was i would download an image from the Bureau of Meteorology in Australia, then i would download the webpage with my forecast on it, scrape away all the tags and then i would get the text i wanted from that.

So www.bom.gov.au works if your in Australia. Not sure about other places, but im sure that there would be something readily available.

lllllIllIlllI 178 Veteran Poster

PS. What's the Python code tag? When I call (code=python) I don't get the formating or syntax highlighting.

Yeah thats an issue right now. http://daniweb.com/forums/thread189444.html

lllllIllIlllI 178 Veteran Poster

But there also is the GUI Synaptic Package Manager on Ubuntu, thats really nice to start with, it gets all of the dependencies. It is search-able and categorised.
You find it in System -> Administration -> Synaptic Package Manager

Thats what i use if i cant find it with the aptitude search. :)

Hope that helps

lllllIllIlllI 178 Veteran Poster

Yeah i used to get that a lot with IDLE. I did the same thing i outlined above and that fixes that problem for me. Hopefully it works for someone else as well!

lllllIllIlllI 178 Veteran Poster

Just search this website, we have loads of threads on the pros and cons of many other IDE's and im with Jlm. IDLE isnt good enough when programs get complicated. Its best to try something else.

lllllIllIlllI 178 Veteran Poster

Usually this is fixed pretty easily. Shut down all IDLE's open, and any other programs that could be using python. Then you proceed to the task manager (CTRL+ALT+DEL) and go to the processes tab.

End any processes that have python.exe or pythonw.exe

Once that is all done, try restarting IDLE

Hope that helps

lllllIllIlllI 178 Veteran Poster

could you post there error you are getting?

oh and instead of

xy=(1,1)
xy=list(xy)

You can just go

xy = [1,1]

And then it is a list already

lllllIllIlllI 178 Veteran Poster

Yeah shadwickman. I have a funny feeling that it is not python. I get a clue from the *endif and stuff like that...

lllllIllIlllI 178 Veteran Poster

Yeah i got a Dell inspron mini 9. One of the netbooks and it runs linux so well. I spent ages getting confused about how to install applications until about a week later i found the add/remove programs item. Woops!

But i love its speed and its community. Hope you have fun with ubuntu! :)

lllllIllIlllI 178 Veteran Poster

Im pretty sure that using the Image module is unnessicary for that. I think you can just use os and go:

import os
os.startfile("image.jpg")

Yep, just checked, it works perfectly on my computer.

lllllIllIlllI 178 Veteran Poster

Yeah i spent about 3 weeks a while ago trying to work out pyGL but there was absolutely no documentation or tutorials to do so i was stuck and there really was no way for me to learn. IMHO i think you should probably use something like VPython or another language.

lllllIllIlllI 178 Veteran Poster

Ah just a simple misunderstanding. Firstly you can do it this way

n = input("Enter your number: ")
print(n+2)

But that wont work with python 30. Also in python 2.x people dont usually like the input() function as it evaluates the input. So if i typed 2*7 it would return 14 rather than just an 2 or 7. So what we use it

n = int(raw_input("enter your number: "))

But to make it work with python 30 we need to remember that with python 30 the input statement now is like the python 2.x raw_input statement so we can go:

n = int(input("Enter your number: "))
print (n+2)

Hope that solves your problem! :)

lllllIllIlllI 178 Veteran Poster

Yeah, i know what you mean scru. I was using this because of the relatively simple lists. But thanks for the heads up. I love learning of new modules :)

lllllIllIlllI 178 Veteran Poster

Oh i did exactly the same exercise myself when learning about lists, what you need to know here is about the "in" keyword. It is used to check if "a in b" so what we can do is check if item a is in list b. If it is then we have a match. Get it? I hope so. If not here is an example:

def getMatches(first, second):
    count = 0
    for item in first:
        if item in second:
            count += 1
    return count
            

list1 = ['spam', 'eggs', 'bacon',"ham"]
list2 = ['spam', 'ham', 'king richard']

print "there are ",getMatches(list1, list2)," matches"

Hope that helps you on your way!
:)

lllllIllIlllI 178 Veteran Poster

Try using the absolute path, such as
"C:\\Documents and Settings\\Paul\\Desktop\\Programming\\Excel\\values.xls"

Remember that the double backslash is used so there are no escape characters such as \n used accidentally. There is a way to get around that and that is putting an r in front of the first " sign. That formats it into a raw string and escape characters are ignored.

lllllIllIlllI 178 Veteran Poster

Yeah you can do open internet things with the webbrowser module.
Oh and also execfile is good if you want to start executables or python files.

>>> import webbrowser
>>> webbrowser.open("www.google.com")

And execfile

#its a built in!
execfile("Path \\ to\\ exe or py \\ file.exe")

Hope that helps

lllllIllIlllI 178 Veteran Poster

If you just re-installed python you might have installed python 30 which means that you now have to go

print("hello")

See if that fixes it. :)

lllllIllIlllI 178 Veteran Poster

Hmm i think i see what you are doing, personally what i would do is make a python program that made an actor and then pickled it rather then using what you are doing, that way you could unpickle it in the actor class and everything would be fine and dandy.

But its all up to you, i think its going to be quite hard that way.... unless you want to use something like eval() to make a dictionary.. that might just work..

lllllIllIlllI 178 Veteran Poster

Well give us a look at an example file that you are using. That will help greatly.

lllllIllIlllI 178 Veteran Poster

I had the answer for this an hour ago but suddenly the site stopped responding. For this problem you have to split the string into bits and the count the amount of bits.. that sounds really bad.. here is some code that demonstrates this

def Digit(line):
    line = line[line.rindex("J")+1:]
    line = line.split()[0]
    line = line.split(',')
    return len(line)

Digit("28 J=5202,5204,7497,7498 SEC=WALL1")
#output 3

What this does is it first takes off all the line after the = sign and makes line equal that then we split it by the spaces and get the first bit of that. Then we are only left with the "234,14,21" bit (i just made up those numbers). Then we just split it by the comma and count the amount of things in the list and return that value. It should word every time. If it dosent it should be just a simple coding error, i havent actually tested the code :P

lllllIllIlllI 178 Veteran Poster

Umm.. i would edit those passwords there. Just asterisk them or something.

lllllIllIlllI 178 Veteran Poster

You can read the text file word by word! :)

d = {'flight':[]}
f = #text file
for line in f:
    for word in line.split():
        if word == what_you_want:
            d['flight'].append(word)

Hows that? Im a bit confused by exactly what you want but that will read a text file by each word. Replace the if statement with your own one that does something more relevant.

lllllIllIlllI 178 Veteran Poster

I think this is what your code needs to look like

def main():
    print (" PC : Hi there.whats your name?")
    userit = raw_input (" user :")
    print (" Pc : Nice to meet you " ) , userit ,
    userit = raw_input(" Do you like python? (A=Its Great, B=Its Ok, C=Its Rotten)")
    if userit == A:
        userit = userit.upper()
        print ("\n Thats good. I like it too ") ,userit ,

    elif userit = B:
        userit = userit.upper()
        print ("\n really what ever you say ") ,userit ,
    elif userit = C:
        userit = userit.upper()
        print ("\n Thats bad ") ,userit ,
    else:
        print ("\n Please enter from the Above options ") ,userit

    usergame = raw_input(" whats your rating in tennis? (A=best, B=better, C=better)")
    if usergame == A:
        usergame = userit.upper()
        print ("\n wonderful i think you must compete federer ") ,userit ,
    elif usergame = B:
        usergame = userit.upper()
        print ("\n good to play with me ") ,userit ,
    elif usergame = C:
        usergame = userit.upper()
        print ("\n need more learn the game ") ,userit ,
    else:
        print ("\n Please enter from the Above options ") ,userit

    userpl = raw_input(" which country do you like the most? (A=united states, B=Dubai, C=england)")
    if userpl == A:
        userpl = userit.upper()
        print ("\n nice place to live ") ,userit ,
    elif userpl = B:
        userpl = userit.upper()
        print ("\n Too expensive ") ,userit ,
    elif userpl = C:
        userpl = userit.upper()
        print ("\n good choice ") ,userit ,
    else:
        print ("\n …
lllllIllIlllI 178 Veteran Poster

What that means is that the indentation level is not correct, this is best explained by examples:

if True:
    print "this"
  print "That"  ##Error!! The indentation is not standard

if True:
print "this"  ##Error!! No indentation

if True:
    print "This"
        print "That"#Error, indentation not correct.

if True:
    print "This" #works Fine!! Yay

All you have to do is clean up your indentation, if you are not using an IDE i would recommend starting, they really help with indentation! :)

lllllIllIlllI 178 Veteran Poster

It checks to see if l is existant, if there are no elelments in l then it will return False because your key cant be in an empty list! Therefore avoiding any unwanted Exceptions! :)

lllllIllIlllI 178 Veteran Poster

Well i could be a bit biased, i am very much a wxPython guy, i love it, its a smart, easy to use GUI. Oh and also, wxPython is cross platform

People tend to not use Tkinter, as it is not that powerful and does not have that many things going for it.

If you know GTK then there really would be no hard in using pyGTK, but i have found with switching between wxWidgets and wxPython that there isnt that much that is actually the same apart from what is looks like. The general things will stay the same, such as widgets and such, but the code style will be different.

siddhant3s commented: Thank You +3
lllllIllIlllI 178 Veteran Poster

I would say after reading Dive into Python is probably all you need in the way of a book, because in the end after you know all that book has to offer you will know practically all that you need to just muck around with python.

If you are looking for GUI's and books/tutorials for that then i would reccomend zetcode.com, it has a great wxPython tutorial.
Personally wxPython is my favourite GUI in python, if you have used Qt then there is pyQt if you are familliar with that.

There is a thread on this forum about learning wxPython as well if you need some extra tips. I would reccomend getting a full understanding of python before starting GUI's but it is a lot lot lot lot simpler then C++ guis! :)

lllllIllIlllI 178 Veteran Poster

Personally i would definitely go for Dive Into Python, it is a long and very comprehensive book. I went back to one of its chapters just the other day to read up on unit testing and found it to be a great help.

Seeing you already know C++ the migration to python will be most likely quick and easy.

lllllIllIlllI 178 Veteran Poster

If you want to make python into an executable file, thats easy with py2exe!
http://www.py2exe.org/

I started learning C++ as my first language a couple of years ago but was almost killed by the amount of syntax i didnt understand, so i started python instead. Its easy, simple and great fun. I still use C++ today (as you would know, been posting on C++ forum) but not as much as python. I really only use C++ for things i cant do in python, because at the end of the day, python is easier and great fun!

lllllIllIlllI 178 Veteran Poster

Okay so here is some working code. Make sure you can understand everything in it, if you dont ask questions make sure you can understand why things are the way there are:

import random



def chance():
    
    number = raw_input("How many random numbers do you want?: ")
    l = []
    for each in range(int(number)):
        n = random.randrange(100)+1
        l.append(n)
    return l
        
def extreme(x):
    z = x + 5
    y = z - 3
    return z, y

    
#main
repeat = 0
while repeat != 2:

    x = input("Enter a value for x: ")
    z, y = extreme(x)
    print x,"+ 5 =",z
    print z,"- 2 =",y

    for f in chance():
        print f
    

    repeat=input("Do you want to go again? Yes [1] or no [2]: ")

raw_input("Press Enter to exit!")
lllllIllIlllI 178 Veteran Poster

What about the number variable, i cant find where it is made:

import random

def chance(number):
    number = input
    for each in xrange(number):
        n = random.randrange(100)+1
        return n

def extreme(x):
    z = x + 5
    y = z - 3
    return z, y

    
#main
repeat = 0
while repeat != 2:
    x = input("Enter a value for x: ")

    z, y = extreme(x)
    print x," + 5 = ",z
    print z," - 2 = ",y

    n = chance(number)   #<--------- Where is number made
    input = raw_input("How many random numbers do you want?: ")
    #also never use the word input as a word, otherwise when you call input() again it will not work. Use a different variable name
    print n

    repeat=input("Do you want to go again? Yes [1] or no [1]: ")

raw_input("Press Enter to exit!")
lllllIllIlllI 178 Veteran Poster

You can return it like this:

def returnTwoThings():
    return 1,2

a,b = returnTwoThings()
print a 
print b
#output
#1
#2
lllllIllIlllI 178 Veteran Poster

Use a try, except statement:

import os, sys

folder = os.path.abs("pathtoscriptsfolder")
sys.path.append(folder)

for script in os.listdir(folder):
    if script.endswith(".py"):
        try:
            mod = __import__(script)
            res = mod.run_test()
        
            fh = open("tests.res", "a")
            fh.writeline(str(res))
        except TypeOfErrorHere:
            print "Test case didnt work... continuing"

I hope that helps

lllllIllIlllI 178 Veteran Poster

Here is a site where they do just what you are doing, the first bit talks about unit testing, just ignore that and keep going on, it shows you how to make a roman numeral converter that is almost impossible to break:
http://www.diveintopython.org/unit_testing/index.html

lllllIllIlllI 178 Veteran Poster

Well if you want them to all be in a different category then you have to get a new number each time. Also you can use random.choice() to get a random choice from a list.

Here is what i would do

import random

house = ["a mansion", "an apartment", "a shack", "a house"]
spouse = ["name1", "name2", "name3", "name4"]
car = ["car1", "car2", "car3", "car4"]
kids = ["no kids", "1 kid", "2 kids", "5 kids"]

print"List 3 people you want to marry in the future:"
spouse[0] = raw_input("1. ")
spouse[1] = raw_input("2. ")
spouse[2] = raw_input("3. ")

print"List 1 person who you don't like: "
spouse[3] = raw_input("1. ")

print"List 3 cars you want in the future:"
car[0] = raw_input("1. ")
car[1] = raw_input("2. ")
car[2] = raw_input("3. ")

print"List 1 car that you don't like: "
car[3] = raw_input("1. ")


#main
while True:
    raw_input("Now mashing... Press [enter] for your results")
    print "You will live in",random.choice(house)
    print "Married to",random.choice(spouse)
    print "Driving a",random.choice(car)
    print "With",random.choice(kids),"running around the house"
    choice = raw_input("Do you want a second chance? Type [n] to quit. ")
    if"n"in choice:
        break

raw_input("Press [Enter] to exit.")
lllllIllIlllI 178 Veteran Poster

Well i think your first problem is here:

w = input(random.randrange(100)+)

input is a built in function that only needs a string and gets input from the user. There are a few other things that dont work in your program, like print w*random will just times w by random and give back one number, here is a sample of what i think you mean to do

import random

exit = False
while not exit:
    nums = input("how many numbers?")
    for f in range(nums):
        print random.randrange(0,100),

That will give you the amount of numbers you want, ill leave the exiting for you to figure out.

But do you see how this works?
I get the user input of how many random numbers and then i loop through that many times and print out a random number between zero and one hundred. Then that gets printed out.

lllllIllIlllI 178 Veteran Poster

Well on the forums remember to use code tags

[code]

code here

[/code]
But here is the code you have

def count(sub, s):
    """
    >>> count('is', 'Mississippi')
    3
    >>> count('an', 'banana')
    3
    >>> count('ana', 'banana')
    3
    >>> count('nana', 'banana')
    3
    >>> count('nanan', 'banana')
    3
    """
    count = 0
    if sub in s:
        count += 1
    print count


if __name__ == '__main__':
    import doctest
    doctest.testmod()

There are a few problem is see with your doc. Firstly this one:
>>> count('ana', 'banana')
2
there is only ONE ana in banana, the other one is a cross over of it, so in that case you should have
>>> count('ana', 'banana')
1
as your docstring.


Also your function is wrong, it will only ever get one as a return value at max, that is because an if statement executes and then goes on.
This seems like a more relevant function.

def count(string, sub):
    return string.count(sub)

See how that goes, and ill help out if there is something still wrong with it.

lllllIllIlllI 178 Veteran Poster

Just a thought, i cant see how it breaks out of the loop, so maybe move the other raw_input() in a bit:

# -*- coding: iso-8859-15 -*-
# check encoding in http://www.python.org/dev/peps/pep-0263/

def function1():
    print "Bonjour, comment allez-vous ?"

def function2():
    print "Hola, cómo esta usted?"

def function3():
    print "Hello, hoe zijn u?"

def function4():
    print "Hallo, wie geht es Ihnen?"

#main

print "Hello, how are you?"

while True:
    choice = raw_input("Enter a language (french, spanish, greek, german): ")
    if choice == "french":
         function1()
    elif choice == "spanish":
         function2()
    elif choice == "greek":
         function3()
    elif choice == "german":
         function4()
    else:
         print "You have to choose from french, spanish, greek or german!"

    if raw_input("\n\nPress the enter key to exit.") == '':
        break
lllllIllIlllI 178 Veteran Poster

Just a thought, i cant see how it breaks out of the loop, so maybe move the other raw_input() in a bit:

# -*- coding: iso-8859-15 -*-
# check encoding in http://www.python.org/dev/peps/pep-0263/

def function1():
    print "Bonjour, comment allez-vous ?"

def function2():
    print "Hola, cómo esta usted?"

def function3():
    print "Hello, hoe zijn u?"

def function4():
    print "Hallo, wie geht es Ihnen?"

#main

print "Hello, how are you?"

while True:
    choice = raw_input("Enter a language (french, spanish, greek, german): ")
    if choice == "french":
         function1()
    elif choice == "spanish":
         function2()
    elif choice == "greek":
         function3()
    elif choice == "german":
         function4()
    else:
         print "You have to choose from french, spanish, greek or german!"

    if raw_input("\n\nPress the enter key to exit.") == '':
        break
lllllIllIlllI 178 Veteran Poster

there is a really quick way to get a list of even numbers:

list_of_evens= [f for f in range(1,500) if f%2==0]

that should give all the even numbers from 1 to 500 in a list

scru commented: Actually it's one to 499, but I agree that a list omprehension is the easiest route. +5
lllllIllIlllI 178 Veteran Poster

just mark it as solved.