If I want to convert one type in another, I can use casts:

s = str(12.5)
i = int(s)
f = float(s)

However, there doesn't seem to be a function cast, or even a statement cast. So how can I turn this string into a statement?

s = """for i in range(v):
    print v - i,

Thanks in advance for any answers.

Recommended Answers

All 5 Replies

I found the answer through another Python forum. There isn't a native cast in Python, but there are conversion functions, although not for function. To convert a string into a function, you need to execute it, using the exec function:

s = """
def countdown(val)
    for i in range(val):
        print val - i,


countdown(10) # --> 10 9 8 7 6 5 4 3 2 1


Thanks for letting us know, this fits our beginner circle well.
Don't know how we lost that colon after def countdown(val)?

Oops, how could I have missed that? I should have run that code before publishing.

just out of curiosity, what operating system are you using?

Mac OS X Panther (10.3.9), with Python 2.4.2 from ActiveState.

I also have an offline Toshiba notebook (640 x 480) running Windows 98SE with the Unofficial Service Pack, with Python 2.4.2 from ActiveState. The PC is only for testing purposes.

I'm looking for a good Linux Distro for Python testing. Do you know what the most popular Linux Distros are and if they run comfortably on a AMD Mobile K6-2 (475 Mhz) with 192 MB internally, 6 GB harddisk and IDE 16X CD-ROM player?

While I'm writing this, I'm downloading Slax, which seems to run a such an "ancient" PC with relative ease. I have tried another Live-CD, which was miserably slow and actually had quite a high system requirement, almost as high as Windows XP :confused:

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.