jlm699 320 Veteran Poster

is it possible, for example, to make the text that appears as output on the command line appear in a certain colour using python?

Yes. But the answer depends on your platform. In windows you can use the command-line COLOR command. Here's how:

Microsoft Windows XP [Version 5.1.2600]
(C) Copyright 1985-2001 Microsoft Corp.

C:\Documents and Settings\Administrator>COLOR /?
Sets the default console foreground and background colors.

COLOR [attr]

  attr        Specifies color attribute of console output

Color attributes are specified by TWO hex digits -- the first
corresponds to the background; the second the foreground.  Each digit
can be any of the following values:

    0 = Black       8 = Gray
    1 = Blue        9 = Light Blue
    2 = Green       A = Light Green
    3 = Aqua        B = Light Aqua
    4 = Red         C = Light Red
    5 = Purple      D = Light Purple
    6 = Yellow      E = Light Yellow
    7 = White       F = Bright White

If no argument is given, this command restores the color to what it was
when CMD.EXE started.  This value either comes from the current console
window, the /T command line switch or from the DefaultColor registry
value.

The COLOR command sets ERRORLEVEL to 1 if an attempt is made to execute
the COLOR command with a foreground and background color that are the
same.

Example: "COLOR fc" produces light red on bright white

C:\Documents and Settings\Administrator>COLOR 52

I used COLOR 52 to set the background to Purple with the foreground (text) to …

jlm699 320 Veteran Poster

You have a lot of options. If you're looking to purely look at html you can use urllib2, or if you'd rather have the module parse out all the elements for you and give you purely the text data you'd be better off using beautifulsoup. Search this forum to find plenty of examples of using both.

jlm699 320 Veteran Poster

Create an empty list:

my_list = []

Create a list of specified length with all "blank" values:

my_list = [''] * my_length
jlm699 320 Veteran Poster

well you could try this:

user_input = [ 1, 2, 3 ] #all are integers
int_data = [ 1, 2, 3, 4, 5 ] #all are integers
for num in user_input:
    for data in int_data:
        if num == data:
            print data

you have to be careful though if you want to use this in files, :)
hope it helps :)

I think that this may simply be the same thing using different logic:

user_input = [ 1, 2, 3 ] #all are integers
int_data = [ 1, 2, 3, 4, 5 ] #all are integers
for num in user_input:
    if num in int_data:
        print num

And further consolidation gives us this list comprehension:

filtered_data = [data for data in user_input if data in int_data]
jlm699 320 Veteran Poster

Here's some examples of converting between strings, lists, lists of strings, and ints using list , str and int :

>>> usr_inp = '123456'
>>> usr_inp2 = '1,2,3,4,5,6'
>>> list(usr_inp)
['1', '2', '3', '4', '5', '6']
>>> usr_inp2.split(',')
['1', '2', '3', '4', '5', '6']
>>> list(usr_inp)[4]
'5'
>>> int(list(usr_inp)[4])
5
>>> str(int(list(usr_inp)[4]))
'5'
>>>
jlm699 320 Veteran Poster

If you declared the encoding at the beginning of your program the same way that IDLE does, it would have worked I believe?

jlm699 320 Veteran Poster

Try this trick (I'm assuming you're using Windows)

1) Open up a terminal (command prompt window)

Ctrl+R -> cmd -> [Enter]

2) Type/find path to Python executable

dir C:\Py* -> [Enter]
# You should see the folder name for your Python install (I'm guessing it's Python30
C:\Python30\python.exe -> Drag-and-drop your python script to the command prompt window (where you're typing this stuff), which should auto-insert the full path to your python script -> [Enter]

This should get you running your python script inside a persistent window that won't close itself. And example command would be:

C:\> C:\Python25\python.exe "C:\Documents and Settings\Administrator\Desktop\em_test.py"
jlm699 320 Veteran Poster

My advice, get rid of Vista as soon as you can.

And if that's not an option make sure you're both installing and running all these things by right-clicking the executable and selecting "Run as Administrator"

jlm699 320 Veteran Poster

And this what I need to do for the third function:

The third function (call it "sum3") computes and prints the answer using a "while" loop. In some respects the code is similar to the "for" loop of part 2 above. However, unlike a "for" loop, you have to initialize a counting variable, test to see if it is small enough (using the while loop) and if so, execute the loop body. In the body you must increment the counting variable. This function is about 6 lines long.

We can't really do your homework for you, but the basics of a while loop are like this.

some_flag = initial_state
while some_flag (does not meet) my_condition:
    perform action
    update some_flag

So initially some_flag does not meet the desired condition. The loop continually updates the value of some_flag , and when it finally meets the condition that you specify, the loop automatically breaks.

You could alternately simply do a while True: loop (super loop or infinite loop), and then compare the flag to a condition using an if statement. If the flag meets the condition, use break to break out of the super loop.

jlm699 320 Veteran Poster
result = [(key, value)for key in dict.keys(), value in dict.values()]

...

result = [(dict.keys[i], dict.values[i]) for i in range(1, len(dict))]

Just please note that in Python, we use the built-in function dict() to convert certain objects to a dictionary. If you used the above code, you would lose this ability as you're overwriting that built-in function with your list!!

EDIT: Notice how dict is highlighted by the syntax highlighting above like the following built-ins (reserved keywords)

d = {'a':1, 'b':2, 'c':3}
for idx in xrange(15):
    y += my_list[idx]
    if y == 256:
        break
list('123456890')
dict(some_iterable)
jlm699 320 Veteran Poster

You are using the input() function instead of using raw_input().

He also is using parenthesis in his print statements. I'd surmise that he's using Python 3.0, in which case the use of input is the only option. ( input has been replaced by raw_input )

EDIT: Additionally, I tried his code (after modifying it to be Python 2.X compliant) and it worked for the most part. To the OP: could you explain the error in more detail and provide some traceback?

jlm699 320 Veteran Poster
def main():
    print "This program illustrates a chaotic function."
    print "Please enter two numbers between 0 and 1."
    x = input ("Enter first number: ")
    y = input ("Enter second number: ")
    print
    print "input", x, y
    print "-----------------"

    for i in range (8):
        x = 3.9 * x * (1 - x)
    for i in range(8):
        y = 3.9 * y * (1 - y) 
        print x, y

main()

output:

This program illustrates a chaotic function.
Please enter two numbers between 0 and 1.
Enter first number: .25
Enter second number: .25

input 0.25 0.25

0.540417912062 0.73125
0.540417912062 0.76644140625
0.540417912062 0.698135010439
0.540417912062 0.82189581879
0.540417912062 0.570894019197
0.540417912062 0.955398748364
0.540417912062 0.166186721954
0.540417912062 0.540417912062

I'm adding code and quote tags to your stuff so that it's easier for other forum members to read. Please try to make use of these options when posting, as it will greatly increase the likelihood that you'll get satisfactory responses.

To see the different tags I've used in this post, simply "Reply" to the message and look at what I typed. Also, you can use the tool buttons at the top of the editing window to help with generating tags. There's lots of different BB Tags available on this forum, you'd benefit from using them.

--

Now onto your dilemma.

You have print x,y in your second loop only. Loop 1 modifies the value of x. Loop 2 modifies the value of y. …

jlm699 320 Veteran Poster

The beginning of every record looks like this: MSUBUGA JIMSON
P O BOX 21273
GABORONE
(Obviously they are all different, but always have 3 values on 3 lines.)
The end looks like this:
P107.17 P0.00 P225.08 P0.00 P332.25
(The numbers always vary, but there are always 5)

So each record is 4 lines total (with only 3 lines we care about).

Can you give an small snippet of a file with at least two records for example? I envision either simply taking every 4 lines and parsing out the relevant info, or if there is a blank line between each record, just split at the blank lines.

If you read the file in with readlines() , using index slicing you can easily grab groups of lines.

jlm699 320 Veteran Poster

It would be nice if the GUI had color-coded parentheses, to show groupings... or better yet, shading of a similar method...

Why not use one that does then?

I use Notepad++, but I know that even python-specific IDEs like PyScripter have parenthesis highlighting, etc. In fact, PyScripter will have a red underline on any unmatched parenthesis similar to a "spelling error" in a word processing application.

jlm699 320 Veteran Poster

IT was quite helpful. so in case of palindromes how can we remove the symbols and capital letters using .upper and replace function?? for example
"Madam, in Eden I'm Adam!"

Use replace to swap out the punctuation for an empty string (''). Then use upper on both the original and the reversed string when you compare them so that the cases are the same.

jlm699 320 Veteran Poster

Here's my problem. I wx application that works great until I close it (leaving the idle editing session open) and then restart it.

Your real problem is that you're using IDLE.

Your best bet is to switch to a better-featured (not to mention better-designed) IDE and run your scripts directly using python.exe or pythonw.exe

I suggest something like PyScripter or NotePad++ (although with the latter you'll have to do your own personalization to get Python setup and have the ability to syntax check, run scripts, etc.)

jlm699 320 Veteran Poster

anyone plz help me out here

We're not here to do your homework for you. But good job on copy-pasting your assignment.

hi
after reading the specification like 5 times here's what I came up with :)

Dear MasterofPuppets,
You shouldn't be spoon feeding people looking for us to do their homework for them. Even though you provided good code, it doesn't help the OP at all because he's obviously going to just copy-paste your solutions and turn them in exactly in the same manner as he copy-pasted his assignment and posted it here.

jlm699 320 Veteran Poster

How about instead of just generating an arbitrary StaticText object, assign it to a persistent member of your class (let's call it self.login_status_text ). Then instead of generating it each time, simply update the contents to the proper string (It's been years since messing with wxPython but if I remember correctly you might want to use SetLabel in this case).

jlm699 320 Veteran Poster
r.getPos()[:2] = ((100, 200), (700, 800))

pygame.draw.circle takes 5 values:
(screen, color, (x,y), radius, thickness)
... pygame.draw.circle(screen,WHITE,r.getPos()[:2],10) ...
we have screen,
and the color,
r.getPos()[:2] are 2 different (x,y) tuples,
and we have 10 as the last radius or thickness,
...
Strange?

Okay, you've solved your own problem you just don't even realize it yet. The circle function is looking for the values you suggested above. Everything you've provided is correct except the r.getPos() part, which you even identified as being incorrect (r.getPos()[:2] are 2 different (x,y) tuples). Now if you take another peek at the circle parameters it's looking for ONE (x,y) tuple. But you're giving it two, as you yourself noted.

Do you see the problem yet? You need to decide which tuple you want to go with, the first or the second.

I have a feeling the confusion comes from the way you're trying to do your indexing. Here's a little example:

>>> r = ((5,2),(7,3))
>>> r[0]
(5, 2)
>>> r[1]
(7, 3)
>>> r[2]
Traceback (most recent call last):
  File "<input>", line 1, in <module>
IndexError: tuple index out of range
>>> r[:2]
((5, 2), (7, 3))
>>>

In most computer languages, indexing starts from position 0 (zero). This index is the first element. The second element is thus at index 1. The index after the second element is 2; however in our case there is no third element, so when we try to …

jlm699 320 Veteran Poster

oh fudge, i must have changed that by mistake with all my changing of code to try and fix the problem, i definetly had it as getPos before.

I changed it and i got the error that i remember seeing before i must have screwed it up... Progress! haha.

[I]r1.step(r2.getPos()[0],r2.getPos()[1])
TypeError: getPos() takes no arguments (1 given)[/I]

See my above post

jlm699 320 Veteran Poster

Hey All,

I have made a program called "Pymailer", I have even made a GUI version... now what I want to do is to convert it to .exe format... how do I do it? I googled for some info, but in vain!

The same way you create any .exe, using py2exe! Search this forum for examples of setting up a setup file.

jlm699 320 Veteran Poster

If you're looking for native-looking windows apps you'll want to go with wxPython. This is a Python class wrapper for the wx.widgets toolkit, which is cross-platform and extremely powerful.

There's a sticky in this forum with tons of examples of wx code. And here's where you can download the modules, as well as example code and find tutorials.

jlm699 320 Veteran Poster
def getpos():
        r1 = x,y = 100,100
        r2 = x,y = 800,800

i get the error:

[I]Traceback (most recent call last):
    r1.step(r2.getPos()[0],r2.getPos()[1])
AttributeError: r2 instance has no attribute 'getPos'[/I]

I have defined getPos() for both r1 and r2 (my objects), so why do i get that error?
Any one got any clues?

So if getpos() is a function for a class object, then you forgot the most important detail. The parameter self !

Your function should be defined as such:

def getpos(self):
        r1 = x,y = 100,100
        r2 = x,y = 800,800

But then again you're using r1 and r2 inside this function, which may indicate this isn't a class function at all. So in that case, you wouldn't use r2.getPos(), you should just use getPos().

Maybe you should post a little bit more code so that we have some context to go by.

thehivetyrant commented: Very good detail and help +1
jlm699 320 Veteran Poster

I want to convert an integer to a hexadecimal string
examples
lets say i have an integer value 1 i want to convert it to 0001
integer value of 16 => 0010
245 =>00F5
and so on the string must have a length of 4 digits

It will be way simpler to use string formatting like so:

>>> print '%04X' % 16
0010
>>> print '%04X' % 245
00F5
>>> print '%04X' % 1024
0400
>>> print '%04X' % 4096
1000

I'm sure you know already how to use the % symbol in strings to substitute values; however you may only know the basic usage. In this particular example we use a number of properties. First, the 0 denotes that we want our string to be padded with zeroes. Then we have a 4, which indicates we're reserving 4 spaces (if we simply had a 4 without the 0 there would be a blank space instead of a zero). And then finally we have the X. This indicates we're formatting the input (in this case an integer) to print out in hexadecimal. If we had used a lower-case X (ie, x) then the output would use lower-case hexadecimal digits.

HTH

jlm699 320 Veteran Poster

Thanks to anyone who can lend help with this.

You've simply forgotten to put the value of results into the string. Instead you mistakenly typed the name results. Here's how you should use string formatting to add the value:

db.execute("SElECT fname, lname, phone, address, email from contacts WHERE lname = (%s)" % results)

HTH

jlm699 320 Veteran Poster

In the if statement you are using w[i+5].

This means that you need to make sure the maximum i plus 5 does not go out of bounds for the string. Let me demonstrate:

>>> w = 'aabbccdd'
>>> print len(w), len(w) - 5
8 3
>>> range(3)
[0, 1, 2]
>>> print w[0], w[1], w[2], w[3]
a a b b
>>> print w[2+2], w[2+3], w[2+4], w[2+5]
 c c d d
>>> print w[3+5]
Traceback (most recent call last):
  File "<input>", line 1, in <module>
IndexError: string index out of range
>>>

You see that the index of the string can only go up to 7 (the length - 1; and you need to subtract 1 because the first index is 0).

If we try to look at index 8 we get an IndexError. So your code just is making sure we're not breaking the indexing.

HTH

A_Dubbs commented: Thank you +1
jlm699 320 Veteran Poster

You might point out that "if Python is good enough for MIT ..."

Or IBM...

jlm699 320 Veteran Poster

Correct, I use python3.


I deleted the float infront of the input since it was causing the program to bug. But shouldnt I be able to tell python to make all variables that i put in the input to be floats? if not,
how do I make them float nicely?

Basically you have to iterate over your "split" coefficients and then perform float conversion on each one independently. When you split them they return a list, which you'll be doing your iteration on. Here's the steps broken down:

>>> my_coeffs = input('Enter coefficients (a,b,c): ')
Enter coefficients (a,b,c): 3, 5.5, 4.25
>>> coeff_list = my_coeffs.split(',')
>>> coeff_list
['3', ' 5.5', ' 4.25']
>>> # Create an empty list to store our float values
>>> float_list = []
>>> # Iterate over our string coefficients
>>> for each in coeff_list:
...     # turn each one into a float
...     conv_coeff = float(each)
...     # and finally store it
...     float_list.append(conv_coeff)
...     
>>> float_list
[3.0, 5.5, 4.25]
>>>

But thankfully in python you can make it look a little more beautiful than the above using list comprehension:

>>> my_coeffs = raw_input('Enter coefficients (a,b,c): ')
Enter coefficients (a,b,c): 2, 4.5, 5.25
>>> float_list = [float(each) for each in my_coeffs.split(',')]
>>> float_list
[2.0, 4.5, 5.25]
>>>

List comprehension allows us to create a list from another iterable while performing some action (and there's even room for logic). This is a powerful tool that you would probably benefit from learning.

jlm699 320 Veteran Poster

the poorly coded "if x != 1 and x != 2 and x != 3"

Why yes, that is poorly coded. Good thing this is Python!

>>> x != 1 and x != 2 and x != 3
True
>>> x not in [1,2,3]
True

Data validation is extremely important for code that is distributable.
If you're writing scripts for you and only you that will never be used by anybody else than you can skip this; however when you have other users you should consider that they did not sit with you while you designed your program. They might completely miss the concept of what you're trying to achieve. If they provide improper input it is highly likely that your program will crash.

There's also going to be malicious users. These 1337 h4x0rs could intentionally try to either crash the system distributing your code or piggy back through your code into the guts of your system, causing all kinds of havoc.

Just my $0.02

jlm699 320 Veteran Poster

The best beginner's language is Assembly code. It will teach you how amazingly convenient a high level language like Python is.

That is sarcasm, but just read my response to this post in the other forum

jlm699 320 Veteran Poster

Anyone got any ideas?

This should help. Don't ever underestimate the power of documentation.

jlm699 320 Veteran Poster

I don't see any reason why you should skip your high school's C++ classes; however realize that your high school career doesn't really impact your job opportunities as much as your college career.

Learning how to program is more about a set of skills than a particular language. There are entire books about programming without a single line of actual code, rather pseudo code. The principles of coding are the same regardless of the language. Once you learn the basics of programming, you'll be able to use any language after a quick study of its the syntax.

Taking the C++ class will help you learn some good practices for code likely, just make sure you pay attention to your teacher and read your book (don't forget to try the exercises). Just make sure that if you really want to be a programmer you apply yourself and get into college. You can go for Computer Science, Software Engineering or Computer Engineering. Any of those degrees should provide classes to give you good insight into proper code structure, data structures, algorithms and if you're really lucky discrete mathematics.

With the programming tool set that you learn in college, you'll be able to learn any language that you want. And your high school C++ curriculum will probably be covered in the first two days of any college programming course that you take. So don't just stick to what you're learning in-class. Strive to absorb as much as possible and go …

jlm699 320 Veteran Poster

This code has a lot of room for improvement. It would benefit you to read up on classes and functions, as well as PEP 8 (recommended Python coding guidelines).

Maybe you should challenge yourself to improve the style of your coding and make your program more readable. Also it would be interesting if you modularized your code so that you could reuse elements in future games (this would speed up your game development on subsequent titles).

jlm699 320 Veteran Poster

OK. I tested calling one object's methods from another object like so.
...
Must be a bug in my actual program.

Can you explain what the bug is? Each call worked and printed "This is Test2's method."

What was the expected output?

EDIT: I think I understand now. You're saying the real program that you made didn't work but this test script did? If that's the case disregard my above questions

jlm699 320 Veteran Poster

1. So you're saying I'm not going to be using curses ever in my life unless I get a linux?... crap...

Unless you run your script on a compatible platform, you will not be able to experience the joy of curses, no. If you're on windows you can either download and burn a linux live CD to boot from (this doens't require installing linux), or you could install cygwin. This program is basically an emulated version of linux; however it will allow you to at least play around with curses and a few linux commands to get used to it.

2. If you mean IDLE, I'm using IDLE. I think I saw wxpython somewhere in the program files... but we call it IDLE, so... yeah...

No, IDLE is your IDE (environment to develop your code). wxPython is a module that you would import. The packages within wxPython allow you to develop a GUI for an application. wxPython is not included with Python, it's a separate install. Take a look at the sticky thread in this forum for some examples of using wxPython and the results that it can give.

the code itself -should- work.. in fact... I need someone to test that...

It does not work, unfortunately.

I think you may be confused about how curses works. Curses isn't just a library that allows you to play with how stdout is put on the screen, it's almost like an entire platform. There's literally books on how to use it, …

jlm699 320 Veteran Poster

hi,
i want to develop small games using python on mac. so which modules /libraries i have to import . and how to proceed to develop the game... plz tell me.

You'll find it all here. Download pygame, tutorials, code examples, everything.

there's also a number of threads about pygame in this very forum. Just search around a bit and you'll find them.

jlm699 320 Veteran Poster

And when you say compatible platform... uhm... whuh???

The platform can be simplified to mean your operating system. If you load up a python interpreter try the following exercise:

>>> import sys
>>> sys.platform
'win32'
>>> import curses
Traceback (most recent call last):
  File "<input>", line 1, in <module>
  File "C:\Python26\lib\curses\__init__.py", line 15, in <module>
    from _curses import *
ImportError: No module named _curses
>>>

This was done on a windows box. You can see that my platform is win32, which is not a compatible platform for curses (without some type of third-party library, which may not even exist). Now let's try the same thing on a red hat box:

>>> import sys
>>> sys.platform
'linux2'
>>> import curses
>>>

Now on red hat linux (a unix-based OS, which is compatible with curses) the import works just fine.

Uhm... wait, difference between wxpython and python are what?...
.... crap, now I'm so confused...

wxPython is a GUI framework build around the wx.Windows library, which is used to build application GUIs. It's basically a module that you can import into your python programs that opens up a whole new world of options for you when designing your programs. You can find the wx website here, and there's a bajillion code examples of different GUI elements in this thread here (you'll find it as a sticky at the top of this Python forum).

Hope that you find something that works for you. Good luck!

jlm699 320 Veteran Poster

No, wait, I'm an idiot :)

It's x = Stuff(), not x = Stuff of course. Meh.

You're not an idiot, you're learning! It's good that you've solved your own problem. I actually just read an article about how a programming instructor put a teddy bear on his desk.

When students came in to ask questions about their assignments he'd ask them to ask the question to the teddy bear. The instructor would happily ignore the student and do his own work while the pupil explained their problem to the teddy bear.

Almost 9 times out of 10, the student would have an "Ah ha!" moment and solve their own problem after hearing it out loud. Seems like sometimes the best way to find an answer is to ask ourselves the very question that we are trying to solve!

Anyway, hope you're getting along just fine with Python. Be sure to stop back and post another question in this forum if you hit any snags. We're here to help!

jlm699 320 Veteran Poster

dint work anyway what code should i write to open the pygame window
is it import pygame?

What "dint work"?

jlm699 320 Veteran Poster

Gribouillis

I'm not sure if this has been fixed or not (perhaps you're using a newer version of Python where this bug has been eliminated) but when I use your path.join this is what I get:

>>> from os.path import join as pjoin
>>> pjoin("C:", "foo", "bar", "baz")
'C:foo\\bar\\baz'
>>>

This is in Python 2.6.2 and has always been this way. I'm not sure why, but I've always found that when using a drive letter in windows you always have to explicitly add backslashes like this:

>>> from os.path import join as pjoin
>>> pjoin("C:\\", "foo", "bar", "baz")
'C:\\foo\\bar\\baz'
>>>
jlm699 320 Veteran Poster

You're likely getting an exception. When an exception is raised, the program quits.

The best way to catch the traceback is to open your own command prompt and run the program that way.

Go to Start -> Run... and enter cmd and press Enter.

This opens a windows command prompt. Now the program you're running is Python, so you'll need to type in the path to your python executable. This is likely going to be C:\PythonXX\python.exe with the XX being your python version. So for Python 2.6 it would be C:\Python26\python.exe . Now at this point you'll need a space and then the path to your python script that you're trying to run. The easiest and quickest way to do this part is to just drag and drop the icon representing your file into the command window. This will automatically insert the full path to your script.

Finally just press, Enter to have Python run your script and you should see the traceback printed to the screen. Your next step will be to debug and fix the error! Good luck! Paste your traceback here if you don't understand it and we can try to help.

jlm699 320 Veteran Poster

... It won't even import curses.

That's because curses isn't available for Windows. The documentation should probably specifically say that, but they actually just tip-toe around that fact:

The curses module provides an interface to the curses library, the de-facto standard for portable advanced terminal handling.

While curses is most widely used in the Unix environment, versions are available for DOS, OS/2, and possibly other systems as well. This extension module is designed to match the API of ncurses, an open-source curses library hosted on Linux and the BSD variants of Unix.

[Source = PyDocs]

Is your instructor asking you to use curses? Or are you just doing it to be snazzy?

If you're really insistent on using it you'll need to use either unix or dos or some other compatible platform.

jlm699 320 Veteran Poster

It would be easier for us to help if you gave us just the barebones code that produces this abnormality. Most users won't have every single one of those modules and it would be cumbersome to traverse around to find and install them all.

Are you able to see your matplotlib frame inside the wx App? What specific action gives you the "Aborted" message. And what exactly is the "Aborted" message? Is it a pop-up? Is it text inside one of the panels on your application window?

Please provide some more details.

jlm699 320 Veteran Poster

though i'm calling pr() function in the subclass after calling the get_details() function(which assigns value to name) it doesn't print the current value of name.

Actually, it is printing the current value of name. The employee.name is always a space (' '), because you never change it. In your get_details function, you have created a new variable called name and assigned the users' input to it. Why don't you try printing x.name after your call to x.get_details()? You'll see that x.name is still just a blank space. The problem is that then name object that you're creating inside get_details only exists inside the scope of that function. You should be using self.name, which is the persistent attribute of the employee class. Let me demonstrate this principle:

>>> class no_init(object):
...     name = 'I have no init function'
...     def print_name(self):
...         name = input('Input some name: ')
...         print('self.name', self.name)
...         print('name', name)
...     
>>> ni = no_init()
>>> ni.print_name()
Input some name: Testing
self.name I have no init function
name Testing
>>> ni.name
'I have no init function'

As you can see, the name attribute is always "I have no init function" even though there is a " name " inside my print_name function. This is because that particular object is created and destroyed inside that function only. To refer to an attribute of a class from inside the class declaration you need to use self. , whereas outside the class you use the …

python.noob commented: Simply awesome +0
jlm699 320 Veteran Poster

The print row command outputs:


I want 'test' to go into Category and 'one' to go into Value.

In that case you'll want this:

c.execute("INSERT INTO a (Category, Value) VALUES (%s, %s)", tuple(row[0].split()))

Basically this takes the element [0], which represents that string 'test one', and then splits it (the default split delimiter is a space), so it turns it into . Finally, you just need to turn it into a tuple.

When doing string formatting, you need to have a tuple containing each argument for string formatting as an element. Here's an example of a string formatting requiring two arguments:

>>> print 'Hey %s totally %s check' % ('test', 'one')
Hey test totally one check
>>>

As you can see, I need two things to fill into the %s pieces. The two elements in the tuple satisfy this requirement.

Here's the transformation from "row" to the tuple required in broken down steps:

>>> row = ['test one']
>>> row[0]
'test one'
>>> row[0].split()
['test', 'one']
>>> tuple(row[0].split())
('test', 'one')
>>>
Shadow-Illusion commented: Solved problem well +0
jlm699 320 Veteran Poster

According to your explanation:

def step(x,y):
    pass

If you need something else you'll need to explain what you're trying to do and give some context. If you really want some code written for you you'll need to provide some code for us to work from. We can't just automagically write your programs for you.

jlm699 320 Veteran Poster

You should uncomment your commit statement. You need to commit your transactions before they go through.

jlm699 320 Veteran Poster
jlm699 320 Veteran Poster

Alternately you could use modulus division like this:

>>> f = 123.456
>>> ipart = int(f)
>>> fpart = f % 1
>>> ipart
123
>>> fpart
0.45600000000000307
>>>
jlm699 320 Veteran Poster

To do it the way you're trying to do it, use this:

>>> num = 0
>>> mylist = []
>>> 
>>> while num < 10:
...     num += 1
...     mylist += [num]
...     
>>> for item in mylist:
...     print item
...     
1
2
3
4
5
6
7
8
9
10
>>>

Notice I put brackets around num since you have to add a list to a list when using the + operator. Other methods would be to use mylist.append(num) or mylist.insert(index, num) . I also changed your x = x + y statements to x += y , which is identical.

HTH