[Tutor] For Loops and nested loops
Hi im still relatively new to python and i am designing a multiplication table that enables a user to input the size of the times table unfortunately ive stumbled on the nested loops this is what i have right now: a=raw_input('please enter a number') b=int(a) n=b+1 for row in range(1, n): for col in range(1, n): print "%3d " % (row * col), print the input which comes out is: 12345 2468 10 369 12 15 48 12 16 20 5 10 15 20 25 however i need something more on the lines of: | 2 3 4 5 == 2 | 4 6 8 10 3 | 6 9 12 15 4 | 8 12 16 20 5 | 10 15 20 25 does anyone know what i need the third nested for loop to be ? to make it like the above example. Pleasee help me !! _ Win New York holidays with Kellogg’s & Live Search http://clk.atdmt.com/UKM/go/107571440/direct/01/___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Beginner problem: name 'convertToFahrenheit' is not defined
On Sat, Aug 16, 2008 at 1:22 AM, Joseph Bae <[EMAIL PROTECTED]> wrote: > convertTo == "C" and convertToCelsius(temp) or > convertToFahrenheit(temp) This idiom has a pitfall. Consider A and B or C If B can evaluate to a false value, such as None or 0, the expression will not do what you intend. This idiom is only safe when you are sure that B will never evaluate to false. In Python 2.5 there is a better way to write it: B if A else C This is a safer way to write your program. Kent ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Beginner problem: name 'convertToFahrenheit' is not defined
On Sat, 2008-08-16 at 07:40 +0200, [EMAIL PROTECTED] wrote: > Message: 1 > Date: Fri, 15 Aug 2008 22:22:00 -0700 > From: "Joseph Bae" <[EMAIL PROTECTED]> > Subject: Re: [Tutor] Beginner problem: name 'convertToFahrenheit' is > not defined > To: "Alan Gauld" <[EMAIL PROTECTED]> > Cc: tutor@python.org > Message-ID: > <[EMAIL PROTECTED]> > Content-Type: text/plain; charset="iso-8859-1" > > Thanks for the help! > > I have managed to get a good temperature converter program working! I > am > working on beefing it up a bit with some exception handling and an > "and-or > trick". The error handling works okay but I am having problems using > and-or. > Here's my updated code: > You can fix some of these: > def main(): > true = 1 > while true: You can use True (note the capital (T)rue) for the boolean value of True. > try: > temp = int(raw_input("Enter A Number : ")) > break > except ValueError: > print "Invalid Input" Following the concept: Don't Make Me Repeat Myself, you could factor out the input function: def take_input(prompt, validator = int, errormessage = 'Invalid Input', exceptions = (ValueError, )): ''' prompt - String to be printed before raw_input validator - Function to be called after raw_input errormessage - String to be printed if any exceptions in exceptions is raised exceptions - List/Tuple containing list of exceptions to caught ''' while True: print prompt, try: return validator(raw_input()) except exceptions: print errormessage > while true: > convertTo = raw_input("Convert To (F)ahrenheit or (C)elsius? : > ") > if not convertTo == "F" and not convertTo == "C": If a boolean expression so simple looks complex, there is usually a simpler version. Try learning boolean logic a little bit, specifically boolean simplification for formal ways to simplify a boolean expression (although many text about boolean logic subject is from electronic, the basic rules are the same in programming and math). > print "Invalid Input" > *else: > convertTo == "C" and convertToCelsius(temp) or > convertToFahrenheit(temp) Never use and-or trick except if you're writing for Python Obfuscation Code Contest, they have huge pitfalls[1], the and-or trick was useful before python got "inline if" (although Guido choose a frankly rather unusual syntax): true_value if expression else false_value so your and-or trick should be: convertToCelcius(temp) if convertTo == 'C' else convertToFahrenheit(temp) [1] in and-or hackery a problem arises for codes like this: >>> b = 0 >>> c = 3 >>> True and b or c 3 >>> False and b or c 3 I'll leave it to you for brain exercise on why that thing happened > break > * > def convertToCelsius(t): > tC = (9.0/5.0) * (t - 32) > print "%d Fahrenheit = %d Celsius" % (t, tC) It's a bad idea for reusability to make convertToCelcius and convertToFahrenheit print the result themselves, the function would be more useful if it return the converted value and let the main program print them. This way, the function could be used for other things as well (for example, in a more complex temperature converter, rather than typing out all to all converters, it's a much better idea to convert to a common unit (say Kelvin, the SI standard for temperature), then convert it again to the target unit. This is impossible to be done if convertToCelcius prints the result themself. i.e.: def convertToCelcius(t): return #Do some formula t = 10 print '%s %s = %s %s' + (t, 'Fahrenheit', convertToCelcius(t), 'Celcius') > def convertToFahrenheit(t): > tF = (9.0/5.0) * (t + 32) > print "%d Celsius = %d Fahrenheit" % (t, tF) > > if __name__=="__main__": it's not a must, you should see PEP 8 (it's the style guideline): http://www.python.org/dev/peps/pep-0008/ > main() > > Sample Output (as of right now): > > Enter A Number : 50 > Convert to (F)ahrenheit or (C)elsius? C > 50 Fahrenheit = 32 Celsius > 32 Celsius = 147 Fahrenheit <-- shouldn't show up and 147 is too > high ... > > This only happens when I tell it to convert to C, if I say F it works > normally. I've debugged it with pdb.set_trace() many times but can't > figure > out what's wrong. Help is much appreciated =) > > Thanks, > > Joe ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] For Loops and nested loops
Umesh Singhal wrote: Hi im still relatively new to python and i am designing a multiplication table that enables a user to input the size of the times table unfortunately ive stumbled on the nested loops this is what i have right now: a=raw_input('please enter a number') b=int(a) n=b+1 for row in range(1, n): for col in range(1, n): print "%3d " % (row * col), print the input which comes out is: 12345 2468 10 369 12 15 48 12 16 20 5 10 15 20 25 however i need something more on the lines of: | 2 3 4 5 == 2 | 4 6 8 10 3 | 6 9 12 15 4 | 8 12 16 20 5 | 10 15 20 25 does anyone know what i need the third nested for loop to be ? to make it like the above example. Pleasee help me !! I could write the program for you but I'd rather prod you into working it out yourself as I think you will learn more in the process. What code would you write to generate the first line? It is a loop, but not nested. At the beginning of each row you want to print the row number. What one statement would you add and where would you put it to do that. BTW I would find your questions and comments easier to read if you divided sentences with capitalization and punctuation. Be sure to reply-all. -- Bob Gailer Chapel Hill NC 919-636-4239 When we take the time to be aware of our feelings and needs we have more satisfying interatctions with others. Nonviolent Communication provides tools for this awareness. As a coach and trainer I can assist you in learning this process. What is YOUR biggest relationship challenge? ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Beginner problem: name 'convertToFahrenheit' is not defined
I too am a Beginner at python, and i have been playing around with it for about a week. While playing around, i decided to make a calculator program (A Very simple one) to calculate area and also to convert farenheit to celcius and vice versa. So, here is the code: def options(): print "Options:" print " 'p' to print options" print " 's' for area of square" print " 't' for area of triangle" print " 'c' for area of square" print " 'ce' to convert from celsius to farenheit" print " 'fa' to convert from fahrenheit to celcius" print " 'q' to quit the program" print "Welcome to this calculator." user = raw_input("So, What is your name? ") print "Oh, Welcome ", user,",I´ll be your calculator to day." print "Please select one of these options, and lets calculate!" print options() def positive(): print "Must be a positive number" def square_area(width, height): return width * height def triangle_area(width, height): return width * height / 2 def circle_area (radius): return radius * 3.141562953589793 def c_to_f(c_temp): return 9.0 / 5.0 * c_temp + 32 def f_to_c(f_temp): return (f_temp - 32.0) * 5.0 / 9.0 def choice(): choice = "p" while choice != "q": choice = raw_input("Option: ") if choice == "p": print options() elif choice == "s": print "So, you have chosen to calculate the area of a Square." w = input("Please enter Width: ") while w <= 0: positive() w = input("Please enter Width: ") h = input("Please enter Height: ") while h <= 0: positive() h = input("Please enter Height: ") print "The Square´s area is: ", square_area(w,h) elif choice == "t": print "So, you have chosen to calculate the area of a Triangle." w = input("Please enter Width: ") while w <= 0: positive() w = input("Please enter Width: ") h = input("Please enter Height: ") while h <= 0: positive() h = input("Please enter Height: ") print "The Triangle´s area is: ", triangle_area(w,h) elif choice == "c": print "So, you have chosen to calculate the area of a Circle." r = input("Please enter radius: ") while r <= 0: positive () r = input("Please enter radius: ") print "The Circle´s area is: ", circle_area (r) elif choice == "ce": print "So, you´re wondering how Celcius relates to Farenheit." c = input("Please enter Celcius degree´s: ") print c, "Degree´s Celcius are", c_to_f(c), "Degree´s Farenheit." elif choice == "fa": print "So, you´re wondering how Farenheit relates to Celcius." f = input("Please enter Farenheit degree´s: ") print f,"Degree´s Farenheit are", f_to_c(f), "Degree´s Celcius." else: print "That option does not exsist" choice = raw_input("Option: ") choice() print "Leaving eh, Well, Goodbye!" time.sleep(5) There you can see the Farenheit - Celcius part, and also the simple menu system. Hope this Helps! ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] What has Editor X got that PyWin32 hasn't?
> Message: 6 > Date: Fri, 15 Aug 2008 21:31:51 +0100 > From: "Alan Gauld" <[EMAIL PROTECTED]> > Subject: Re: [Tutor] What has Editor X got that PyWin32 hasn't? > To: tutor@python.org > Message-ID: <[EMAIL PROTECTED]> > Content-Type: text/plain; format=flowed; charset="iso-8859-1"; > reply-type=original > > > "Lie Ryan" <[EMAIL PROTECTED]> wrote > > > I've seen vi(m) being praised a lot, well, personally the thing > that > > I > > hate the most about vim is its directional button (khjl) which is > > unnatural > > But very logical and easy to remember when you recall > that ^H was backspace (go left), and ^j was linefeed > (go down) and the typists home position has the right hand > on ,j,k,l, (and if you use your imagination K looks a bit like > an up arrow and L like a right facing symbol - but personally > I think that's coincidental!) and shifting one position left is > an easy reach. (BTW A lot of early terminal games, especially > on Unix use the hjkl format. And so, of course does the > bash shell and more (and maybe less?) ) No offense (to you and to other vi(m) fans), but that argument is forcing itself way too much[1], humans doesn't think in such terms -- not in their subconsciousness -- humans think visually when navigating (up is located somewhere higher than down)[2]. [1] (to note: it isn't that I don't remember the buttons, but I found myself subconsciously pressing j when I want to go up and k when I want to go down nearly all the time) [2] That's why no TV remote put their buttons in this arrangements: right down up left Though I do admit that plane pilots do have their own queerness on choosing the direction their plane goes when they move their joystick, somehow it does feels more natural. > > touchpad and keyboard 2) the keyboard is smaller, 3) many of the > > hotkeys > > require pressing Esc first to get out from editing/inserting mode, > > which > > is just as inconvenient as reaching the Ctrl. And for vi(m), after > > going > > to command/shortcut mode and pressing the shortcut, then most of the > > time you have to go back to editing mode by pressing i/a/etc, that > > is > > much worse than the Ctrl craziness. > > Remember that the default mode in vi is "editing mode" with is > actually OK, wrong terminology, I'm not too much fan of vi(m) myself, pardon for that. > where you type commands. The mode you call editing mode is > actually insert mode and only applies for the duration of a command. > Thus it is logical, from command mode, to enter a command, enter trext > and then hit ESC to escape from insert mode back to the native > editing/command mode. You have to get used to the idea that inserting > text is not the default activity, navigating and changing text is - > which is To me, as a programmer, navigating, inserting, deleting, and editing are four basic operation when editing a text, I can't stand inserting and deleting (or any one of them) being called second to the others. Why do they think that programmers insert texts less often than changing text? I'm not sure, probably that's their workflow. > what most programmers do most of the time. So a command in > vim consists of: > > [[]] which is a waste of movement compared to modern text editor. Compared to just clicking then typing, pressing command then typing then escape is redundant. For those that used vim because you don't want your hand to be getting back and forth from the keyboard to mouse when typing, you should change to a laptop, in which the distance between the touchpad and keyboard is really close (you could, sort of, say that the keyboard and the touchpad is a singular device). I could even argue that moving the hand from the home position to touchpad is shorter than moving the hand from home position to Esc key, which you have to do many times in vim. And as an addition, in a modern text editor, you could use shift+directional[1] to select text very quickly, you can't do that in the almighty vim, you must instead type "y(ank)-an_obscure_direction_that_is_slow_to_work_with_because_you_have_to_carefully_count_first_how_many_characters_or_words_or_lines_you_want_to_yank_,_what_makes_it_worse_is_you_cannot_realize_counting_mistake_until_you_putted_the_text_,_also_if_you_make_a_mistake_you_have_to_do_it_from_beginning_instead_of_continuing_where_you_left_off_before-ESCAPE(From_this_mess)" [1] directional isn't only up, down, left, and right, but also home, end, page up, page down, and ctrl+directional, most people never fully utilize the extended directionals and instead uses the mouse (or in case of vim users, keyboards) more than is really necessary (instead of balancing between keyboard and mouse usage). > The good news about vim (as opposed to vi) The only good news about vim is it's the only command-line text editor in my OS that I know. > is that you don't > need to do that nearly as often since it recognises the arrow > keys and you can do basic deletion etc while i
Re: [Tutor] What has Editor X got that PyWin32 hasn't?
On Sat, Aug 16, 2008 at 11:07 AM, Lie Ryan <[EMAIL PROTECTED]> wrote: > > I agree it is very powerful, at its time, when computers are > keyboard-only and terminal-only. But now, most of its power is largely > redundant and is pale compared to modern text-editor that do acknowledge > mouse as a primary input device. > I've never met anyone who could edit faster with a mouse than I can with my basic knowledge of vi. Bottom line - you don't like to use vi (or prefer to use your mouse). Those of us who use vi have experienced its benefits. (And using visual mode to yank helps eliminate counting errors ;) ) Neither of us will change, and making arguments to the contrary is worse than arguing about religion (although one could very well argue that choice of editors is practically a religion, and I'm sure there are many folks out there who defend their editor more than their religion). Bottom line v.2, People should use what works best for them. -Wayne ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Beginner problem: name 'convertToFahrenheit' is not defined
On Sat, Aug 16, 2008 at 12:07 PM, Matti/Tritlo <[EMAIL PROTECTED]> wrote: Some quick notes: > print options() No need for the 'print' here, options() already prints. The extra print will print the return value of options(), which is None. > def triangle_area(width, height): > return width * height / 2 This will give an incorrect result if width and height are both odd integers. Use 2.0 instead of 2 to force float division. Kent ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] What has Editor X got that PyWin32 hasn't?
This is getting pretty far off topic. Let's not have an editor flamewar please. If you like vim, great! Use it! If you don't like vim, great! Use something else. If everyone liked the same editor features there wouldn't be so many to choose from. Thanks, Kent ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Beginner problem: name 'convertToFahrenheit' is not defined
On Sat, 2008-08-16 at 16:07 +, Matti/Tritlo wrote: > I too am a Beginner at python, and i have been playing around with it > for about a week. While playing around, i decided to make a calculator > program (A Very simple one) to calculate area and also to convert > farenheit to celcius and vice versa. So, here is the code: Shall I give some comments on your code? > def options(): > print "Options:" > print " 'p' to print options" > print " 's' for area of square" > print " 't' for area of triangle" > print " 'c' for area of square" > print " 'ce' to convert from celsius to farenheit" > print " 'fa' to convert from fahrenheit to celcius" > print " 'q' to quit the program" > print "Welcome to this calculator." > user = raw_input("So, What is your name? ") > print "Oh, Welcome ", user,",I´ll be your calculator to day." > print "Please select one of these options, and lets calculate!" > print options() > def positive(): > print "Must be a positive number" > > def square_area(width, height): > return width * height > > def triangle_area(width, height): > return width * height / 2 > > def circle_area (radius): > return radius * 3.141562953589793 > > def c_to_f(c_temp): > return 9.0 / 5.0 * c_temp + 32 > > def f_to_c(f_temp): > return (f_temp - 32.0) * 5.0 / 9.0 > > def choice(): > choice = "p" > while choice != "q": > choice = raw_input("Option: ") > if choice == "p": > print options() > elif choice == "s": > print "So, you have chosen to calculate the area of a > Square." > w = input("Please enter Width: ") never use input(), use raw_input() instead. input() parses the string it receives first, and may (read: WILL in the hands of certain persons) allow user to input certain strings that get parsed into dangerous codes. Use int(raw_input()) instead to convert the result of raw_input (i.e. string) into a number (i.e. integer). Since we're using int() to convert the string into number now, if you typed non-numbers, you'd get an Exception/Error, so you should add a try: block that would -- in case of errors -- reask the user again. try: int('string') except ValueError: print 'You passed a string that cannot be turned into integer' > while w <= 0: > positive() > w = input("Please enter Width: ") > h = input("Please enter Height: ") > while h <= 0: > positive() > h = input("Please enter Height: ") > print "The Square´s area is: ", square_area(w,h) > elif choice == "t": > print "So, you have chosen to calculate the area of a > Triangle." > w = input("Please enter Width: ") > while w <= 0: > positive() > w = input("Please enter Width: ") > h = input("Please enter Height: ") > while h <= 0: > positive() > h = input("Please enter Height: ") > print "The Triangle´s area is: ", triangle_area(w,h) Don't you think that all those codes seems very similar and redundant and tiring to type? Then make it into a function, pass arguments to make the behavior of the function differs and cut short a lot of lines. def getanumber(prompt): h = int(raw_input(prompt)) while h <= 0: positive() h = int(raw_input(prompt)) return h ... elif choice == 't': print "So, you have chosen to calculate the area of a Triangle." w = getanumber("Please enter Width: ") h = getanumber("Please enter Height: ") print "The Triangle´s area is: ", triangle_area(w,h) elif choice ... Ok, now we're left with that, which is still redundant since the pattern of print, get input values, and print output values is still repeated. Personally I'd go even further to make them functions too, but I'll let you pass with that (why? because: since not all menu options require the same number of argument it'd require using a clever trick involving list/dictionary and for-loop iteration, for now I think it might be out of bounds). PS: If you're really interested in how your program can still even be made more concise and less redundant, see way below for a raw, uncommented, !untested! code. > > elif choice == "c": > print "So, you have chosen to calculate the area of a > Circle." > r = input("Please enter radius: ") > while r <= 0: > positive () > r = input("Please enter radius: ") > print "The Circle´s area is: ", circle_area (r) > elif choice == "ce": > print "So, you´re wondering how Celcius relates to > Farenheit." > c = input("Please enter Celcius degree´s:
Re: [Tutor] What has Editor X got that PyWin32 hasn't?
On Sat, 2008-08-16 at 11:20 -0500, W W wrote: > On Sat, Aug 16, 2008 at 11:07 AM, Lie Ryan <[EMAIL PROTECTED]> wrote: > > > I agree it is very powerful, at its time, when computers are > keyboard-only and terminal-only. But now, most of its power is > largely > redundant and is pale compared to modern text-editor that do > acknowledge > mouse as a primary input device. > > I've never met anyone who could edit faster with a mouse than I can > with my basic knowledge of vi. I think the greatest bottleneck in editing isn't the tool itself, but how fast the editor can identify what to edit/write next (the slowest thing attached to a computer is between the keyboard and chair). And if you're doing an editing contest, I'm sure I can fare _at_least_ as fast as you. > Bottom line - you don't like to use vi (or prefer to use your mouse). Don't take it wrong, I don't hate vi, I like to use it too in certain circumstances, I only thought it was way too overrated. > Those of us who use vi have experienced its benefits. (And using > visual mode to yank helps eliminate counting errors ;) ) > > Neither of us will change, and making arguments to the contrary is > worse than arguing about religion (although one could very well argue > that choice of editors is practically a religion, and I'm sure there > are many folks out there who defend their editor more than their > religion). > > Bottom line v.2, People should use what works best for them. > I won't try to change you if you won't. I agree with you though: "choose what's works best for you". For me: touchpad+keyboard combination allows the fastest editing speed a typical vim-ers would have a hard time to match. > -Wayne > ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] For Loops and nested loops
On Sat, Aug 16, 2008 at 06:33:42AM +0100, Umesh Singhal wrote: > Hi im still relatively new to python and i am designing a multiplication > table that enables a user to input the size of the times table unfortunately > ive stumbled on the nested loops this is what i have right now: Is this a homework assignment? Forgive me if it's not, but somehow it feels like the sort of thing a teacher would assign. At least, I've been known to give my programming students things like it before when they were just starting out. > a=raw_input('please enter a number') > b=int(a) > n=b+1 > for row in range(1, n): remember what means in range(1, ). You may have a fencepost error (off-by-one), depending on what you intended to happen here. -- Steve Willoughby| Using billion-dollar satellites [EMAIL PROTECTED] | to hunt for Tupperware. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] For Loops and nested loops
On Sat, 2008-08-16 at 18:07 +0200, [EMAIL PROTECTED] wrote: > Message: 1 > Date: Sat, 16 Aug 2008 06:33:42 +0100 > From: Umesh Singhal <[EMAIL PROTECTED]> > Subject: [Tutor] For Loops and nested loops > To: > Message-ID: <[EMAIL PROTECTED]> > Content-Type: text/plain; charset="windows-1252" > > > Hi im still relatively new to python and i am designing a > multiplication table that enables a user to input the size of the > times table unfortunately ive stumbled on the nested loops this is > what i have right now: > > a=raw_input('please enter a number') > b=int(a) > n=b+1 > for row in range(1, n): > for col in range(1, n): > print "%3d " % (row * col), > print > > the input which comes out is: > 12345 > 2468 10 > 369 12 15 > 48 12 16 20 > 5 10 15 20 25 > > however i need something more on the lines of: > | 2 3 4 5 > == > 2 | 4 6 8 10 > 3 | 6 9 12 15 > 4 | 8 12 16 20 > 5 | 10 15 20 25 > > does anyone know what i need the third nested for loop to be ? to make > it like the above example. Pleasee help me !! You don't need to use third nested loop, your two nested loop is enough. First, however, you need to think first, how you'd generate the output. Following your thinking pattern, I'd do it like this: #1 | 2 3 4 5 #2 | 2 3 4 5 == 2 | #3 | 2 3 4 5 == 2 | 4 #4 | 2 3 4 5 == 2 | 4 6 #5 | 2 3 4 5 == 2 | 4 6 8 #6 | 2 3 4 5 == 2 | 4 6 8 10 #7 | 2 3 4 5 == 2 | 4 6 8 10 3 | #8 etc Do you see how you could generate the table headings? ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] simple python scrip for collocation discovery
Hello Tutors, I'm trying to write a small scrip to find collocations using chi squared, depending on a fairly big corpus. The program below does a good job, but it's too slow, and I need to process something like 50 million words. How can I make it run fast? Your help is appreciated. Emad nawfal #! usr/bin/python # Chi-squared collocation discovery # Important definitions first. Let's suppose that we # are trying to find whether "powerful computers" is a collocation # N = The number of all bigrams in the corpus # O11 = how many times the bigram "powerful computers" occurs in the corpus # O22 = the number of bigrams not having either word in our collocation = N - O11 # O12 = The number of bigrams whose second word is our second word # but whose first word is not "powerful" # O21 = The number of bigrams whose first word is our first word, but whose second word # is different from oour second word ### print """ * * Welcome to the Collocationer ** * * * """ # Let's first get the text and turn into bigrams bigrams = [] infile = file("corpus.txt") text = infile.read().lower().split() infile.close() for i,v in enumerate(text): # get words and their ranking number if i < len(text)-1: # This guarntees that the list index is not out of range bigram = v, text[i+1] # each word and the two succeding words bigrams.append(bigram) tested_collocate = raw_input("Enter the bigram you think is a collocation\n") word1 = tested_collocate.split()[0] word2 = tested_collocate.split()[1] N = len(bigrams) O11 = bigrams.count(tuple(tested_collocate.split())) O22 = [bigram for bigram in bigrams if word1 != bigram[0] and word2 != bigram[1]] O12 = [bigram for bigram in bigrams if bigram[1] == word2 and bigram[0] != word1] O21 = [bigram for bigram in bigrams if bigram[0]== word1 and bigram[1] != word2] O22 = len(O22) O12 = len(O12) O21 = len(O21) chi2 = (N * ((O11 * O22 - O12 * O21) ** 2))/ float((O11 + O12) * (O11 + O21) * (O12 + O22) * (O21 + O22)) print "Chi-Squared = ", chi2 if chi2 > 3.841: print "These two words form a collocation" else: print "These two words do not form a collocation" raw_input('Enter to Exit') -- لا أعرف مظلوما تواطأ الناس علي هضمه ولا زهدوا في إنصافه كالحقيقة.محمد الغزالي "No victim has ever been more repressed and alienated than the truth" Emad Soliman Nawfal Indiana University, Bloomington http://emnawfal.googlepages.com ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] simple python scrip for collocation discovery
On Sat, Aug 16, 2008 at 01:55:36PM -0400, Emad Nawfal ( ) wrote: > Hello Tutors, > I'm trying to write a small scrip to find collocations using chi squared, Minor nit, but the word you're looking for here is "script". "Scrip" is also an English word but means something completely different. Looking professional in a field includes using the jargon correctly. > depending on a fairly big corpus. > The program below does a good job, but it's too slow, and I need to process > something like 50 million words. > How can I make it run fast? How fast is fast enough? What's its time now? Can you identify where it might be slowing down? Depending on the order of magnitude of the speedup you're looking to achieve, the answer could be very different. > # Let's first get the text and turn into bigrams > bigrams = [] > infile = file("corpus.txt") > text = infile.read().lower().split() This strikes me as needlessly memory-consuming. You might want to iterate over lines of text instead of sucking the entire file into a giant string. I'm guessing you want to recognize words next to one another even if separated by a newline? Be aware of the cost, though, of passing potentially huge data values around. > infile.close() > for i,v in enumerate(text): # get words and their ranking number > if i < len(text)-1: # This guarntees that the list index is not out of > range > bigram = v, text[i+1] # each word and the two succeding words > bigrams.append(bigram) Why don't you trust enumerate's i values, out of curiosity? It seems to me if you think of what you're collecting here you could do some calculating on the fly as you look through the list of words and wouldn't need to be building these lists and then going back through them. I'm trying to give some vague help without doing the work for you because we don't do homework exercises for people :) -- Steve Willoughby| Using billion-dollar satellites [EMAIL PROTECTED] | to hunt for Tupperware. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] python-ldap installation
This may sound silly, but I've been searching for a reliable method for installing the python-ldap module for Python 2.4 in a Windows XP environment. Actually, I'm looking for a method that would work cross-platform with Linux and OS X as well, or at least methods that were close enough in nature to be called similar. As far as Windows goes: I've tried installing the binary linked from the python-ldap project page, but that is a third-party binary, and they only have installers for 2.5 (I tried these just to be sure, and sure enough, 2.4 won't import the module, as it wants a 2.5 DLL instead). I did find a binary elsewhere that someone created [1], but this one seems fairly outdated. Ultimately, I'd like to automate an installation method as part of a buildout environment script that could work on multiple platforms, but I'm not sure that's going to be possible: Windows doesn't use apt-get, OS X doesn't use DLL files, etc. I also found this post [2], which probably works for systems that use apt-get, but not for others, and seems fairly complicated as well. Thanks in advance for your ideas and pointers on whether this is possible, or the best way to do it on different platforms. ~John [1] http://www.agescibs.org/mauro/ [2] http://bluedynamics.com/articles/jens/python-ldap-as-egg-with-buildout ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] simple python scrip for collocation discovery
Dear Steve, Thank you so much for your help. Actually this is not homework. It's gonna be used in building a collocation dictionary as part of my dissertation. Please remeber that I'm not a programmer, so many of the terminologies may not be accessible to me. Thank you also for attracting my attention to the typo On Sat, Aug 16, 2008 at 2:09 PM, Steve Willoughby <[EMAIL PROTECTED]> wrote: > On Sat, Aug 16, 2008 at 01:55:36PM -0400, Emad Nawfal ( ) wrote: > > Hello Tutors, > > I'm trying to write a small scrip to find collocations using chi squared, > > Minor nit, but the word you're looking for here is "script". "Scrip" > is also an English word but means something completely different. > Looking professional in a field includes using the jargon correctly. > > > depending on a fairly big corpus. > > The program below does a good job, but it's too slow, and I need to > process > > something like 50 million words. > > How can I make it run fast? > > How fast is fast enough? > What's its time now? > Can you identify where it might be slowing down? > > Depending on the order of magnitude of the speedup you're looking > to achieve, the answer could be very different. > > > # Let's first get the text and turn into bigrams > > bigrams = [] > > infile = file("corpus.txt") > > text = infile.read().lower().split() > > This strikes me as needlessly memory-consuming. You might want to > iterate over lines of text instead of sucking the entire file into > a giant string. I'm guessing you want to recognize words next to > one another even if separated by a newline? Be aware of the cost, > though, of passing potentially huge data values around. > > > infile.close() > > for i,v in enumerate(text): # get words and their ranking number > > if i < len(text)-1: # This guarntees that the list index is not out > of > > range > > bigram = v, text[i+1] # each word and the two succeding words > > bigrams.append(bigram) > > Why don't you trust enumerate's i values, out of curiosity? > > It seems to me if you think of what you're collecting here > you could do some calculating on the fly as you look through > the list of words and wouldn't need to be building these > lists and then going back through them. > > I'm trying to give some vague help without doing the work for you > because we don't do homework exercises for people :) > > -- > Steve Willoughby| Using billion-dollar satellites > [EMAIL PROTECTED] | to hunt for Tupperware. > -- لا أعرف مظلوما تواطأ الناس علي هضمه ولا زهدوا في إنصافه كالحقيقة.محمد الغزالي "No victim has ever been more repressed and alienated than the truth" Emad Soliman Nawfal Indiana University, Bloomington http://emnawfal.googlepages.com ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] python-ldap installation
On Sat, Aug 16, 2008 at 1:15 PM, John DeStefano <[EMAIL PROTECTED]>wrote: > > Ultimately, I'd like to automate an installation method as part of a > buildout environment script that could work on multiple platforms, but > I'm not sure that's going to be possible: Windows doesn't use apt-get, > OS X doesn't use DLL files, etc. I also found this post [2], which > probably works for systems that use apt-get, but not for others, and > seems fairly complicated as well. > > Thanks in advance for your ideas and pointers on whether this is > possible, or the best way to do it on different platforms. For the most part I doubt I'd be much help, but if you're looking for a way to work cross-platform, you have a few options. 1) Package all the installers together, and use your script to determine the system, either by user input, or by looking for a file that should exist on the system. It might be safer to ask for user confirmation in that case, though. 2) Do the same thing, but instead of packaging all the files, retrieve them from the 'net. HTH, Wayne -- To be considered stupid and to be told so is more painful than being called gluttonous, mendacious, violent, lascivious, lazy, cowardly: every weakness, every vice, has found its defenders, its rhetoric, its ennoblement and exaltation, but stupidity hasn't. - Primo Levi ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] What has Editor X got that PyWin32 hasn't?
"Lie Ryan" <[EMAIL PROTECTED]> wrote No offense (to you and to other vi(m) fans), No offense taken, as I said right at the beginning of this thread, editors are a religious battleground for programmers and elicit very personal reactions. Personally I use over a dozen editors on a regular basis but only about 3 or 4 heavily - all of which are quite different in style. not in their subconsciousness -- humans think visually when navigating (up is located somewhere higher than down)[2]. Actually humans think in lots of different ways. Programmers tend not to think visually but verbally (or more accuratelty symbolically) which is one reason so called visual programming environments have failed to take off! [2] That's why no TV remote put their buttons in this arrangements: Some do, I used to own one (a Philips as I recall)! :-) they think that programmers insert texts less often than changing text? I'm not sure, probably that's their workflow. It's not so much "changing" its navigating. Studies have shown that programmers spend most of their time going back over code they have alrweady written (or someone else has) and making small changes. Thats exactly where vi/vim excels. In fact when I used to work exclusively on Unix I used emacs for the initial text creation (because it is better at that) but then used vi (actually viper mode in Xemacs) for editing changes thereafter. The best of both worlds! which is a waste of movement compared to modern text editor. Compared to just clicking then typing But you can do that in vim. It is fully mouse aware and you can position the cursor, select text and more all with the mouse. should change to a laptop, in which the distance between the touchpad and keyboard is really close (you could, sort of, say that the keyboard and the touchpad is a singular device). I do use a laptop but laptop pointers are universally awful in my experience! I could even argue that moving the hand from the home position to touchpad is shorter than moving the hand from home position to Esc key, which you have to do many times in vim. Thats a valid point, but less so in vim. The ESC key was originally easily within reach of the little finger but with the introduction of PCs it has moved further away. text editor, you could use shift+directional[1] to select text very quickly, you can't do that in the almighty vim, you must instead type You can use the usual selection movements using Visual mode in vim. drag select or shift select both work as expected "y(ank)-an_obscure_direction_that_is_slow_to_work_with But no vim power user does that. They use the navigational power of vim to jump directly to where they want to be. As i said earlier I virtually never use the number commands, I use the search features or the t/f set. Thus yt or yf or for long sections ,.//y [1] directional isn't only up, down, left, and right, but also home, end, page up, page down, and ctrl+directional, most people never fully utilize the extended directionals and instead uses the mouse (or in case of vim users, keyboards) more than is really necessary (instead of balancing between keyboard and mouse usage). And all of those movements exist in vi.vim plus quite a few others as well - half page movements up down left and right movement to/from a letter or regex etc etc Its not visual and if you like visual you probably won't like vi (which is ironic since vi is short for visual! - as opposed to line oriented) I know I can use the arrow key, but that doesn't seems to be the preferred choice of vim-ers when they're in editing mode (now with correct terminology) Experienced users prefer hjkl purely because its faster than stretching to the arrow keys... But beginners nearly always use the arrow keys. (when I had the time I will surely approach them), I never thought SQL as a programming language, SQL is fully Turing complete. Some people write full business applications in pure SQL. its just a different way of thinking about control flow etc. Its more akin to prolog than Python. redundant and is pale compared to modern text-editor that do acknowledge mouse as a primary input device. vim does use the mouse as a primary device. I'm confused at the comments re vim but I totally understand them in the context of vi. But back to what I said at the beginning, if you don't like vi./vim there are lots of other choices and just go with the one that works for you. Alan g. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] What has Editor X got that PyWin32 hasn't?
As a meta-comment on this discussion (hopefully to avoid fueling the editor holy war further), there's a reason sophisticated editors such as vi[m] and EMACS (and a dozen others I could name) exist and remain popular so long after they were introduced (which may well have been longer ago than some on this list have been alive). They tend to be very, very, very good at doing certain things with text. Complaints about not liking the style of the interface or standard keybindings are understandable, but generally with these sophisticated tools, it's possible to completely redefine all of those elements to suit your personal style anyway. However, in my experience, complaints about these editors lacking capability or being too awkward to really use effectively generally stem from a lack of experience or in-depth knowledge of how to use those tools. I've heard many people say how they can't believe people would struggle through using vi when it's so fast and easy to use a mouse and easy-to-remember keys and menus, and how much faster they can perform their editing operations that way. And many times when I've worked with them on something and fired up vi and started flying all over the document changing things, or using the more powerful commands to make transformations over the whole text with a few keystrokes, I've heard "I... didn't know you could DO that!" (and I know people who know vi much, much better than I do). Like any complex tool, the time you invest in learning how to *really* harness its power will pay off. Likewise, there's a reason the IDE environments like Visual Studio or Eclipse, and pointy-clicky-WYSIWYG editing tools exist. They're much easier for beginners to learn, not as intimidating, but in the end they don't pay off with anywhere close to the amount of text-document-altering power. Their payoff is in another arena... things like having an IDE write giant chunks of boilerplate code for you, or making it easy for people whose editing needs are just to tweak a few lines here and there in an existing document (like an auto-generated template from the IDE). They're just tools. Pick the ones that work for the jobs you need to get done, but don't assume that the other ones are pointless. They may either have points you don't need, or you may not have realized their importance yet. --steve ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] What has Editor X got that PyWin32 hasn't?
Steve Willoughby wrote: Likewise, there's a reason the IDE environments like Visual Studio or Eclipse, and pointy-clicky-WYSIWYG editing tools exist. They're much easier for beginners to learn, not as intimidating, but in the end they For example, I use pyWin or IDLE all the time if I want to play interactively with the interpreter or demonstrate a really simple thing. If I go to write a 10,000-line or 50,000-line application you can bet money it will be with vim or emacs (or maybe eclipse but usually not even that). On the other hand, I'm teaching some people in my family how to program computers, and for the time being they have enough to learn just mastering the basics. They're using IDLE and pyWin. Those are easy, obvious how to do what they need to do, and can focus on learning Python itself without remembering what key does what in the editor. I love those simpler, more visual, editors for situations like that. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] simple python scrip for collocation discovery
Thank you so much Steve, I followed your advice about calculating o the fly and it really rang a bell. Now I have this script. It's faster and does not give me the nasty memory error message the first one sometimes did: # Chi-squared collocation discovery # Important definitions first. Let's suppose that we # are trying to find whether "powerful computers" is a collocation # N = The number of all bigrams in the corpus # O11 = how many times the bigram "powerful computers" occurs in the corpus # O22 = the number of bigrams not having either word in our collocation = N - O11 # O12 = The number of bigrams whose second word is our second word # but whose first word is not "powerful" # O21 = The number of bigrams whose first word is our first word, but whose second word # is different from oour second word ### print """ * * Welcome to the Collocationer ** * * * """ # Let's first get the text and turn into bigrams #tested_collocate = raw_input("Enter the bigram you think is a collocation\n") #word1 = tested_collocate.split()[0] #word2 = tested_collocate.split()[1] word1 = 'United' word2 = 'States' infile = file("1.txt") # initilize the counters N = 0 O11= 0 O22 = 0 O12 = 0 O21 = 0 for line in infile: length = len(line.split()) # a variable to hold the length of each line if len(line.split()) <=1: continue for word in line.split(): N+=1 for i,v in enumerate(line.split()): if i< length-1: if word1 == v and word2 == line.split()[i+1]: O11 +=1 for i,v in enumerate(line.split()): if i < length -1: if word1 != v and word2 != line.split()[i+1]: O22+=1 for i,v in enumerate(line.split()): if i< length-1: if word1 != v and word2 == line.split()[i+1]: O12+=1 for i,v in enumerate(line.split()): if i< length-1: if word1 == v and word2 != line.split()[i+1]: O21+=1 chi2 = (N * ((O11 * O22 - O12 * O21) ** 2))/ float((O11 + O12) * (O11 + O21) * (O12 + O22) * (O21 + O22)) print "Chi-Squared = ", chi2 if chi2 > 3.841: print "These two words form a collocation" else: print "These two words do not form a collocation" On Sat, Aug 16, 2008 at 2:09 PM, Steve Willoughby <[EMAIL PROTECTED]> wrote: > On Sat, Aug 16, 2008 at 01:55:36PM -0400, Emad Nawfal ( ) wrote: > > Hello Tutors, > > I'm trying to write a small scrip to find collocations using chi squared, > > Minor nit, but the word you're looking for here is "script". "Scrip" > is also an English word but means something completely different. > Looking professional in a field includes using the jargon correctly. > > > depending on a fairly big corpus. > > The program below does a good job, but it's too slow, and I need to > process > > something like 50 million words. > > How can I make it run fast? > > How fast is fast enough? > What's its time now? > Can you identify where it might be slowing down? > > Depending on the order of magnitude of the speedup you're looking > to achieve, the answer could be very different. > > > # Let's first get the text and turn into bigrams > > bigrams = [] > > infile = file("corpus.txt") > > text = infile.read().lower().split() > > This strikes me as needlessly memory-consuming. You might want to > iterate over lines of text instead of sucking the entire file into > a giant string. I'm guessing you want to recognize words next to > one another even if separated by a newline? Be aware of the cost, > though, of passing potentially huge data values around. > > > infile.close() > > for i,v in enumerate(text): # get words and their ranking number > > if i < len(text)-1: # This guarntees that the list index is not out > of > > range > > bigram = v, text[i+1] # each word and the two succeding words > > bigrams.append(bigram) > > Why don't you trust enumerate's i values, out of curiosity? > > It seems to me if you think of what you're collecting here > you could do some calculating on the fly as you look through > the list of words and wouldn't need to be building these > lists and then going back through them. > > I'm trying to give some vague help without doing the work for you > because we don't do homework exercises for people :) > > -- > Steve Willoughby| Using billion-dollar satellites > [EMAIL PROTECTED] | to hunt for Tupperware. > -- لا أعرف مظلوما تواطأ الناس علي هضمه ولا زهدوا في إنصافه كالحقيقة.محمد الغزالي "No victim has ever been more repressed and alienated than the truth" Emad Soliman Nawfal Indiana University, Bloomington http://emnawfal.googlepages.com ___
Re: [Tutor] Beginner problem: name 'convertToFahrenheit' is not defined
On 8/16/08, Lie Ryan <[EMAIL PROTECTED]> wrote: > never use input(), use raw_input() instead. input() parses the string it > receives first, and may (read: WILL in the hands of certain persons) > allow user to input certain strings that get parsed into dangerous > codes. Use int(raw_input()) instead to convert the result of raw_input > (i.e. string) into a number (i.e. integer). Probably float(raw_input()) would be better in this program. Kent ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] MySQLdb simple menu
New to python and programming. This works but I don't like the way it is set up. I would like to have a simple menu like; [code] def options(): print \ """ Options: 'p' Print Options 'l' Login 'c' Create account 'q' Quit """ options() def choice(): choice = "p" while choice != "q": choice = raw_input("Options: ") if choice == "p": print options() if choice == "l": login() if choice == "c": newlogin() if choice == "q": sys.exit(0) else: print "That option does not exsist!" choice = raw_input("Option: ") choice() [/code] But I can't get it to work, I can't get past; [code] for row in rows: [/code] Works but I don't like that you have to try to login first, would like it to give you the option to; login create account print menu exit [code] import sys import MySQLdb import MySQLdb.cursors conn = MySQLdb.Connect( host='localhost', user='root', passwd='atlantic', db='python', compress=1, cursorclass=MySQLdb.cursors.DictCursor) cursor = conn.cursor() cursor.execute("SELECT * FROM login") rows = cursor.fetchall() cursor.close() conn.close() username = raw_input("Enter your username (q to exit): ") password = raw_input("Enter your password (q to exit): ") for row in rows: if username == row['username'] and password == row['password']: print "Hello", username sys.exit(0) else: r = raw_input("Login failed, do you want to create an account? [y/n]") if r != 'y' : sys.exit(0) newname = "" data = [] newname = raw_input("Please enter a username: ") newpw = raw_input("Please enter a password: ") tuple = (newname, newpw) data.append(tuple) db = MySQLdb.connect( host="localhost", user="root", passwd="atlantic", db="python") cursor = db.cursor() cursor.executemany( "INSERT INTO login (username, password)VALUES (%s, %s)", data) [/code] -- Have Fun, David A. Powered by Gentoo GNU/LINUX http://www.linuxcrazy.com ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] simple python scrip for collocation discovery
Emad Nawfal (عماد نوفل) wrote: Thank you so much Steve, I followed your advice about calculating o the fly and it really rang a bell. Now I have this script. It's faster and does not give me the nasty memory error message the first one sometimes did: # Chi-squared collocation discovery # Important definitions first. Let's suppose that we # are trying to find whether "powerful computers" is a collocation # N = The number of all bigrams in the corpus # O11 = how many times the bigram "powerful computers" occurs in the corpus # O22 = the number of bigrams not having either word in our collocation = N - O11 # O12 = The number of bigrams whose second word is our second word # but whose first word is not "powerful" # O21 = The number of bigrams whose first word is our first word, but whose second word # is different from oour second word ### print """ * * Welcome to the Collocationer ** * * * """ # Let's first get the text and turn into bigrams #tested_collocate = raw_input("Enter the bigram you think is a collocation\n") #word1 = tested_collocate.split()[0] #word2 = tested_collocate.split()[1] word1 = 'United' word2 = 'States' infile = file("1.txt") # initilize the counters N = 0 O11= 0 O22 = 0 O12 = 0 O21 = 0 for line in infile: length = len(line.split()) # a variable to hold the length of each line if len(line.split()) <=1: continue for word in line.split(): N+=1 for i,v in enumerate(line.split()): if i< length-1: if word1 == v and word2 == line.split()[i+1]: O11 +=1 for i,v in enumerate(line.split()): if i < length -1: if word1 != v and word2 != line.split()[i+1]: O22+=1 for i,v in enumerate(line.split()): if i< length-1: if word1 != v and word2 == line.split()[i+1]: O12+=1 for i,v in enumerate(line.split()): if i< length-1: if word1 == v and word2 != line.split()[i+1]: O21+=1 chi2 = (N * ((O11 * O22 - O12 * O21) ** 2))/ float((O11 + O12) * (O11 + O21) * (O12 + O22) * (O21 + O22)) print "Chi-Squared = ", chi2 if chi2 > 3.841: print "These two words form a collocation" else: print "These two words do not form a collocation" I'd like to jump in here and offer a few refinements that make the code simpler and more "Pythonic". In the background I'm also researching how to use dictionaries to make things even better. Some guidelines: - use initial lower case for variable and function names, upper case for classes - don't repeat calculations - do them once and save the result in a variable - don't repeat loops - you can put the calculations for o11 o12 o21 and o22 all under 1 for loop - obtain one word at a time as rightWord and then save it as leftWord # your initial code goes here, up to but not including # for line in infile: line = infile.readline().split() # get the first line so we can get the first word leftWord = line[0] line = line[1:] # drop the first word n = 1 # count the first word o11 = o12 = o21 = o22 = 0 while line: n += len(line) # count words for rightWord in line: if word1 == leftWord and word2 == rightWord: o11 += 1 elif word1 != leftWord and word2 != rightWord: o22 += 1 elif word1 != leftWord and word2 == rightWord: o12 += 1 else: # no need to test o21 += 1 leftWord = rightWord line = infile.readline().split() # rest of your code follows starting with # chi2 = ... # If you want to get even "sexier" you could create an array of counters # counters = [[0,0],[0,0]] # where the elements left to right represent o22, o12, o21 and o11 # taking advantage of the fact that False == 0 and True == 1: for rightWord in line: counters[word1 == leftWord][word2 == rightWord] += 1 leftWord = rightWord line = infile.readline().split() -- Bob Gailer Chapel Hill NC 919-636-4239 When we take the time to be aware of our feelings and needs we have more satisfying interatctions with others. Nonviolent Communication provides tools for this awareness. As a coach and trainer I can assist you in learning this process. What is YOUR biggest relationship challenge? ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] For Loops and nested loops
PLEASE REPLY TO THE GROUP NOT JUST ME. Did you miss my request for that (reply-all)? Umesh Singhal wrote: Hi Bob, unfortunately when i pasted in the code it seems to have gone wrong this is how it is at the moment with the correct indentation for the nested loop: code: a=raw_input('please enter a number') b=int(a) n=b+1 for row in range(1, n): for col in range(1, n): print "%3d " % (row * col), print I am also unaware of what code I would need to enter to enable the row to have the value selected, if you could please tell me as I will understand it more if i see the code infront of me thank you Umesh Singhal How did you get this much code written and not be able to figure that out? Put something like print "%3d |" % row, between the 2 for statements. -- Bob Gailer Chapel Hill NC 919-636-4239 When we take the time to be aware of our feelings and needs we have more satisfying interatctions with others. Nonviolent Communication provides tools for this awareness. As a coach and trainer I can assist you in learning this process. What is YOUR biggest relationship challenge? ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] MySQLdb simple menu
David wrote: New to python and programming. This works but I don't like the way it is set up. I would like to have a simple menu like; [code] def options(): print \ """ Options: 'p' Print Options 'l' Login 'c' Create account 'q' Quit """ options() def choice(): choice = "p" while choice != "q": choice = raw_input("Options: ") if choice == "p": print options() if choice == "l": login() if choice == "c": newlogin() if choice == "q": sys.exit(0) else: print "That option does not exsist!" choice = raw_input("Option: ") choice() [/code] But I can't get it to work, I can't get past; [code] for row in rows: [/code] Works but I don't like that you have to try to login first, would like it to give you the option to; login create account print menu exit [code] import sys import MySQLdb import MySQLdb.cursors conn = MySQLdb.Connect( host='localhost', user='root', passwd='atlantic', db='python', compress=1, cursorclass=MySQLdb.cursors.DictCursor) cursor = conn.cursor() cursor.execute("SELECT * FROM login") rows = cursor.fetchall() cursor.close() conn.close() username = raw_input("Enter your username (q to exit): ") password = raw_input("Enter your password (q to exit): ") for row in rows: if username == row['username'] and password == row['password']: print "Hello", username sys.exit(0) else: r = raw_input("Login failed, do you want to create an account? [y/n]") if r != 'y' : sys.exit(0) newname = "" data = [] newname = raw_input("Please enter a username: ") newpw = raw_input("Please enter a password: ") tuple = (newname, newpw) data.append(tuple) db = MySQLdb.connect( host="localhost", user="root", passwd="atlantic", db="python") cursor = db.cursor() cursor.executemany( "INSERT INTO login (username, password)VALUES (%s, %s)", data) [/code] How does this look; #!/usr/bin/python #Filename : choices.py import sys import MySQLdb import MySQLdb.cursors def login(): conn = MySQLdb.Connect( host='localhost', user='root', passwd='atlantic', db='python', compress=1, cursorclass=MySQLdb.cursors.DictCursor) cursor = conn.cursor() cursor.execute("SELECT * FROM login") rows = cursor.fetchall() cursor.close() conn.close() username = raw_input("Enter your username (q to exit): ") password = raw_input("Enter your password (q to exit): ") for row in rows: if username == row['username'] and password == row['password']: print "Hello", username sys.exit(0) print "Login failed!" def newlogin(): newname = "" data = [] newname = raw_input("Please enter a username: ") newpw = raw_input("Please enter a password: ") tuple = (newname, newpw) data.append(tuple) db = MySQLdb.connect( host="localhost", user="root", passwd="atlantic", db="python") cursor = db.cursor() cursor.executemany( "INSERT INTO login (username, password)VALUES (%s, %s)", data) print "Account created for", newname sys.exit(0) def options(): print \ """ Please pick one: 'p' Print Options 'l' Login 'c' Create account 'q' Quit """ options() choice = "p" while choice != "q": choice = raw_input("Please pick an option: ") if choice == "p": options() elif choice == "l": login() elif choice == "c": newlogin() elif choice == "q": print "Goodbye!" seems to work OK. -- Have Fun, David A. Powered by Gentoo GNU/LINUX http://www.linuxcrazy.com ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Is there python editor or plugin for a python editor for curly brackets around code blocks?
I talked about earlier how the main problem for me wanting to use curly braces is because of the visual ease of seeing the end of the code blocks.. well you can change the indention guidelines on most code editors to a bright color and this might be the next best thing. Also a good feature to implement is just like there are highlighted curly braces when your mouse or key presses are inside certain code blocks, they should highlight or change the indentation guides to the same effect On Thu, Aug 14, 2008 at 1:16 AM, Timothy Grant <[EMAIL PROTECTED]>wrote: > On Wed, Aug 13, 2008 at 9:08 PM, xbmuncher <[EMAIL PROTECTED]> wrote: > > I don't see what the big deal is on coming up with the .{ #{, and other > > bracket types to try to not interfere with normal bracket use in python. > Its > > relatively easy to create a parser to identify the brackets in use > normally > > and the code block brackets, with regex or without. > > > > On Wed, Aug 13, 2008 at 11:39 PM, Chad Crabtree <[EMAIL PROTECTED]> > wrote: > >> > >> Oh, I forgot there's another way to add braces > >> > >> if it_is_way_cool: #{ > >> print 'coolness' > >> #} > >> > >> On Wed, Aug 13, 2008 at 11:06 PM, xbmuncher <[EMAIL PROTECTED]> > wrote: > >> > I'll check out your links. But in response to some of the things said: > >> > I'm a fan of indentation, a replacement of indentation with curly > braces > >> > is > >> > not what I was aiming for. If I could have it my way, I'd have > >> > indentation > >> > and curly braces. I don't want to change official python syntax > either.. > >> > I > >> > just want to be able to easily do it myself. > >> > > >> > The big problem I had that I didn't explain well enough when I said > >> > "visually" is that it is visually hard to tell when code blocks end > when > >> > other code blocks and statements begin immediately after them. With > >> > curly > >> > braces you can easily visualize when looking at a lot of code where > the > >> > code > >> > block ends. The best thing you can do in python currently is to put an > >> > empty > >> > line in between the last line of a code block and the following code, > so > >> > you > >> > can better visualize the end of the code block. > >> > > >> > On Wed, Aug 13, 2008 at 4:23 AM, Chris Fuller > >> > <[EMAIL PROTECTED]> wrote: > >> >> > >> >> Some clarifications w.r.t. indentation and Python: > >> >> http://www.secnetix.de/olli/Python/block_indentation.hawk > >> >> > >> >> It's just a joke, really: > >> >> http://timhatch.com/projects/pybraces/ > >> >> > >> >> Turnabout is fair play! > >> >> http://blog.micropledge.com/2007/09/nobraces/ > >> >> > >> >> Also, pindent.py in the Tools/scripts directory of your Python > >> >> distribution > >> >> will produce correctly indented scripts if the blocks are designated > >> >> with > >> >> a "#end" line. > >> >> > >> >> > >> >> But seriously, you don't want to go creating a separate class of > source > >> >> file. > >> >> It'll be harder for you and the other programmers to context switch > >> >> when > >> >> working with code that uses the standard style, will confuse others > who > >> >> won't > >> >> know what to do with your code, adds overhead to the compiling, will > >> >> break > >> >> when somebody tries to run it under the standard environment, could > >> >> clutter > >> >> up your development directories, depending on the implementation, > etc. > >> >> > >> >> Here's a thread from 1999 on the Python mailing list that discusses > the > >> >> issue: > >> >> http://mail.python.org/pipermail/python-list/1999-June/004450.html > >> >> > >> >> There's another script towards the end that might even do what you > >> >> want, > >> >> but > >> >> you might want to read what they have to say first :) > >> >> > >> >> Cheers > >> >> ___ > >> >> Tutor maillist - Tutor@python.org > >> >> http://mail.python.org/mailman/listinfo/tutor > > > > If it's no big deal to parse the braces, I would encourage you to > write your own python preprocessor to handle that for you. > > > -- > Stand Fast, > tjg. [Timothy Grant] > ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Downloading RTSP streams quicker than real time streaming
Trying to create a program to download RTSP streams. I know that RTSP streams are live, so its hard to know if the stream will ever end, but the streams I'm concerned about are fixed length. *I wonder if its possible to know if the streaming content is fixed length or not * *Anyways*, I'm wanting to be able to quicken the streaming (thus download) of the stream, maybe to trick it by sending whatever signal required to make it stream more pieces of information quicker, so I can download the stream quicker than real time streaming. I've searched for a *RTSP library for python*.. haven't found anything useful, mostly unanswered threads in other mailing lists! *So do you know of one? or perhaps any other useful information/pointers/source that could help in the tasks described above?* -thanks ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor