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

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

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

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

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
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

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 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

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

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

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

Or what about using chr() and then just adding 65?:

>>> def numtolet(num):
...     return chr(num + 65)
...     
>>> numtolet(1)
'B'
>>> numtolet(12)
'M'
>>> numtolet(14)
'O'
>>>

Or the reverse:

>>> def lettonum(let):
...     return ord(let) - 65
...     
>>> lettonum('O')
14
>>> lettonum('A')
0
>>> lettonum('N')
13
>>>
jlm699 320 Veteran Poster

Is there a way to use a string to call a previously named variable?

Eval is what you're looking for:

>>> sports = [1,23,4]
>>> eval( 'sports' )
[1, 23, 4]
>>>
jlm699 320 Veteran Poster

I don't really get what you mean by initially setting a boolean variable to false before the loop.

Like this: my_boolean = False . Now the variable named my_boolean will act as your "flag" to tell you whether a number is "lucky" or not.

Also for the for loop, should I get rid of it? Because if I enter 007, it will print the statements 3 times and I only want it to print once.

Here's what I posted above, maybe you didn't read it last time:

The rest will work except that it will print a message on every character that is evaluated. You should be using a boolean variable that is initially set to false before your loop. If the number 7 is found, change it (the boolean) to True, otherwise do nothing. [EDIT: Meaning this should be the only logic in your for loop. Take everything else out]

After the loop has completed, check if your boolean is true; if so, print the lucky message or otherwise print unlucky.

HTH

jlm699 320 Veteran Poster

This is a very hacked solution but:

>>> sports = ## Defined as above - snipped for length
>>> def build_html(chosenCategory):
...     up_locals = sys._getframe(1).f_locals
...     for each_var in up_locals:
...         if id(up_locals[each_var]) == id(chosenCategory):
...             var_name = each_var
...     filename = '%s.html' % (var_name)
...     print filename
...     
>>> build_html(sports)
sports.html
>>>

You could even be brazen and shorten that for loop to a single list comprehension (albeit a very long one):

def build_html(chosenCategory):
    var_name = [each_var for each_var in sys._getframe(1).f_locals if id(sys._getframe(1).f_locals[each_var]) == id(chosenCategory)][0]
    filename = '%s.html' % (var_name)
    print filename
vegaseat commented: actually a good hack +9
qadsia commented: Very Helpful! solved my problem. +0
jlm699 320 Veteran Poster

I never learned the "in" function yet. What if I wanted to use the index code in my code? Like the lucky, is there a way to do it? I haven't learned much about python yet, so I wanted to see if I can use what I've learned to finish this code first.

(learned the index, for loops, while loops and if statement)
Thanks.

You should remove the parenthesis from around your input statement. so it should just be: lucky = raw_input("Enter an integer: ") The rest will work except that it will print a message on every character that is evaluated. You should be using a boolean variable that is initially set to false before your loop. If the number 7 is found, change it to True, otherwise do nothing.

After the loop has completed, if your boolean is true, print the lucky message; otherwise print unlucky.

HTH

jlm699 320 Veteran Poster

I saw it mentioned somewhere on the web that you need to import PyQT4 instead of PyQt4 .

Note the Capital 'T'

jlm699 320 Veteran Poster

thanks a lot man,
there is just one problem, my version of ubuntu does not support any version of python higher than 2.5. awww well. at least i know now to stop trying to get this one to work and start a new project witch might work.

That's not entirely true. You can use the Synaptec Package Manager to download the latest versions of Python. FYI.

jlm699 320 Veteran Poster

I will have to google the changes.

Here you go: http://docs.python.org/dev/3.0/whatsnew/3.0.html

This gives a nice breakdown of the changes between 2.X and 3.X versions of Python. Hope it helps!

jlm699 320 Veteran Poster

the progress bar only shows 100% and doesn't progress at all..

A progress bar is only useful if you're actually progressing through something. The steps that happen before you send the 100% to the progress bar are like going so fast that you can't see the "progress" of your function.

Also, to call a function you need to use parenthesis. None of your calls to progress_timeout are actually running. All you're doing is getting is the reference to that object on stdout. Reading through that function I'm not sure you should even be calling it at all though. But that's for you to discover.

Additionally, you should really use a function to do the progress updates since you have so much repeat code, it will cut down on the clutter and make it easier to read what this function does:

def set_progress(self, percent):
        ''' Sets the text, fraction and then calls progress_timeout
        @ Inputs
        - percent    Floating point representing the progress percent
        '''

        self.pbar.set_text('%i%%' % progress)
        self.pbar.set_fraction(progress)
        self.progress_timeout(self)
        return

Then each of your "updates" for the progress bar should be called as self.set_progress(0.1) . But the problem of executing code quickly before seeing progress still exists... You could add time.sleep(1) to the function so that after each update the program hangs for 1 second.

EDIT: I also have to re-iterate that I REALLY don't think you should be trying to call progress_timeout.

jlm699 320 Veteran Poster

Mensa: your code was very well structured and a nice example of reading user input then using it for calculation. Here's how I've modified your code:

def calc_payment(int_rate, num_pmnts, principal, freq):
    ''' This function will calculate the payment amount of a loan.
    @ Inputs
    - int_rate  - The interest rate of the loan
    - num_pmnts - The number of payments required
    - principal - The original amount of the loan (minus down-payment)
    - freq      - Frequency of payments (weekly, monthly, quarterly, annually)
    
    @ Returns
    - pmnt_amt  - The amount that each payment will be
    '''
    
    freq_lookup = {'weekly':52, 'monthly':12, 'quarterly':4, 'annually':1}
    int_rate = float(int_rate) / 100
    
    rr = int_rate / freq_lookup[freq]
    x = (1.0 + rr) ** num_pmnts
    y = rr / (x - 1.0)
    pmnt_amt = (rr + y) * principal
    
    return pmnt_amt


def main():
    r = input('What is your interest rate?   ')
    t = input('How many payments will you make?   ')
    la = input('What was the amount of the loan?   ')
    rt = None
    while rt not in ['weekly', 'monthly', 'quarterly', 'annually']:
        if rt:
            rt = raw_input('Sorry that was not an option, please respond with weekly, monthly, quarterly, or annually:   ').lower()
        else:
            rt = raw_input('Do you make your payments weekly, monthly, quarterly, or annually?   ').lower()
    payment = calc_payment(r, t, la, rt)
    print 'Your %s payment will be %.2f' % (rt, payment)


if __name__ == '__main__':
    main()
    raw_input('Press Enter to Exit...')

Here are the modifications I made:

1. Moved the payment calculation to a function called calc_payment

vegaseat commented: nice info +9
jlm699 320 Veteran Poster

How about using a dictionary instead of two separate lists/tuples:

>>> user_dict = {}
>>> user_dict['user1'] = 'passwd1'
>>> user_dict.get('user2')
>>> user_dict.get('user1')
'passwd1'
>>>

As you can see, by using the get function, we can test whether a user name is in the dictionary or not. If the name is in the dictionary, it returns a string; otherwise it returns a None .

I think this would simplify and speed up your code big time.

jlm699 320 Veteran Poster

Hey guys I managed to figure it out myself. Thanks for the help.
However what in my code makes it insert a space after every letter and how do I undo that? like if I input "BJ" the output is "W E" and I just want "WE." And how can I restrict it to an 80 character window without wrapping if the input is a very long single line? Thanks a ton.

Having a comma in your print statement gives you the spaces. Either upgrade to Python3.X with the new print function or use sys.stdout like so:

import sys

# Your code here

#Instead of print chr(ascii), use this:
sys.stdout.write(chr(ascii))

Either that or simply create a new string variable in your loop and print it after the loop exits:

new_str = ''

# Do stuff

for ch in usr_input:
    # Do stuff
    new_str += new_character

print new_str

HTH

jlm699 320 Veteran Poster

Why don't you try something like this:

from string import letters
# Upper letters only
letters = letters[26:]

c_string = raw_input("Enter desired sentence to convert: ")

cs_string = 5
ci_string = cs_string % 26
upper_string = c_string.upper()

for ch in upper_string:
    lett_idx = letters.find(ch)

    if lett_idx != -1:
        lett_idx -= cs_string
        if lett_idx < 0:
            lett_idx += len(letters)

    print letters[lett_idx],

You don't actually need to do the check for if lett_idx < 0 since negative indices in Python will still give you the same result, I was just keeping your logic intact

jlm699 320 Veteran Poster

Ok do you have other suggestions?

Instead of making your variables global, simply return them from the function. Here's an example of a function with return values

>>> def retVals(inp):
...     inp += 5
...     out = inp*3
...     return inp, out
...     
>>> a = 4
>>> b, c = retVals(a)
>>> print a,b,c
4 9 27
>>> a = 10
>>> b, c = retVals(a)
>>> print a,b,c
10 15 45
>>>
jlm699 320 Veteran Poster

On top of jice's comment, you don't need to import string, and it would benefit you to move your top-level code into your main function:

def getdata(data):
    listing = []
    for line in data:
        new_line = line.split()[:2]
        listing.append(new_line)
  
    number = len(listing)
    items = listing

    # This is what jice added
    return number, items

def main():
    Name = raw_input("Filename ")
    infile = open(Name, 'r')
    data = infile.readlines()
    number, items = getdata(data)

''' This is a pretty common practice in Python to call your main
function (this wont get called if another script imports this
a module, as the other script will in that case be __main__,
not this one):
'''
if __name__ == '__main__':
    ''' If you want your program to loop you would put that
       logic here; for instance :
    while 1:
        main()
    '''
    main()
jlm699 320 Veteran Poster

I have looked more into pstgresql since my last post and want to refine my questions. From what I understand limiting who can connect to the database server is very easy with postgresql. You can use usernames and passwords along with allowing only certain ip addresses.

So as long as you are connected to the office intranet, know the name of the host of the database server, know a username and password and you have an allowed ip address, you should be able to get access to the server...no matter where you are? If the database server is hosted on either a computer or server on the private office intranet, do you need to be on the private office intranet to access it, or just simply connected to the internet somewhere?

In addition to ov3rcl0ck's comments above, also keep in mind that many "intranets" allow you to tunnel or VPN inside of the intranet from the outside world. If you have a way of accessing your work LAN/intranet from home then potentially you could access the private network-hosted database from anywhere. Otherwise, the only way to access the intranet-hosted database would be to have open access to said intranet.

You could also choose to host the database on your company's DMZ server; this would be the server that provides the outside internet into your internal network. You'd have to talk to your IT department about it, as I'm sure they'd have a number of security measures that they would …

jlm699 320 Veteran Poster

How do I create this server? Can the server and the databases be on any machine's hard disk on the network?

This process is pretty easy with Postgresql; just download and install from here. There's documentation and help resources there for you if you're a command line junkie. There's a GUI front-end for pg that you can use to setup your database quickly and with very minimal effort. And yes, you can install the server/database onto any machine's hard disk but keep in mind that if you need a large database that is always available you'll want to install it on a server (or at least a reliable computer that is always available), preferably with more than plenty of storage.

Also, once the server and databases are created, how is access granted to the server?

You set up user accounts with passwords

In my application I use wxpython as a front-end, but can anyone with a front-end get onto this database server?

wxPython isn't your front-end it's just your GUI toolkit. The front-end would be whatever you use to access the database. Anyone that has a compatible front-end would have access as long as they know a user name/password (can also be open access ie, no pw). When you install pg it comes with a very nice front-end that will allow you quick and easy access to any pg databases. Any body that wants to access your db could install this application.

You could alternately create and …

jlm699 320 Veteran Poster

This is certainly not the only solution but postgresql can easily handle multiple users (like I assume most other RDMs can). The psycopg2 module is what I've used in the past for postgres but I know there are a few others out there.