Re: [Tutor] PLEASE HELP

2018-04-13 Thread Mayo Adams
 discrete, not discreet.

On Fri, Apr 13, 2018 at 11:38 AM, Neil Cerutti  wrote:

> On 2018-04-13, David Rock  wrote:
> >
> >> On Apr 13, 2018, at 09:24, Neil Cerutti  wrote:
> >>
> >> On 2018-04-12, Scharrer, Brianna  wrote:
> >>> Applications of basic language syntax
> >>>
> >>> Date/time string parsing
> >>>
> >>> Time stamps on data are often recorded in the standard ISO date
> >>> and time format as shown below
> >>> 1999-02-14T21:02:37 > 9:02pm on February 14, 1999
> >>>
> >>> Write code that when given a datetime string and outputs a
> >>> human readable version exactly in the format specified below.
> >>
> >> I disagree that the first version isn't human readable. It is
> >> both human readable and stores the date/time in lexicographic
> >> order, which is extremly useful for both humans and machines.
> >
> > Don???t nitpick the definition of ???human readable;??? it
> > isn???t relevant to the assignment and just serves to confuse
> > the student.  Using the phrase ???human readable??? is just a
> > poor choice for describing the assignment parameters: changing
> > from one format to another (ISO -> ???standard English??? (for
> > lack of a better description of the target format).  That???s
> > the only thing that matters in this context.
>
> It is relevant to the assignment if the student hadn't noticed
> that the date was human readable. I was hoping to correct this
> possible misapprehension resulting from the poor assignment
> language.
>
> --
> Neil Cerutti
>
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor
>



-- 
Mayo Adams

287 Erwin Rd.
Chapel Hill, NC 27514
(919)-780-3917
mayoad...@gmail.com
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] PLEASE HELP

2018-04-13 Thread Neil Cerutti
On 2018-04-13, David Rock  wrote:
>
>> On Apr 13, 2018, at 09:24, Neil Cerutti  wrote:
>> 
>> On 2018-04-12, Scharrer, Brianna  wrote:
>>> Applications of basic language syntax
>>> 
>>> Date/time string parsing
>>> 
>>> Time stamps on data are often recorded in the standard ISO date
>>> and time format as shown below
>>> 1999-02-14T21:02:37 > 9:02pm on February 14, 1999
>>> 
>>> Write code that when given a datetime string and outputs a
>>> human readable version exactly in the format specified below.
>> 
>> I disagree that the first version isn't human readable. It is
>> both human readable and stores the date/time in lexicographic
>> order, which is extremly useful for both humans and machines.
>
> Don???t nitpick the definition of ???human readable;??? it
> isn???t relevant to the assignment and just serves to confuse
> the student.  Using the phrase ???human readable??? is just a
> poor choice for describing the assignment parameters: changing
> from one format to another (ISO -> ???standard English??? (for
> lack of a better description of the target format).  That???s
> the only thing that matters in this context.

It is relevant to the assignment if the student hadn't noticed
that the date was human readable. I was hoping to correct this
possible misapprehension resulting from the poor assignment
language.

-- 
Neil Cerutti

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] PLEASE HELP

2018-04-13 Thread David Rock

> On Apr 13, 2018, at 09:24, Neil Cerutti  wrote:
> 
> On 2018-04-12, Scharrer, Brianna  wrote:
>> Applications of basic language syntax
>> 
>> Date/time string parsing
>> 
>> Time stamps on data are often recorded in the standard ISO date
>> and time format as shown below
>> 1999-02-14T21:02:37 > 9:02pm on February 14, 1999
>> 
>> Write code that when given a datetime string and outputs a
>> human readable version exactly in the format specified below.
> 
> I disagree that the first version isn't human readable. It is
> both human readable and stores the date/time in lexicographic
> order, which is extremly useful for both humans and machines.

Don’t nitpick the definition of “human readable;” it isn’t relevant to the 
assignment and just serves to confuse the student.  Using the phrase “human 
readable” is just a poor choice for describing the assignment parameters: 
changing from one format to another (ISO -> “standard English” (for lack of a 
better description of the target format).  That’s the only thing that matters 
in this context.

For the assignment, think about the following:

How to separate the date from the time
How to separate the -MM-DD into discreet variables
How to convert the digit month into a Full name (e.g, convert 2 -> February)
How to convert a 24-hour time into a 12-hour am/pm time
How to print the bits into a specific format

Tackle each part separately, and it should be fairly straightforward.  Look up 
methods for parsing formatted strings as a place to start.

— 
David Rock
da...@graniteweb.com




___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] PLEASE HELP

2018-04-13 Thread Neil Cerutti
On 2018-04-12, Scharrer, Brianna  wrote:
> Applications of basic language syntax
>
> Date/time string parsing
>
> Time stamps on data are often recorded in the standard ISO date
> and time format as shown below
>
> -mm-ddThh:mm:ss
>
> 2018-01-02T18:31:16 > 6:31pm on January 2, 2018
>
> 1999-02-14T21:02:37 > 9:02pm on February 14, 1999
>
> Write code that when given a datetime string and outputs a
> human readable version exactly in the format specified below.

I disagree that the first version isn't human readable. It is
both human readable and stores the date/time in lexicographic
order, which is extremly useful for both humans and machines.

> [Morning, Noon, Afternoon, Evening, or Night], X:XX[am or pm] on [Month as a 
> word] [day], [year]
>
> E.g. 1999-02-14T21:02:37 would be ?Night, 9:02pm on February 14, 1999?

You will need to ask for clarification from your teacher for the
deliniation between morning, noon, afternoon, evening and night.
There's no international standard I'm aware of.

>
> Do not use any datetime string function, though depending on
> your language they would be useful to do this in practice.

They certainly would!

> Hint: you?ll have to cast strings to integers in order to
> perform the if statements which place [Morning, Noon?], [am or
> pm] and [Month as a word] appropriately.

With the exception of converting string to integer (as Alan
discussed) I recommend using a dictionaries for conversion,
rather than if statements, if you're allowed.

-- 
Neil Cerutti

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] PLEASE HELP

2018-04-12 Thread Alan Gauld via Tutor
On 12/04/18 18:24, Scharrer, Brianna wrote:

What appears below seems to be an assignment of some kind.
We do not do your work for you although we will offer help.
But it is best if you show us your work so far, or at
least describe how you intend to tackle it.

In this case you are being given a string and need to
convert it to a different format. It is not clear how
you should expect to "be given" the input data but
I assume you can read it from a user?

In Python you have many string methods to help you
slice/split the input into its parts. Look at the slice
operations and the split method. Given the fixed
lengths involved here slicing is probably easiest.

The assignment suggests "casting" the string to integers
but I think this is poor terminology and what is meant
is that you should convert the substrings into integers
(casting and conversion are very different things!).

Get back to us when you have something to show us or
a specific query.

> Applications of basic language syntax
> 
> Date/time string parsing
> 
> Time stamps on data are often recorded in the standard ISO date and time 
> format as shown below
> 
> -mm-ddThh:mm:ss
> 
> 2018-01-02T18:31:16 > 6:31pm on January 2, 2018
> 
> 1999-02-14T21:02:37 > 9:02pm on February 14, 1999
> 
> 
> Write code that when given a datetime string and outputs a human readable 
> version exactly in the format specified below.
> 
> [Morning, Noon, Afternoon, Evening, or Night], X:XX[am or pm] on [Month as a 
> word] [day], [year]
> 
> E.g. 1999-02-14T21:02:37 would be “Night, 9:02pm on February 14, 1999”
> 
> Do not use any datetime string function, though depending on your language 
> they would be useful to do this in practice.
> 
> Hint: you’ll have to cast strings to integers in order to perform the if 
> statements which place [Morning, Noon…], [am or pm] and [Month as a word] 
> appropriately.



-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos


___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] please help me with after method

2016-11-17 Thread Alan Gauld via Tutor
Always use REply-All or Reply-List to the tutor list.

On 17/11/16 18:34, Freedom Peacemaker wrote:
> Thank you Alan for answer but i still cant make it. I have improved my
> program but it still uses root.update() and now my app looks
> professional :) It is my first program. I am self learning Python
> since july this year but still i need a lot of knowledge. Could you
> help me improve my app with root.after?

OK, I'll try.

> And there is problem - when im closing app with X button after using
> app it shows two windows. One with messagebox i wrote, and second
> blank new tk window. I dont know where im doing mistake, or it is
> caused by root.update maybe? Maybe with using root.after problem will
> be no more.

Maybe, but I'll need to look at the code more closely.
There are a couple of things that could cause this
Having looked, I think you need to bind the window
manager close button to root.quit Take a look at
the wm_ methods in the Tkinter docs.


>
> def displayCountdown():
> lcd = "{:02d}:{:02d}".format(*divmod(t, 60))
> timeString.set(lcd)
> setTime -= 1
> if setTime > 0:
> root.after(1000,displayCountdown)
>

Where is 't' (used in the divmod) defined? Looking below I think
it should use setTime?

Otherwise it looks like it should work. All you need to do is insert
a call to displayCountdown() in your START button event handler.


> There are problems with my app but im so proud that i wrote myself

Its rare that anything is ever perfect but the buzz of getting
something to work more or less as you want it to is always good. :-)

> import sys, time, os
> import tkinter as tk
> from tkinter import *
>

You should probably only ose one of the tkinter imports.
And the first is the preferred method for production code.

> def change_1():
> B1['state'] = tk.DISABLED
> B2['state'] = tk.NORMAL  
>
> def change_2():
> B1['state'] = tk.NORMAL
> B2['state'] = tk.DISABLED
>
> def change_3():
> B1['state'] = tk.DISABLED
> B2['state'] = tk.DISABLED


Add the displayCountdown() definition here

>
> def startCount():
> setTime = setMinutes.get() * 60
> strTime = str(setTime)
> timeSet = ("\""+"shutdown /s /f /t " +strTime+"\"")
> os.system(timeSet)
> change_1()
displayCountdown() # uses the after() method.

This removes the need for all of the code below.

> for t in range(setTime, -1, -1):
> lcd = "{:02d}:{:02d}".format(*divmod(t, 60))
> timeString.set(lcd)
> try:
> root.update()
> except TclError:
> messagebox.showinfo('Info', 'Closing app wont stop timer.')
> return
> time.sleep(1)
> return
>

The rest of your code is unchanged.
But note I haven't tested this! :-)

> def stopCount():
> passwd = "science"
> passwdGet = getPass.get()
> if passwd != passwdGet:

You could make this more secure.
You should probably do some reading about best [practice
for handling passwords. But for now it probably meets your needs.


> messagebox.showinfo('Wrong', 'It wasnt correct password')
> change_3()
> else:
> messagebox.showinfo('Good', 'Shutdown canceled')
> os.system("shutdown /a")
> change_2()
> return
>
> root = tk.Tk()
> setMinutes = IntVar()
> getPass = StringVar()
> timeString = StringVar()
> label_font = ('Verdana', 30)
> root.geometry('260x150+200+200')
> root.title('Timer v1.4')
> root.resizable(0, 0)
>
> L1 = tk.Label(root, text='How much time you have?')
> L1.grid(row=0, columnspan=3, sticky='WE')
>
> L2 = tk.Label(root, textvariable=timeString, font=label_font, bg='white',
>  fg='orange', relief='raised', bd=3)
> L2.grid(row=1, columnspan=3, sticky='WE', padx=5, pady=5)
>
> E1 = tk.Entry(root, textvariable=setMinutes, bg='lightgreen')
> E1.grid(row=2, column=1, padx=5, pady=5)
>
> B1 = tk.Button(root, text='S T A R T', fg='green', bg='black',
> command=startCount)
> B1.grid(row=2, rowspan=2, sticky='NS', column=0, padx=5, pady=5)
>
> E2 = tk.Entry(root, textvariable=getPass, bg='red')
> E2.grid(row=3, column=1, padx=5, pady=5)
>
> B2 = tk.Button(root, text='S T O P', fg='red', bg='black',
> command=stopCount,
> state=tk.DISABLED)
> B2.grid(row=2, rowspan=2, sticky='NS', column=2, padx=5, pady=5)
>
> root.mainloop()
>
>
>
> 2016-11-17 1:03 GMT+01:00 Alan Gauld via Tutor  >:
>
> On 16/11/16 18:48, Freedom Peacemaker wrote:
> > Hi, i need help. I am using Python 3.4 and I have wrote little
> app for
> > windows only ( windows 7 and higher). Its timer and my app
> working but not
> > good. Some people said that i should use after method instead of
> update()
>
> after() executes a function after a delay.
> In your case you could use it to trigger an
> immediate shutdown after the delay elapses.
> But I'm not sure that would be much better
> than doing what you are doing.
>
> The other use 

Re: [Tutor] please help me with after method

2016-11-16 Thread Alan Gauld via Tutor
On 16/11/16 18:48, Freedom Peacemaker wrote:
> Hi, i need help. I am using Python 3.4 and I have wrote little app for
> windows only ( windows 7 and higher). Its timer and my app working but not
> good. Some people said that i should use after method instead of update()

after() executes a function after a delay.
In your case you could use it to trigger an
immediate shutdown after the delay elapses.
But I'm not sure that would be much better
than doing what you are doing.

The other use of after is to avoid loops in
event handlers such as the one you have here.
This allows control to return to the GUI window.

See below...

> When you run app first enter minutes in entry then press start. If you
> first press start your pc will shutdown with no time to stop it

You can fix that by setting a default value for the time.
But you still need to write some code to cancel the shutdown
(by killing the process perhaps?)

> def startCount():
> setTime = setMinutes.get() * 60
> strTime = str(setTime)
> timeSet = ("\""+"shutdown /s /f /t " +strTime+"\"")
> os.system(timeSet)

Up to here is fine but you don't want a long running loop
inside an event handler. Although, in this case, it probably
doesn't run for long, it just counts down very quickly.

Instead you want it to count down  every second or so.

So you want to call a function that displays the time
remaining then calls after() with a delay of 1 second.
The call to after should have the same function in it.
Like so:

def displayCountdown():
# display the time here
# decrement the time by 1 second
# if any time remains:
#call after(1000,displayCountdown) # 1000ms = 1s

Note that after only needs the function name, don't
include any parentheses.

> for t in range(setTime, -1, -1):
> lcd = "{:02d}:{:02d}".format(*divmod(t, 60))
> timeString.set(lcd)
> try:
> root.update()
> except TclError:
> messagebox.showinfo('Info', 'Closing app wont stop timer.')
> return
> time.sleep(1)
> return


HTH
-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos


___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] please help me modify this code so that I can utilize raw_input

2016-10-05 Thread Oscar Benjamin
On 4 October 2016 at 19:11, Alan Gauld via Tutor  wrote:
>> """Define a function sum() and a function multiply() that sums and
>> multiplies (respectively) all the numbers in a list of numbers. For
>> example, sum([1, 2, 3, 4]) should return 10, and multiply([1, 2, 3, 4])
>> should return 24."""
>
> 
> I do wish teachers would not ask students to reinvent the wheel.

You may be misunderstanding the teacher's objectives here. Sometimes
Python is used to introduce the concept of programming more generally
rather than specifically to prepare someone for professional
programming using Python. I don't know about you but I came to Python
after a number of other programming languages. Now that I teach
programming I can see that it's important in a first programming
introduction to cover nuts and bolts type algorithmic thinking. sum()
is a good example of an algorithm that most people are already used to
performing on pen and paper making it a good candidate for learning to
use loops and functions.

> Python already has a perfectly good sum() function.

Writing your own sum function helps to understand what actually
happens when using the standard sum function. I do the same thing with
my students in C teaching them how to make their own e.g. strlen
function. I will tell them that strlen exists afterwards but I want
them to understand what the null byte is and writing your own (or just
looking at a) strlen implementation helps with that. Likewise simply
using a function e.g. strcat without understanding its implementation
can lead to segfaults so there can be a relevance in understanding the
implementation even if you don't intend to reimplement something in
your own code. The implications of the implementation of sum are also
non-trivial which is why the stdlib contains at least 3 different sum
functions.

It's great that Python comes with so many functions to do common
tasks. However from personal experience teaching Python as a first
language can lead to the disadvantage that many students become spoilt
programmers. They will learn to assume that there is a function for
exactly what they want and all they ever need to do is ask a precise
question in a search engine and read the first stackoverflow page.
That may be the correct approach for many problems but it isn't
always. A programmer should have the ability to implement basic
algorithms (e.g. sum) for themselves when necessary.

> And both problems become trivial if using functools.reduce()
> 

Different people think in different ways but I reckon most people -
and especially most beginners - would find a loop more straightforward
than reduce. I doubt that the OP is at a stage where using reduce
seems trivial.

--
Oscar
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] please help me modify this code so that I can utilize raw_input

2016-10-04 Thread Alan Gauld via Tutor
On 04/10/16 15:04, Richard Koeman wrote:
> I would like to modify this code so that instead of me calling the function
> with the list as shown [1,2,3,4], the user inputs the list with raw_input.
> 

You don't need to modify your code you just need ton write a function
that reads a list from the user. Notice that this can e done by either
repeatedly asking the user to input values until they are done or by
reading a string containing the values and converting the string to a
list of numbers.


> """Define a function sum() and a function multiply() that sums and
> multiplies (respectively) all the numbers in a list of numbers. For
> example, sum([1, 2, 3, 4]) should return 10, and multiply([1, 2, 3, 4])
> should return 24."""


I do wish teachers would not ask students to reinvent the wheel.
Python already has a perfectly good sum() function.
And both problems become trivial if using functools.reduce()


> 
> def sum(mylist = [], *args):
>   print mylist
>   sum_of_number = 0
>   for i in mylist:
> sum_of_number += i
>   print "The sum of the digits in your number is %s" %(sum_of_number)

> def multiply(mylist = [], *args):
>   product_of_number = 1
>   for i in mylist:
> product_of_number = product_of_number * i
>   print "The product of the digits in your number is %s"
> %(product_of_number)
> 
> sum([1,2,3,4])
> multiply([1,2,3,4])

Incidentally, notice that the assignment asks you to *return* the
results not print them. This is good practice, keep the printing
separate from the calculation. You can then print the result,
if you wish, with

print( sum([]) )

hth
-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos


___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Please Help to build an addon for Anki

2015-04-20 Thread Alan Gauld

On 20/04/15 09:54, Mahesh Chiramure wrote:


I liked the addon "Picture-flasher" written for anki very much
and I was wondering if the same thing could be done with mp3 and/or
flac files.


Probably, but I (and probably most of the list) have no idea what anki 
is or what the addon does. This is a list for learning Python and its 
standard library. You could try asking on the general Python 
mailinglist/newsgroup where you might find someone familiar with it.


If you do try that you sould try explaining what anki is,
and what the addon does. ie how it 'adds on'.

Better still is if you can find an anki forum, since they will 
understand anki, addons and probably be familiar with the PictureFlasher 
one you describe.



--
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos


___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] please help

2014-03-22 Thread spir

On 03/21/2014 10:39 PM, Cameron Simpson wrote:

On 21Mar2014 20:31, Mustafa Musameh  wrote:

Please help. I have been search the internet to understand how to write a 
simple program/script with python, and I did not do anything.
I have a file that look like this

ID 1

agtcgtacgt…

ID 2

acccttcc
.
.
.
in other words, it contains several IDs each one has a sequence of 'acgt' 
letters
I need to write a script in python where the output will be, for example, like 
this

ID 1

a = 10%, c = 40%,  g=40%, t = 10%

ID 2

a = 15%, c = 35%,  g=35%, t = 15%
.
.
.
(i mean the first line is the ID and the second line is the frequency of each 
letter )
How I can tell python to print the first line as it is and count characters 
starting from the second line till the beginning of the next '>' and so on


You want a loop that reads lines in pairs. Example:

   while True:
 line1 = fp.readline()
 print line1,
 line2 = fp.readline()
 ... process the line and report ...

Then to process the line, iterate over the line. Because a line is
string, and a string is a sequence of characters, you can write:

   for c in line2:
 ... collect statistics about c ...
   ... print report ...

I would collect the statistics using a dictionary to keep count of
the characters. See the dict.setdefault method; it should be helpful.


I think it would be easier to do that in 2 loops:
* first read the file line by line, building a list of pairs (id, base-sequence)
  (and on the fly check the input is correct, if needed)
* then traverse the sequences of bases to get numbers & percentages, and write 
out

d

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] please help

2014-03-22 Thread Cameron Simpson
On 22Mar2014 00:04, Mark Lawrence  wrote:
> On 21/03/2014 21:39, Cameron Simpson wrote:
> >On 21Mar2014 20:31, Mustafa Musameh  wrote:
> >
> >I would collect the statistics using a dictionary to keep count of
> >the characters. See the dict.setdefault method; it should be helpful.
> >
> 
> Delightfully old fashioned but I'd now prefer
> http://docs.python.org/3/library/collections.html#collections.Counter
> :)

Maybe, but using a dictionary is easy and Mustafa will learn more.

Cheers,
-- 
Cameron Simpson 

Do not underestimate your abilities.  That is your boss's job.
It is your job to find ways around your boss's roadblocks.
- Glen Appleby  http://www.armory.com/~glena/
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] please help

2014-03-21 Thread Mark Lawrence

On 21/03/2014 21:39, Cameron Simpson wrote:

On 21Mar2014 20:31, Mustafa Musameh  wrote:

I would collect the statistics using a dictionary to keep count of
the characters. See the dict.setdefault method; it should be helpful.



Delightfully old fashioned but I'd now prefer 
http://docs.python.org/3/library/collections.html#collections.Counter :)


--
My fellow Pythonistas, ask not what our language can do for you, ask 
what you can do for our language.


Mark Lawrence

---
This email is free from viruses and malware because avast! Antivirus protection 
is active.
http://www.avast.com


___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] please help

2014-03-21 Thread Steven D'Aprano
On Fri, Mar 21, 2014 at 08:31:07PM +1100, Mustafa Musameh wrote:

> Please help. I have been search the internet to understand how to 
> write a simple program/script with python, and I did not do anything. 
> I have a file that look like this
> >ID 1
> agtcgtacgt…
> >ID 2
> acccttcc
> .
> .
> .
> in other words, it contains several IDs each one has a sequence of 'acgt' 
> letters
> I need to write a script in python where the output will be, for example, 
> like this 
> > ID 1
> a = 10%, c = 40%,  g=40%, t = 10%
> >ID 2
> a = 15%, c = 35%,  g=35%, t = 15%
> .
> .
> .
> (i mean the first line is the ID and the second line is the frequency of each 
> letter )
> How I can tell python to print the first line as it is and count 
> characters starting from the second line till the beginning of the 
> next '>' and so on


This sounds like a homework exercise, and I have a policy of trying not 
to do homework for people. But I will show you the features you need.

Firstly, explain what you would do if you were solving this problem in 
your head. Write out the steps in English (or the language of your 
choice). Don't worry about writing code yet, you're writing instructions 
for a human being at this stage.

Those instructions might look like this:

Open a file (which file?).
Read two lines at a time.
The first line will look like ">ID 42". Print that line unchanged.
The second line will look line "gatacacagtatta...". Count how 
many "g", "a", "t", "c" letters there are, then print the
results as percentages.
Stop when there are no more lines to be read.

Now that you know what needs to be done, you can start using Python for 
it. Start off by opening a file for reading:

f = open("some file")

There are lots of ways to read the file one line at a time. Here's one 
way:

for line in f:
print(line)


But you want to read it *two* lines at a time. Here is one way:

for first_line in f:
second_line = next(f, '')
print(first_line)
print(second_line)


Here's another way:

first_line = None
while first_line != '':
first_line = f.readline()
second_line = f.readline()


Now that you have the lines, what do you do with them? Printing the 
first line is easy. How about the second?


second_line = "gatacattgacaaccggaataccgagta"

Now you need to do four things:

- count the total number of characters, ignoring the newline at the end
- count the number of g, a, t, c characters individually
- work out the percentages of the total
- print each character and its percentage


Here is one way to count the total number of characters:

count = 0
for c in second_line:
count += 1


Can you think of a better way? Do you think that maybe Python has a 
built-in command to calculate the length of a string?


Here is one way to count the number of 'g' characters:

count_of_g = 0
for c in second_line:
count_of_g += 1


(Does this look familiar?)

Can you think of another way to count characters? Hint: strings have a 
count method:

py> s = "fjejevffveejf"
py> s.count("j")
3


Now you need to calculate the percentages. Do you know how to calculate 
the percentage of a total? Hint: you'll need to divide two numbers and 
multiply by 100.

Finally, you need to print the results.


Putting all these parts together should give you a solution. Good luck! 
Write as much code as you can, and come back with any specific questions 
you may have.



-- 
Steven

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] please help

2014-03-21 Thread Cameron Simpson
On 21Mar2014 20:31, Mustafa Musameh  wrote:
> Please help. I have been search the internet to understand how to write a 
> simple program/script with python, and I did not do anything.
> I have a file that look like this
> >ID 1
> agtcgtacgt…
> >ID 2
> acccttcc
> .
> .
> .
> in other words, it contains several IDs each one has a sequence of 'acgt' 
> letters
> I need to write a script in python where the output will be, for example, 
> like this 
> > ID 1
> a = 10%, c = 40%,  g=40%, t = 10%
> >ID 2
> a = 15%, c = 35%,  g=35%, t = 15%
> .
> .
> .
> (i mean the first line is the ID and the second line is the frequency of each 
> letter )
> How I can tell python to print the first line as it is and count characters 
> starting from the second line till the beginning of the next '>' and so on

You want a loop that reads lines in pairs. Example:

  while True:
line1 = fp.readline()
print line1,
line2 = fp.readline()
... process the line and report ...

Then to process the line, iterate over the line. Because a line is
string, and a string is a sequence of characters, you can write:

  for c in line2:
... collect statistics about c ...
  ... print report ...

I would collect the statistics using a dictionary to keep count of
the characters. See the dict.setdefault method; it should be helpful.

Cheers,
-- 
Cameron Simpson 

... in '59 I ran out of brakes *four times* -- and I don't mean they didn't
work very well, I mean I had none.  Like the main oil line had sheared.  You
know, so that oil, you know, when you put your foot on the floor, the oil
just went squirting out into the atmosphere.  Things like that.  You know,
I'd always believed that Colin was close to genius in his design ability
and everything -- if he could just get over this failing of his of making
things too bloody light.  I mean, Colin's idea of a Grand Prix car was
it should win the race and, as it crossed the finishing line, it should
collapse in a heap of bits.  If it didn't do that, it was built too strongly.
- Innes Ireland
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] please help

2014-03-21 Thread Alan Gauld

On 21/03/14 09:31, Mustafa Musameh wrote:

Please help. I have been search the internet to understand how to write a

> simple program/script with python, and I did not do anything.

There are ma y tutorials on how to write Python for every level
of programmer.

What is your level? If you can already program then the official 
tutorial on the python.org web site is a good start.


https://wiki.python.org/moin/BeginnersGuide/Programmers

and

http://docs.python.org/2/tutorial/
or
http://docs.python.org/3/tutorial/

Depending on wheher you are using Pyton v2 or v3 - there are
significant differences.

If you cannot already program then this project will require quite a bit 
of work to learn the basics  before you can start to solve your problem. 
For that you should look at the list of tutors for non 
programmers(including mine as cited below).


https://wiki.python.org/moin/BeginnersGuide/NonProgrammers


I have a file that look like this

ID 1

agtcgtacgt…

ID 2

acccttcc
.


This looks like bioscience? If so there are standard
libraries available to help with processing that.
Once you understand how to write basic Python you
should probably download one of those libraries.

There is a page for bioscientists using Python here:

http://www.onlamp.com/pub/a/python/2002/10/17/biopython.html

If you try one of the tutorials and have specific questions
come back here and we can try to clarify things,

--
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.flickr.com/photos/alangauldphotos

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] please help

2014-03-21 Thread Mark Lawrence

On 21/03/2014 09:31, Mustafa Musameh wrote:

Please help. I have been search the internet to understand how to write a 
simple program/script with python, and I did not do anything.
I have a file that look like this

ID 1

agtcgtacgt…

ID 2

acccttcc
.
.
.
in other words, it contains several IDs each one has a sequence of 'acgt' 
letters
I need to write a script in python where the output will be, for example, like 
this

ID 1

a = 10%, c = 40%,  g=40%, t = 10%

ID 2

a = 15%, c = 35%,  g=35%, t = 15%
.
.
.
(i mean the first line is the ID and the second line is the frequency of each 
letter )
How I can tell python to print the first line as it is and count characters 
starting from the second line till the beginning of the next '>' and so on

Please help


Welcome :)

Start here http://docs.python.org/3/tutorial/index.html and then come 
back with specific questions about any problems that you may encounter.



--
My fellow Pythonistas, ask not what our language can do for you, ask 
what you can do for our language.


Mark Lawrence

---
This email is free from viruses and malware because avast! Antivirus protection 
is active.
http://www.avast.com


___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Please help replace Long place-names with short place-names in many files with Python

2013-09-01 Thread Joel Goldstick
On Sun, Sep 1, 2013 at 4:19 PM, mc UJI  wrote:
> Dear Pythonistas,
>
> I am totally new to Python. This means a know the basics. And by basics I
> mean the very, very basics.
>
> I have a problem with which I need help.
>
> in short, I need to:
>
> a) Open many files (in a dir) with an .html extension

Do you know how to do this?  Its not hard.  Google 'python reading all
files in a directory' to get started
> b)  Find Long name-places (Austria)
> c) Replace them by short name.places (AT)

In python strings are objects and they have the replace method  (look
here:  http://docs.python.org/2/library/string.html#string.replace)

If you figure out how to read each file into a string (see above), you
just run the string.replace method on it for each long-short country
pair.  Then write the file.

Try first to write this code.  If you apply yourself, it will take you
maybe an hour to get something working.
Then come back with your code and tell us what went wrong.


> d) In the context of the xml tags ( and
> )
>
> At length:
>
> I have many xml files containing a day of speeches at the European
> Parliament each file. Each file has some xml-label for the session metadata
> and then the speakers (MPs) interventions. These interventions consist of my
> metadata and text. I include here a sample of two speeches (Please pay
> attention to xml labels  and  country=".*?"/> ):
>
> 
>SAMPLE OF INTERVENTIONS
> 
> 
> Knapman, Roger
> 19440220
> Crediton
> NA
> male
> 
> 
> 
> 
> 
> 
> 
> UK Independence Party
> 
> 
> on behalf of the group
> 
> 
> Mr President, Mr Juncker's speech was made with
> all the passion that a civil servant is likely to raise.
> Mr Juncker, you say that the Stability and
> Growth Pact will be your top priority, but your past statements serve to
> illustrate only the inconsistencies. Whilst I acknowledge
> that you played a key role in negotiating the pact's original rules, you
> recently said that the credibility of the pact had been buried and that the
> pact was dead. Is that still your opinion?
> You also said that you have a window of
> opportunity to cut a quick deal on the EU budget, including the British
> rebate of some EUR 4 billion a year. Is that so, Mr
> Juncker? The rebate took five years to
> negotiate. If your comments are true and you can cut a
> deal by June, then Mr Blair must have agreed in principle to surrender the
> rebate. Is that the case? With whom in
> the British Government precisely are you negotiating? Will
> the British electorate know about this at the time of the British general
> election, probably in May?
> Finally, the UK Independence Party, and in
> particular my colleague Mr Farage, has drawn attention to the criminal
> activities of more than one Commissioner. More details
> will follow shortly and regularly. Are you to be tainted
> by association with them, or will you be expressing your concerns and the
> pressing need for change?
> 
> 
>
> 
> 
> Angelilli, Roberta
> 19650201
> Roma
> NA
> female
> 
> 
> 
> 
> 
> 
> 
> Alleanza nazionale
> 
> 
> on behalf of the group
> 
> 
> Mr President, the Luxembourg Presidency’s
> programme is packed with crucial issues for the future of Europe, including
> the priorities on the economic front: the Lisbon strategy, reform of the
> Stability Pact and approval of the financial perspective up to 2013.
> My first point is that it will soon be time for
> the mid-term review of the level of implementation of the Lisbon
> strategy. To give it a greater chance of success, the
> programme needs to make the individual Member States responsible for
> achieving the targets that were set. To that end, I
> consider the proposal to specify an individual at national level to be
> responsible for putting the strategy into practice to be a very useful
> idea.
> Secondly, with regard to the review of the
> Stability Pact, it has also been emphasised this morning that a reform is
> needed which can propose a more flexible interpretation of the Pact during
> times of recession, without bypassing the Maastricht criteria and without
> giving up the commitment to reduce the debt. I am also
> convinced that steps could be taken to exclude certain specific types of
> investment from the calculation of the deficit in order to give a new boost
> to Europe’s growth and competitiveness.
> Thirdly, I hope that we can really succeed in
> approving the financial perspective up to 2013 by June, so that the
> resources can be used to the full from the very beginning of the period in
> question. I especially hope that the proposals – the
> Council’s and the Commission’s proposals on those important topics – are
> adequately discussed in advance by Parliament which, let us recall, is the
> only European institution that directly represents the sovereignty of the
> people.
> Lastly, I hope that a European civil protection
> agenc

Re: [Tutor] Please Help

2013-03-22 Thread Martin A. Brown

Greetings,

 : I have the following data points.
 : data = [1,2,0,9,0,1,4]
 : I like to store in an array and print the odd-indexed points, i.e. 2, 9,1 
 : (considering index starts at 0)
 : 
 : I have written the following code which is not running:
 : 
 : import math
 : 
 : number_list = [1,2,0,9,0,1,4]
 : 
 : number_list_1 = []
 : for k in range(math.floor(float(len(number_list)/2))):
 : if (k< math.floor(float(len(number_list)/2))):
 : number_list_1[k] = number_list[k*2 + 1]
 : 
 : print 'data: ', number_list_1 

My first thought when I see the above is that you appear to be
taking a circuitous route to the market!  You must really want to
get your exercise on your journey to fetch the list of [2, 9, 1].

My second observation is that the looping over a list using the
technique you showed here (and in your prior mail) is something
that looks more like C or Java.  Looping on an list (array, or any
sort of sequence) is a bit easier here in the lands of Python.
You can simply:

  for item in list_data:
  # -- do something with item

Since you are in the lands of Python (and welcome, by the way),
the Python docs are pretty good (and not overwhelming), and
include some excellent examples, so try reading about sequences
and how to manipulate them at this online doc:

  
http://docs.python.org/2/library/stdtypes.html#sequence-types-str-unicode-list-tuple-bytearray-buffer-xrange

Anyway, I think you may benefit from seeing this solution a bit
more Pythonically, so I have offered two different solutions.

-Martin

data = number_list = [1,2,0,9,0,1,4]

# -- you call it 'number_list_1'; I will call it 'outlist'
#
outlist = []
for idx,val in enumerate(data):
print idx, val
if 0 == (idx % 2):  # -- skip even entries; do not append
continue
outlist.append(val)

print 'loop over enumerate() to get your data: ', outlist

# -- OR, given how simple your operation on the list is, consider
#learning about slicing; see the standard docs on sequences:
#
#
http://docs.python.org/2/library/stdtypes.html#sequence-types-str-unicode-list-tuple-bytearray-buffer-xrange
#

print 'slice out from your original data: ', data[1::2]

-- 
Martin A. Brown
http://linux-ip.net/
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Please Help

2013-03-22 Thread Asokan Pichai
On Fri, Mar 22, 2013 at 6:07 PM, Arijit Ukil  wrote:

> I have the following data points.
> data = [1,2,0,9,0,1,4]
> I like to store in an array and print the odd-indexed points, i.e. 2, 9,1
> (considering index starts at 0)
>
> *I have written the following code which is** not **running:*
>
> import math
>
> number_list = [1,2,0,9,0,1,4]
>
> number_list_1 = []
> for k in range(math.floor(float(len(number_list)/2))):
> if (k< math.floor(float(len(number_list)/2))):
> number_list_1[k] = number_list[k*2 + 1]
>
> print *'data: '*, number_list_1
>
> Please help
>
> Regards,
>


I would suggest that your roblems have more to do with insufficient
understanding of basic constructs, and
that you should work on them, "Learn Python the hard way" a book by Zed
Shaw is a good one.

Why do I say that? Among other things,

k< math.floor(float(len(number_list)/2))

is very poor in any language.

Asokan Pichai

The root of all superstition is that men observe when a thing hits, but not
when it misses. -- Francis Bacon
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Please Help

2013-03-22 Thread Andreas Perstinger

Please use a meaningful subject.

On 22.03.2013 13:37, Arijit Ukil wrote:

I have the following data points.
data = [1,2,0,9,0,1,4]
I like to store in an array and print the odd-indexed points, i.e. 2, 9,1
(considering index starts at 0)


You can simply slice your list:

>>> data = [1, 2, 0, 9, 0, 1, 4]
>>> number_list = data[1::2]
>>> number_list
[2, 9, 1]

See also
http://docs.python.org/3/library/stdtypes.html#common-sequence-operations

Bye, Andreas
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Please Help

2013-03-22 Thread Alan Gauld

On 22/03/13 07:24, Arijit Ukil wrote:


f = open ("digi_2.txt", "r+")
lines = f.readlines()
for line in lines:
 number_list = []
 for number in line.split(','):
 number_list.append(float(number))

s_data = []
for i in range(len(number_list)):


You hardly ever need to do this, its much simpler to just iterate over 
the list items directly:


for number in number_list:


 if number_list[i] > 5:
 s_data = number_list[i]


Note that you are overwriting your list with a single value.
You need to do what you did above and use append().


*The problem is: it is printing only the last value, not all the values.
In this case '10', **not**'9,8,6,10'.*


Because you overwrote the list each time. You need to remember to append 
data to lists not replace the list.




--
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Please Help

2013-03-22 Thread suhas bhairav
Hi Arijit,
I have modified your program a bit and it is working fine for me. Values 
greater than 5 are being printed. Here is the code:
f = open ("D:\\digi_2.txt", "r+") lines = f.readlines() number_list = [] for 
line in lines: print line  for number in line.split(','):   
   #number_list.append(float(number))  
number_list.append(int(number)) 
s_data = [] for i in number_list:   print i #if number_list[i] > 5: 
if(i>5):s_data.append(i)
for x in s_data:print 'Data val:', float(x) 


RegardsSuhas
To: tutor@python.org
From: arijit.u...@tcs.com
Date: Fri, 22 Mar 2013 12:54:01 +0530
Subject: [Tutor] Please Help

Hi,



I have another small problem. Pls help.



I have written the following code:



f = open ("digi_2.txt", "r+")

lines = f.readlines()

for line in lines:

number_list = []

for number in line.split(','):

number_list.append(float(number))



s_data = []

for i in range(len(number_list)):

if number_list[i] >
5:

s_data =
number_list[i]



print 'Data val:', s_data





The problem is: it is printing only
the last value, not all the values. In this case '10', not
'9,8,6,10'.







Regards,

Arijit Ukil

Tata Consultancy Services

Mailto: arijit.u...@tcs.com

Website: http://www.tcs.com



Experience certainty.IT Services


   Business Solutions


   Outsourcing

________








From:
Amit Saha 

To:
Arijit Ukil 

Cc:
tutor@python.org

Date:
03/21/2013 05:30 PM

Subject:
Re: [Tutor] Please Help








Hi Arijit,



On Thu, Mar 21, 2013 at 8:42 PM, Arijit Ukil 
wrote:

>

> I am new to python. I like to calculate average of the numbers by
reading

> the file 'digi_2.txt'. I have written the following code:

>

> def average(s): return sum(s) * 1.0 / len(s)

>

> f = open ("digi_2.txt", "r+")

>

> list_of_lists1 = f.readlines()

>

>

> for index in range(len(list_of_lists1)):

>

>

> tt = list_of_lists1[index]

>

> print 'Current value :', tt

>

> avg =average (tt)

>

>

> This gives an error:

>

> def average(s): return sum(s) * 1.0 / len(s)

> TypeError: unsupported operand type(s) for +: 'int' and 'str'

>

> I also attach the file i am reading.

>

>

>

> Please help to rectify.



The main issue here is that when you are reading from a file, to

Python, its all strings. And although, 'abc' + 'def' is valid, 'abc' +

5 isn't (for example). Hence, besides the fact that your average

calculation is not right, you will have to 'convert' the string to an

integer/float to do any arithmetic operation on them. (If you know C,

this is similar to typecasting). So, coming back to your program, I

will first demonstrate you a few things and then you can write the

program yourself.



If you were to break down this program into simple steps, they would be:



1. Read the lines from a file (Assume a generic case, where you have

more than one line in the file, and you have to calculate the average

for each such row)

2. Create a list of floating point numbers for each of those lines

3. And call your average function on each of these lists



You could of course do 2 & 3 together, so you create the list and call

the average function.



So, here is step 1:



with open('digi.txt','r') as f:

lines = f.readlines()



Please refer to

http://docs.python.org/2/tutorial/inputoutput.html#methods-of-file-objects

for an explanation of the advantage of using 'with'.



Now, you have *all* the lines of the file in 'lines'. Now, you want to

perform step 2 for each line in this file. Here you go:



for line in lines:

number_list = []

for number in line.split(','):

number_list.append(float(number))



 (To learn more about Python lists, see

http://effbot.org/zone/python-list.htm).
It is certainly possible to

use the index of an element to access elements from a list, but this

is more Pythonic way of doing it. To understand this better, in the

variable 'line', you will have a list of numbers on a single line. For

example: 1350696461, 448.0, 538660.0, 1350696466, 448.0. Note how they

are separated by a ',' ? To get each element, we use the split( )

function, which returns a list of the individual numbers. (See:

http://docs.python.org/2/library/stdtypes.html#str.split).
And then,

we use the .append() method to create the list. Now, you have a

number_list which is a list of floating point numbers for each line.



Now, step 2 & 3 combined:



for line in lines:

  

Re: [Tutor] Please Help

2013-03-21 Thread Dave Angel

On 03/21/2013 08:09 AM, Arijit Ukil wrote:

Thanks for the help.



You're welcome.

You replied privately, instead of including the list, so I'm forwarding 
the response so everyone can see it.  You also top-posted, so the 
context is backwards.



After running your code, I am getting the following error:

Traceback (most recent call last):
   File "C:\Documents and Settings\207564\Desktop\Imp privacy analyzer\New
Folder\test\src\test.py", line 53, in ?
 nums.append(float(numstsrings))
TypeError: float() argument must be a string or a number




Check carefully, apparently the copy/paste on your machine inserts extra 
letters.


--
DaveA
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Please Help

2013-03-21 Thread Amit Saha
Hi Arijit,

On Thu, Mar 21, 2013 at 8:42 PM, Arijit Ukil  wrote:
>
> I am new to python. I like to calculate average of the numbers by reading
> the file 'digi_2.txt'. I have written the following code:
>
> def average(s): return sum(s) * 1.0 / len(s)
>
> f = open ("digi_2.txt", "r+")
>
> list_of_lists1 = f.readlines()
>
>
> for index in range(len(list_of_lists1)):
>
>
> tt = list_of_lists1[index]
>
> print 'Current value :', tt
>
> avg =average (tt)
>
>
> This gives an error:
>
> def average(s): return sum(s) * 1.0 / len(s)
> TypeError: unsupported operand type(s) for +: 'int' and 'str'
>
> I also attach the file i am reading.
>
>
>
> Please help to rectify.

The main issue here is that when you are reading from a file, to
Python, its all strings. And although, 'abc' + 'def' is valid, 'abc' +
5 isn't (for example). Hence, besides the fact that your average
calculation is not right, you will have to 'convert' the string to an
integer/float to do any arithmetic operation on them. (If you know C,
this is similar to typecasting). So, coming back to your program, I
will first demonstrate you a few things and then you can write the
program yourself.

If you were to break down this program into simple steps, they would be:

1. Read the lines from a file (Assume a generic case, where you have
more than one line in the file, and you have to calculate the average
for each such row)
2. Create a list of floating point numbers for each of those lines
3. And call your average function on each of these lists

You could of course do 2 & 3 together, so you create the list and call
the average function.

So, here is step 1:

with open('digi.txt','r') as f:
lines = f.readlines()

Please refer to
http://docs.python.org/2/tutorial/inputoutput.html#methods-of-file-objects
for an explanation of the advantage of using 'with'.

Now, you have *all* the lines of the file in 'lines'. Now, you want to
perform step 2 for each line in this file. Here you go:

for line in lines:
number_list = []
for number in line.split(','):
number_list.append(float(number))

 (To learn more about Python lists, see
http://effbot.org/zone/python-list.htm). It is certainly possible to
use the index of an element to access elements from a list, but this
is more Pythonic way of doing it. To understand this better, in the
variable 'line', you will have a list of numbers on a single line. For
example: 1350696461, 448.0, 538660.0, 1350696466, 448.0. Note how they
are separated by a ',' ? To get each element, we use the split( )
function, which returns a list of the individual numbers. (See:
http://docs.python.org/2/library/stdtypes.html#str.split). And then,
we use the .append() method to create the list. Now, you have a
number_list which is a list of floating point numbers for each line.

Now, step 2 & 3 combined:

for line in lines:
number_list = []
for number in line.split(','):
number_list.append(float(number))
print average(number_list)

Where average( ) is defined as:

def average(num_list):
return sum(num_list)/len(num_list)



There may be a number of unknown things I may have talked about, but i
hope the links will help you learn more and write your program now.

Good Luck.
-Amit.


--
http://amitsaha.github.com/
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Please Help

2013-03-21 Thread Dave Angel

On 03/21/2013 06:42 AM, Arijit Ukil wrote:

I am new to python.


Since you're new to Python, I won't try to supply you an answer using 
list comprehensions, since you've probably not learned them yet.




I like to calculate average of the numbers by reading
the file 'digi_2.txt'. I have written the following code:

def average(s): return sum(s) * 1.0 / len(s)


This function presumably expects to be passed a list (or iterable) of 
ints or a list of floats as its argument.  It'll fail if given a list of 
strings.  A comment or docstring to that effect would be useful to 
remind yourself.




f = open ("digi_2.txt", "r+")


Why is there a "plus sign" in the mode string?  Not necessary, since 
you're just going to read the file straight through.




list_of_lists1 = f.readlines()



Not a good name, since that's not what readlines() returns.  It'll 
return a list of strings, each string representing one line of the file.




for index in range(len(list_of_lists1)):


Since your file is only one line long, this loop doesn't do much.




 tt = list_of_lists1[index]

 print 'Current value :', tt



At this point, It is the string read from the last line of the file. 
The other lines are not represented in any way.



avg =average (tt)


This gives an error:

def average(s): return sum(s) * 1.0 / len(s)
TypeError: unsupported operand type(s) for +: 'int' and 'str'

I also attach the file i am reading.

You shouldn't assume everyone can read the "attached" data.  Since it's 
short, you should just include it in your message.  It's MUCH shorter 
than all the irrelevant data you included at the end of your message.


For those others who may be reading this portion of the hijacked thread, 
here's the one line in digi_2.txt


1350696461, 448.0, 538660.0, 1350696466, 448.0


Now to try to solve the problem.  First, you don't specify what the 
numbers in the file will look like.  Looking at your code, I naturally 
assumed you had one value per line.  Instead I see a single line with 
multiple numbers separated by commas.


I'll assume that the data will always be in a single line, or that if 
there are multiple lines, every line but the last will end with a comma, 
and that the last one will NOT have a trailing comma.  If I don't assume 
something, the problem can't be solved.



Since we don't care about newlines, we can read the whole file into one 
string, with the read() function.



f = open ("digi_2.txt", "r")
filedata = f.read()
f.close()

Now we have to separate the data by the commas.

numstsrings = filedata.split(",")

And now we have to convert each of these "numstring" values from a 
string into a float.


nums = []
for numstring in numstrings:
nums.append(float(numstring))

Now we can call the average function, since we have a list of floats.

avg = average(nums)

Completely untested, so there may be typos in it.





--
DaveA
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Please Help

2013-03-21 Thread Sven
Please trim unrelated text from emails.

On 21 March 2013 10:42, Arijit Ukil  wrote:

> I am new to python. I like to calculate average of the numbers by reading
> the file 'digi_2.txt'. I have written the following code:
>
> def average(s): return sum(s) * 1.0 / len(s)
>
> f = open ("digi_2.txt", "r+")
>
> list_of_lists1 = f.readlines()
>
>
> for index in range(len(list_of_lists1)):
>
>
> tt = list_of_lists1[index]
>
> print 'Current value :', tt
>
> avg =average (tt)
>
>
> This gives an error:
>
> def average(s): return sum(s) * 1.0 / len(s)
> TypeError: unsupported operand type(s) for +: 'int' and 'str'
>

tt is a string as it's read from the file. int(tt) would fix the problem.
But in addition you're also not actually calculating the average.


def average(s):
return sum(s) / len(s)


# convert the list of strings to a list of floats
tt = [float(x) for x in list_of_lists1]

avg = average(tt)

 --
./Sven
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Please help

2013-01-01 Thread Asokan Pichai
I saw the code;

I see too many formatting errors:
Line No 24 starts a function definition and the
next few lines are indented by two spaces, but
Line 29 is a print statement that is in line with
the def; IOW it completes the function. It is
very likely wrong.

You are defining functions within functions;
again it is very likely to be wrong.

My advice, look at PEP 8 and also some
sample python code in the tutorial to
understand how to format code. Remember:
Leading whitespace is syntactically significant

HTH


Asokan Pichai

Religion offers hope against all the strife and misery of
the world caused by religions.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Please help

2013-01-01 Thread Jack Little
Maybe tomorrow I can just email you the code

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Please help

2013-01-01 Thread Steven D'Aprano

On 02/01/13 13:02, Jack Little wrote:

I do not understand my error (it says something about an out-of-function return 
on line 179)


You cannot use "return" unless it is inside a function.

# This is okay.
def test():
print "test"
return "testing complete"  # indented, therefore inside the function


# this is not okay
def test():
print "test"
return "testing complete"  # not indented, therefore not inside the function



--
Steven
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Please help

2013-01-01 Thread Ryan Macy

Jack Little wrote:


I do not understand my error (it says something about an
out-of-function return on line 179)
my code is at the link
http://www.mediafire.com/download.php?4ga0weu4ifc6s1u
___
Tutor maillist - Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor



I'd like to help, but I'm not going to download anything from that site.

Can you instead post it on gist.github.com or bpaste.com?

_Ryan
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] please help - stuck for hours

2011-11-17 Thread Alan Gauld

On 17/11/11 23:12, ADRIAN KELLY wrote:

i know i should use input but when i changed to raw_input

In Python v3 use input()

In python v2 input() is dangerous, use raw_input() instead.


> ... it wouldn't recognise the word print on the next line.

Show us the exact code and error. You may be missing
a parenthesis, or maybe you are just expecting the wrong
behaviour... It won't execute the print until after it
has read your input.


everything to get this working..
i am 6 hrs at one program


Heh, I've got one I've been working on for over 10 years,
6 hours is nothing! :-)


--
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] please help - stuck for hours

2011-11-17 Thread ADRIAN KELLY

i know i should use input but when i changed to raw_input it wouldn't recognise 
the word print on the next line. honestly i have tried everything to get this 
working..i am 6 hrs at one program


 

  

Adrian Kelly 
1 Bramble Close

Baylough

Athlone

County Westmeath

0879495663


From: waynejwer...@gmail.com
Date: Thu, 17 Nov 2011 16:53:59 -0600
Subject: Re: [Tutor] please help - stuck for hours
To: kellyadr...@hotmail.com
CC: tutor@python.org

On Thu, Nov 17, 2011 at 4:32 PM, ADRIAN KELLY  wrote:








thanks very much, great response really really appreciated it and now i 
understand. i hate to ask again but can you see why it won't print the  'enter 
and amount over 50' in the right place??


Computers are unfailingly stupid machines. They will do whatever wrong thing 
you tell them to do every single time. 

 def main():amount=0while amount<50:amount = input('how 
much do you want to change:')

print 'enter an amount over €50: 'else:
total=exchange(amount)print 'Your exchange comes to: ',total


Sometimes it helps writing out the logic in steps before you translate it to 
code. In this case my guess is that these are the steps you want:
  1. Get a value from the user (you're still using input - stop that, it's 
dangerous! input is   only a good function in 3.x where it replaces raw_input)

   2. If the value is less than 50, tell the user to enter an amount > 50 and 
repeat step 1
  3. Otherwise, exchange the amount and display that.
Right now, these are the steps that you're doing:


  1. Get a value from the user
  2. Display the error message
  3. If the value is < 50, go to 1
  4. exchange the amount


  5. display the amount.
HTH,Wayne ___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] please help - stuck for hours

2011-11-17 Thread Wayne Werner
On Thu, Nov 17, 2011 at 4:32 PM, ADRIAN KELLY wrote:

>
> thanks very much, great response really really appreciated it and now i
> understand. i hate to ask again but can you see why it won't print the
>  'enter and amount over 50' in the right place??
>

Computers are unfailingly stupid machines. They will do whatever wrong
thing you tell them to do every single time.


>  
> def main():
> amount=0
> while amount<50:
> amount = input('how much do you want to change:')
> print 'enter an amount over €50: '
> else:
> total=exchange(amount)
> print 'Your exchange comes to: ',total
>

Sometimes it helps writing out the logic in steps before you translate it
to code. In this case my guess is that these are the steps you want:

  1. Get a value from the user (you're still using input - stop that, it's
dangerous! input is   only a good function in 3.x where it replaces
raw_input)

  2. If the value is less than 50, tell the user to enter an amount > 50
and repeat step 1

  3. Otherwise, exchange the amount and display that.

Right now, these are the steps that you're doing:

  1. Get a value from the user

  2. Display the error message

  3. If the value is < 50, go to 1

  4. exchange the amount

  5. display the amount.

HTH,
Wayne
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] please help - stuck for hours

2011-11-17 Thread ADRIAN KELLY


thanks very much, great response really really appreciated it and now i 
understand. i hate to ask again but can you see why it won't print the  'enter 
and amount over 50' in the right place?? 

  # -*- coding: cp1252 -*-def exchange(cash_in):euro=1dollar=1.35
base=50if cash_in>base:totalreturn=cash_in*dollarelse:
totalreturn=0return totalreturn

def main():amount=0while amount<50:amount = input('how much do 
you want to change:')print 'enter an amount over €50: 'else:
total=exchange(amount)print 'Your exchange comes to: ',total  main()

Adrian Kelly 
1 Bramble Close

Baylough

Athlone

County Westmeath

0879495663


From: waynejwer...@gmail.com
Date: Thu, 17 Nov 2011 15:35:29 -0600
Subject: Re: [Tutor] please help - stuck for hours
To: kellyadr...@hotmail.com
CC: tutor@python.org

On Thu, Nov 17, 2011 at 3:19 PM, ADRIAN KELLY  wrote:







i have tried everything, i am trying to build in a loop to my 2 functions which 
worked fine up until my latest sorti.
please have a look if you can..



def exchange(cash_in):euro=1dollar=1.35

base=50if cash_in>base:totalreturn=cash_in*dollar

else:totalreturn=0return totalreturn



def main():

amount=""while amount<50:print 'Sorry, cannot convert an amount 
under €50 '

amount = input('how much do you want to change:')else:

total=exchange(amount)print 'Your exchange comes to: ',total

  main()


 
Traceback (most recent call last):

  File "F:\VTOS ATHLONE\PYTHON_VTOS\foreign exchange\f_ex3.py", line 27, in 
main()  File "F:\VTOS ATHLONE\PYTHON_VTOS\foreign 
exchange\f_ex3.py", line 19, in main

total=exchange(amount)  File "F:\VTOS ATHLONE\PYTHON_VTOS\foreign 
exchange\f_ex3.py", line 7, in exchangetotalreturn=cash_in*dollar

TypeError: can't multiply sequence by non-int of type 'float'
Thank you for posting the full traceback - this last line tells you the exact 
problem - you're trying to multiply a sequence by a float (in this case your 
sequence is a string). The line right above that tells you the what you tried 
to do: multiply `cash_in` by `dollar`.


Take a look at your code and what do you see? Well, you set `dollar = 1.35`, 
and you don't change the value elsewhere so that's certainly a float. What 
about cash_in? Well if you work your way backwards through the traceback you 
see that it was called with the parameter "amount".


Where is amount set? Ah, on that line:
amount = input()
This line is extremely problematic. First, I see by your print statement that 
you're using  Python 2.x, so input is actually executing arbitrary code. What 
you *want* is raw_input which returns a string and is much MUCH safer.


I don't know what your input value was, but I suspect that you did something 
like '30' (with the quotes), because otherwise it would evaluate to an integer. 
It's also possible that you used `amount`, which would evaluate to "" since you 
already declared it. None of these things are good.


Change your initial assignment to :
amount = 0
and the input line to:
amount = float(raw_input("How much would you like to exchange? "))


This will first get a string from the user and then convert it to a float - 
which I suspect you'll want, since you're dealing with monetary 
values.HTH,Wayne  ___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] please help - stuck for hours

2011-11-17 Thread delegbede
Where do you intend the variable cash_in to come from?

The system doesn't know what cash_in is beyond that you mentioned it and that 
makes it impossible to multiply it with dollar which is a float type. 

If cash_in is supposed to be an input from the user, you probably should make 
it an int type right away before doing the multiplication. 

Hope this helps. 

Cheers. 
Sent from my BlackBerry wireless device from MTN

-Original Message-
From: ADRIAN KELLY 
Sender: tutor-bounces+delegbede=dudupay@python.org
Date: Thu, 17 Nov 2011 21:19:45 
To: 
Subject: [Tutor] please help - stuck for hours

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] please help - stuck for hours

2011-11-17 Thread Wayne Werner
On Thu, Nov 17, 2011 at 3:19 PM, ADRIAN KELLY wrote:

>  i have tried everything, i am trying to build in a loop to my 2 functions
> which worked fine up until my latest sorti.
>
> please have a look if you can..
>
> def exchange(cash_in):
> euro=1
> dollar=1.35
> base=50
> if cash_in>base:
> totalreturn=cash_in*dollar
> else:
> totalreturn=0
> return totalreturn
>
>
> def main():
> amount=""
> while amount<50:
> print 'Sorry, cannot convert an amount under €50 '
> amount = input('how much do you want to change:')
> else:
> total=exchange(amount)
> print 'Your exchange comes to: ',total
>
>
> main()
>
>
>
> Traceback (most recent call last):
>   File "F:\VTOS ATHLONE\PYTHON_VTOS\foreign exchange\f_ex3.py", line 27,
> in 
> main()
>   File "F:\VTOS ATHLONE\PYTHON_VTOS\foreign exchange\f_ex3.py", line 19,
> in main
> total=exchange(amount)
>   File "F:\VTOS ATHLONE\PYTHON_VTOS\foreign exchange\f_ex3.py", line 7, in
> exchange
> totalreturn=cash_in*dollar
> TypeError: can't multiply sequence by non-int of type 'float'
>

Thank you for posting the full traceback - this last line tells you the
exact problem - you're trying to multiply a sequence by a float (in this
case your sequence is a string). The line right above that tells you the
what you tried to do: multiply `cash_in` by `dollar`.

Take a look at your code and what do you see? Well, you set `dollar =
1.35`, and you don't change the value elsewhere so that's certainly a
float. What about cash_in? Well if you work your way backwards through the
traceback you see that it was called with the parameter "amount".

Where is amount set? Ah, on that line:

amount = input()

This line is extremely problematic. First, I see by your print statement
that you're using  Python 2.x, so input is actually executing arbitrary
code. What you *want* is raw_input which returns a string and is much MUCH
safer.

I don't know what your input value was, but I suspect that you did
something like '30' (with the quotes), because otherwise it would evaluate
to an integer. It's also possible that you used `amount`, which would
evaluate to "" since you already declared it. None of these things are good.

Change your initial assignment to :

amount = 0

and the input line to:

amount = float(raw_input("How much would you like to exchange? "))

This will first get a string from the user and then convert it to a float -
which I suspect you'll want, since you're dealing with monetary values.
HTH,
Wayne
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Please help understanding unittest fixtures

2011-08-22 Thread Peter Otten
Steven D'Aprano wrote:

> D. Guandalino wrote:

>> In this case is there a
>> way to force just one setUp() call?
> 
> 
> I don't know if this is the best way, but the first way that comes to
> mind is this:
> 
> 
> class C(TestCase):
>  initialised = False
>  def setUp(self):
>  if self.initialised:
>  return
>  # Make sure you save the flag on the class, not the instance!
>  self.__class__.initialised = True
>  ...

Python 2.7 and 3.2 support setUpClass()/tearDownClass() classmethods, see

http://docs.python.org/library/unittest.html#unittest.TestCase.setUpClass

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Please help understanding unittest fixtures

2011-08-21 Thread Steven D'Aprano

D. Guandalino wrote:

Suppose I have this TestCase class.

class C(TestCase):
   def setUp():
  # very time consuming and resources intensive stuffs.
  pass

   def test_A(self):
   pass
   def test_B(self):
   pass
   def test_C(self):
   pass

The unittest docs says:


Each instance of the TestCase will only be used to run a single test
method, so a new fixture is created for each test.



Does this mean that the setUp() method, which is called to prepare the test
fixture, get called for test_A, test_B and test_C? 


That's easy enough to find out:

def setUp(self):
print("calling setUp")
...


See how many times "calling setUp" is printed.



In this case is there a
way to force just one setUp() call?



I don't know if this is the best way, but the first way that comes to 
mind is this:



class C(TestCase):
initialised = False
def setUp(self):
if self.initialised:
return
# Make sure you save the flag on the class, not the instance!
self.__class__.initialised = True
...


--
Steven

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Please help, the program is not behaving as I want

2011-05-17 Thread Prasad, Ramit
Start solving the problem by viewing the text around what is being returned. 
Look at the +- 10-100 characters from what is being returned.

Where exactly on the page is the return coming from? Is this centered near 
where you expected it? If not, what could be causing that? If it is actually 
close (and not just an error that is returning something that looks close but 
is actually not related) to what you want then why are the boundaries for the 
slice not what you expect? Play around with the boundaries and see if you can 
get it closer. Goldstein's second email has narrowed down some of your 
problems, if you cannot find it.

Since you are doing text matches, be careful of case. What if WAter is typed 
instead of Water or water (as Andre noted) is typed?


Ramit



Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology
712 Main Street | Houston, TX 77002
work phone: 713 - 216 - 5423

From: tutor-bounces+ramit.prasad=jpmchase@python.org 
[mailto:tutor-bounces+ramit.prasad=jpmchase@python.org] On Behalf Of I. 
Dooba
Sent: Tuesday, May 17, 2011 11:54 AM
To: tutor@python.org
Subject: Re: [Tutor] Please help, the program is not behaving as I want

Thanks, Joel Goldstick

There is no error message.
But the program is returning incomplete or too many characters.  For example, 
instead of "Halal" it will return "l Hala"
or "nol" depending on the length of the word the user inputs.

Since I can't predict the words the user will search for, I'm finding it 
difficult to tackle the problem.
___
I. Dooba
Hybrid Intelligence & Digital Infrastructure Research Group
Universiti Teknologi PETRONAS
+6014 644 5086
ibraheem_g01...@utp.edu.my<mailto:ibraheem_g01...@utp.edu.my>



This communication is for informational purposes only. It is not
intended as an offer or solicitation for the purchase or sale of
any financial instrument or as an official confirmation of any
transaction. All market prices, data and other information are not
warranted as to completeness or accuracy and are subject to change
without notice. Any comments or statements made herein do not
necessarily reflect those of JPMorgan Chase & Co., its subsidiaries
and affiliates.

This transmission may contain information that is privileged,
confidential, legally privileged, and/or exempt from disclosure
under applicable law. If you are not the intended recipient, you
are hereby notified that any disclosure, copying, distribution, or
use of the information contained herein (including any reliance
thereon) is STRICTLY PROHIBITED. Although this transmission and any
attachments are believed to be free of any virus or other defect
that might affect any computer system into which it is received and
opened, it is the responsibility of the recipient to ensure that it
is virus free and no responsibility is accepted by JPMorgan Chase &
Co., its subsidiaries and affiliates, as applicable, for any loss
or damage arising in any way from its use. If you received this
transmission in error, please immediately contact the sender and
destroy the material in its entirety, whether in electronic or hard
copy format. Thank you.

Please refer to http://www.jpmorgan.com/pages/disclosures for
disclosures relating to European legal entities.___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Please help, the program is not behaving as I want

2011-05-17 Thread Joel Goldstick
On Tue, May 17, 2011 at 12:54 PM, I. Dooba  wrote:

> Thanks, Joel Goldstick
>
> There is no error message.
> But the program is returning incomplete or too many characters.  For
> example, instead of "Halal" it will return "l Hala"
> or "nol" depending on the length of the word the user inputs.
>
> Since I can't predict the words the user will search for, I'm finding it
> difficult to tackle the problem.
> ___
> I. Dooba
> Hybrid Intelligence & Digital Infrastructure Research Group
> Universiti Teknologi PETRONAS
> +6014 644 5086
> ibraheem_g01...@utp.edu.my
>
>
> I haven't read the book you are using, so I don't know what lessons they
are trying to teach in this example.  However, you should be aware that if
you read the input into a variable first, then do the .find() method
separately on the next line, you can later find out how long the word your
user typed (google python length of string if you don't know how).  Use this
length value to add to the start of your index so that you can start your
result at the beginning of Halal or Haram.  Then at least, if the word is in
your list you will get the answer you expect.

> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
>


-- 
Joel Goldstick
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Please help, the program is not behaving as I want

2011-05-17 Thread I. Dooba
Thanks, Joel Goldstick

There is no error message.
But the program is returning incomplete or too many characters.  For
example, instead of "Halal" it will return "l Hala"
or "nol" depending on the length of the word the user inputs.

Since I can't predict the words the user will search for, I'm finding it
difficult to tackle the problem.
___
I. Dooba
Hybrid Intelligence & Digital Infrastructure Research Group
Universiti Teknologi PETRONAS
+6014 644 5086
ibraheem_g01...@utp.edu.my
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Please help, the program is not behaving as I want

2011-05-17 Thread Joel Goldstick
On Tue, May 17, 2011 at 11:20 AM, I. Dooba  wrote:

> I'm new to programming and have decided to start with Python following the
> advice of experts including Eric S. Raymond.
> So far I've learnt quite a lot from this list.
>
> However, I've the following problem.
>
> The program was designed (as part of my practice with Head First
> Programming) to check whether an ingredient is Halal or Haram.
> I've a simple table online where some ingredients are either halal or
>  haram.
>

You don't have a simple table in this webpage.  You should use 'View Source"
from your browser to actually see what your program is reading.  What you do
have quite far down are words like this between  tags:

 
 
Water Halal
Ethanol Halal
Blood Haram
Alcohol Haram
Benzoic Acid Halal



>
> For example, if the user enters "water" the program is supposed to tell him
> that it's halal;
> but it's returning ">" and other characters I don't want to see.
>
> What am I doing wrong?
>
> import urllib.request
>
> this gets access to  the webpage

> page = urllib.request.urlopen("
> http://halalingredients.theparleyonline.com/";)
>

this reads the whole page into your text variable

> text = page.read().decode("utf8")
>
>
this lets you type in a word, and uses that word to see if it can find it in
the text.  If it does, it returns the index where it finds the start of the
word

> halal_haram_status = text.find(input("Enter the ingredient:  "))
>

if it can't find a match it will return -1

This is strange.  I believe you want to add the length of the word you input
plus 1 (for the space) to the index you found above.

> begin_final_status = halal_haram_status + 3
>

This is ok since halal and haram are both 5 characters long

> end_final_status = begin_final_status + 5
> status = text[begin_final_status:end_final_status]
> print(status)
>
>
>
Be careful to type the word exactly as printed.  If you the a word that is
not in your list, you might get what looks like nonsense since it will just
look to the 5 characters after the word you give it to find

> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
> Since I'm on my lunch break I thought I'd dig into this


-- 
Joel Goldstick
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Please help, the program is not behaving as I want

2011-05-17 Thread Andre Engels
I am not able to check your code (I get an error message about the
usage of urllib, but that might be a difference in Python
installations); however, my first guess is that you neglected to take
case into account: The page contains the text "Water", not "water", so
if you input "water", halal_haram_status will be -1.

As another remark, find() will give the value of the _beginning_ of
the match, thus when all goes right, what is returned will contain
part of the text sought rather than "Halal" or "Haram" - you will get
"er Ha" for water, "anol " for ethanol and "k cho" for pork chops
(also, ethanol is the same as alcohol, so I guess it should be haram).

On Tue, May 17, 2011 at 5:20 PM, I. Dooba  wrote:
> I'm new to programming and have decided to start with Python following the
> advice of experts including Eric S. Raymond.
> So far I've learnt quite a lot from this list.
> However, I've the following problem.
> The program was designed (as part of my practice with Head First
> Programming) to check whether an ingredient is Halal or Haram.
> I've a simple table online where some ingredients are either halal or
>  haram.
> For example, if the user enters "water" the program is supposed to tell him
> that it's halal;
> but it's returning ">" and other characters I don't want to see.
> What am I doing wrong?
> import urllib.request
> page =
> urllib.request.urlopen("http://halalingredients.theparleyonline.com/";)
> text = page.read().decode("utf8")
>
> halal_haram_status = text.find(input("Enter the ingredient:  "))
> begin_final_status = halal_haram_status + 3
> end_final_status = begin_final_status + 5
> status = text[begin_final_status:end_final_status]
> print(status)
>
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
>



-- 
André Engels, andreeng...@gmail.com
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Please help, the program is not behaving as I want

2011-05-17 Thread Joel Goldstick
On Tue, May 17, 2011 at 11:20 AM, I. Dooba  wrote:

> I'm new to programming and have decided to start with Python following the
> advice of experts including Eric S. Raymond.
> So far I've learnt quite a lot from this list.
>
> However, I've the following problem.
>
> The program was designed (as part of my practice with Head First
> Programming) to check whether an ingredient is Halal or Haram.
> I've a simple table online where some ingredients are either halal or
>  haram.
>
> For example, if the user enters "water" the program is supposed to tell him
> that it's halal;
> but it's returning ">" and other characters I don't want to see.
>
> What am I doing wrong?
>
> import urllib.request
>
> page = urllib.request.urlopen("
> http://halalingredients.theparleyonline.com/";)
> text = page.read().decode("utf8")
>
> halal_haram_status = text.find(input("Enter the ingredient:  "))
> begin_final_status = halal_haram_status + 3
> end_final_status = begin_final_status + 5
> status = text[begin_final_status:end_final_status]
> print(status)
>
>
> __


Can you copy and paste the error message traceback that you get?

> _
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
>


-- 
Joel Goldstick
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] please help me

2010-01-30 Thread Luke Paireepinart
[snip homework]

>
>
> please help me
>
>
This is a tutor mailing list.  Tutor means we will help you learn, not that
we will write your homework assignments for you for free.  That is the
opposite of learning.

Try all of the programs.  Give us what you have tried and what didn't work,
why you thought it would work, why you think it didn't work, and anything
else helpful (eg. if you get an error message include the whole traceback,
don't paraphrase it.)

In other words, if you don't have code that you've tried and a specific
problem you're having, you're not going to get a reply.  We're busy people,
make it easy for us to help you.

-Luke
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] please help me

2009-06-18 Thread Emile van Sebille

On 6/18/2009 1:30 AM suzee Eslam said...

to every one help me please ..
i need the code to do chatting by python in mobiles over bluetooth 
technology .. i need it please if any one know it send it to me as soon 
as possible..

thanks for all.


Maybe this will get you started...

http://www.mobilenin.com/mobilepythonbook/examples/057-btchat.html

Emile

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] please help with sqlite replace function

2008-11-07 Thread Alan Gauld


"aivars" <[EMAIL PROTECTED]> wrote


Please try what sqlite3.version shows on your machine?


I also have ActiveState's python (mainly for its very good doc) and 
I get:

>>> import sqlite3
sqlite3.sqlite_version

'3.3.4'


Me too with Python 2.5.1 from Activestate.

Alan G 



___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] please help with sqlite replace function

2008-11-07 Thread aivars
Hello, Denis,

Please try what sqlite3.version shows on your machine?

Thanks

aivars


2008/11/7 spir <[EMAIL PROTECTED]>:
> aivars a écrit :
>>
>> Thanks, John,
>> Yes it seems you are right. The ActiveState python version I have
>> installed have sqlite 2.3.2 only. I find it strange.
>
> I also have ActiveState's python (mainly for its very good doc) and I get:
 >>> import sqlite3
 sqlite3.sqlite_version
> '3.3.4'
>
> Denis
>
>
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] please help with sqlite replace function

2008-11-07 Thread Alan Gauld


"aivars" <[EMAIL PROTECTED]> wrote


Yes it seems you are right. The ActiveState python version I have
installed have sqlite 2.3.2 only. I find it strange.


Why? SQLite is a separate product. Python bundled the then
current version in its standard distribution, but time has moved on.
You have apparently installed a more recent version of SQLite.


I see that on a python website there is is a new version Python26


2.6 may or may not have the same version as you but regardless
you should be able to get the older version of Python to work
with the newer SQLite instal;l, provided the newer version has
a Python library available - which it usually has.


Mark Hammonds PythonWin to get other things for windows? Or maybe I
will reinstall ActiveState Python25 and install Python25 from the
official website


I don't thing the vanilla Python will make any difference. SQLite is
bundled with Python not with ActiveState.


Copying dll to c:\python25\DLLs directory did not help - it still
shows version sqlite version 2.3.2. which I also do not understand 
why


I think you might need to install more than the DLL. Check
the SQLite web site for a new Ptython interface and install
that version.

Alan G. 



___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] please help with sqlite replace function

2008-11-06 Thread aivars
John, just to add to my previous post.

after copying sqlite3.dll (3.6.2) version into Python25\DLLs directory
and running

import sqlite3
dir(sqlite3)

>>> sqlite3.version
'2.3.2'

>>> sqlite3.version_info
(2, 3, 2)

>>> sqlite3.sqlite_version_info
(3, 6, 2)

>>> sqlite3.sqlite_version
'3.6.2'

and now my scrip happily runs with sqlite replace function.

I am just curious why there are so many different version properties
and why now they differ from sqlite3.version?
Of course it seems Python now is running sqlite version 3.6.2 since my
script accepts replace function

Thanks,
Aivars



2008/11/7 aivars <[EMAIL PROTECTED]>:
> Thanks, John,
> Yes it seems you are right. The ActiveState python version I have
> installed have sqlite 2.3.2 only. I find it strange.
> I see that on a python website there is is a new version Python26
> relesed. Should i go on and install Python26? I understand that I can
> install pure Python from python website and after that I can install
> Mark Hammonds PythonWin to get other things for windows? Or maybe I
> will reinstall ActiveState Python25 and install Python25 from the
> official website
>
> Copying dll to c:\python25\DLLs directory did not help - it still
> shows version sqlite version 2.3.2. which I also do not understand why
>
> Re user defined function - it is one of the ways to go probably
> quickest but I would like to have newer version of sqlite being
> already with python
>
> I am noob in Python still
>
> Thanks for your input
>
> Aivars
>
>
>
> 2008/11/6 John Fouhy <[EMAIL PROTECTED]>:
>> 2008/11/7 aivars <[EMAIL PROTECTED]>:
>>> I use python 2.5.2.2 (activestate), WinXP, sqlite version 3.6.2
>>
>> Hi Aivars,
>>
>> I believe python has its own built-in sqlite, rather than using the
>> version you installed independently.  So it is possible that the
>> python version of sqlite is older than 3.6.2 and does not yet have the
>> replace() function.
>>
>> (run 'import sqlite3' and then examine 'sqlite3.sqlite_version' to see
>> what version you are using)
>>
>> You could try replacing sqlite3.dll in your python25\dlls directory
>> with the DLL from your sqlite installation (make a backup first :-) ).
>>  Alternatively, you could define the replace() function in python and
>> then add it to your database: see
>> http://www.initd.org/pub/software/pysqlite/doc/usage-guide.html#creating-user-defined-functions
>> .
>>
>> HTH.
>>
>> --
>> John.
>>
>
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] please help with sqlite replace function

2008-11-06 Thread aivars
Thanks, John,
Yes it seems you are right. The ActiveState python version I have
installed have sqlite 2.3.2 only. I find it strange.
I see that on a python website there is is a new version Python26
relesed. Should i go on and install Python26? I understand that I can
install pure Python from python website and after that I can install
Mark Hammonds PythonWin to get other things for windows? Or maybe I
will reinstall ActiveState Python25 and install Python25 from the
official website

Copying dll to c:\python25\DLLs directory did not help - it still
shows version sqlite version 2.3.2. which I also do not understand why

Re user defined function - it is one of the ways to go probably
quickest but I would like to have newer version of sqlite being
already with python

I am noob in Python still

Thanks for your input

Aivars



2008/11/6 John Fouhy <[EMAIL PROTECTED]>:
> 2008/11/7 aivars <[EMAIL PROTECTED]>:
>> I use python 2.5.2.2 (activestate), WinXP, sqlite version 3.6.2
>
> Hi Aivars,
>
> I believe python has its own built-in sqlite, rather than using the
> version you installed independently.  So it is possible that the
> python version of sqlite is older than 3.6.2 and does not yet have the
> replace() function.
>
> (run 'import sqlite3' and then examine 'sqlite3.sqlite_version' to see
> what version you are using)
>
> You could try replacing sqlite3.dll in your python25\dlls directory
> with the DLL from your sqlite installation (make a backup first :-) ).
>  Alternatively, you could define the replace() function in python and
> then add it to your database: see
> http://www.initd.org/pub/software/pysqlite/doc/usage-guide.html#creating-user-defined-functions
> .
>
> HTH.
>
> --
> John.
>
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] please help with sqlite replace function

2008-11-06 Thread John Fouhy
2008/11/7 aivars <[EMAIL PROTECTED]>:
> I use python 2.5.2.2 (activestate), WinXP, sqlite version 3.6.2

Hi Aivars,

I believe python has its own built-in sqlite, rather than using the
version you installed independently.  So it is possible that the
python version of sqlite is older than 3.6.2 and does not yet have the
replace() function.

(run 'import sqlite3' and then examine 'sqlite3.sqlite_version' to see
what version you are using)

You could try replacing sqlite3.dll in your python25\dlls directory
with the DLL from your sqlite installation (make a backup first :-) ).
 Alternatively, you could define the replace() function in python and
then add it to your database: see
http://www.initd.org/pub/software/pysqlite/doc/usage-guide.html#creating-user-defined-functions
.

HTH.

-- 
John.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] please help with simple python CGI script

2008-10-26 Thread Steve Willoughby

aivars wrote:

Hello, Lie,
I renamed the directory back to Cgi-bin and the scripts are NOT
working. Going back to cgi-bin it works. I also do not understand why.

Aivars

2008/10/26 Lie Ryan <[EMAIL PROTECTED]>:

On Sun, 26 Oct 2008 08:32:52 +, Alan Gauld wrote:


"aivars" <[EMAIL PROTECTED]> wrote in message
news:[EMAIL PROTECTED]

I finally get the script working!

I renamed the script directory from Cgi-bin to cgi-bin just as Alan
told.

I'm glad it worked but I confess I'm not sure why it worked. The
interpreter was apparently finding your script OK but it was the
environment that was messed up. I don't fully understand the interaction
going on  there. But in things web related I've learned that consistency
throughout is usually helpul!

Alan G.


I wouldn't have thought it could work, since Windows is case insensitive
and web server is required understand URL as case insensitive. Why that
Cgi-bin and cgi-bin differs on a windows-based server is beyond me.


Why do you think web servers are required to understand URLs as case
insensitive?  This is not the case (other than the domain name itself).


___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] please help with simple python CGI script

2008-10-26 Thread aivars
Hello, Lie,
I renamed the directory back to Cgi-bin and the scripts are NOT
working. Going back to cgi-bin it works. I also do not understand why.

Aivars

2008/10/26 Lie Ryan <[EMAIL PROTECTED]>:
> On Sun, 26 Oct 2008 08:32:52 +, Alan Gauld wrote:
>
>> "aivars" <[EMAIL PROTECTED]> wrote in message
>> news:[EMAIL PROTECTED]
>>>I finally get the script working!
>>>
>>> I renamed the script directory from Cgi-bin to cgi-bin just as Alan
>>> told.
>>
>> I'm glad it worked but I confess I'm not sure why it worked. The
>> interpreter was apparently finding your script OK but it was the
>> environment that was messed up. I don't fully understand the interaction
>> going on  there. But in things web related I've learned that consistency
>> throughout is usually helpul!
>>
>> Alan G.
>>
>
> I wouldn't have thought it could work, since Windows is case insensitive
> and web server is required understand URL as case insensitive. Why that
> Cgi-bin and cgi-bin differs on a windows-based server is beyond me.
>
> ___
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
>
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] please help with simple python CGI script

2008-10-26 Thread Lie Ryan
On Sun, 26 Oct 2008 08:32:52 +, Alan Gauld wrote:

> "aivars" <[EMAIL PROTECTED]> wrote in message
> news:[EMAIL PROTECTED]
>>I finally get the script working!
>>
>> I renamed the script directory from Cgi-bin to cgi-bin just as Alan
>> told.
> 
> I'm glad it worked but I confess I'm not sure why it worked. The
> interpreter was apparently finding your script OK but it was the
> environment that was messed up. I don't fully understand the interaction
> going on  there. But in things web related I've learned that consistency
> throughout is usually helpul!
> 
> Alan G.
> 

I wouldn't have thought it could work, since Windows is case insensitive 
and web server is required understand URL as case insensitive. Why that 
Cgi-bin and cgi-bin differs on a windows-based server is beyond me.

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] please help with simple python CGI script

2008-10-26 Thread Alan Gauld


"aivars" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]

I finally get the script working!

I renamed the script directory from Cgi-bin to cgi-bin just as Alan 
told.


I'm glad it worked but I confess I'm not sure why it worked.
The interpreter was apparently finding your script OK but it
was the environment that was messed up. I don't fully
understand the interaction going on  there. But in things
web related I've learned that consistency throughout is
usually helpul!

Alan G.



___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] please help with simple python CGI script

2008-10-26 Thread aivars
I finally get the script working!

I renamed the script directory from Cgi-bin to cgi-bin just as Alan told.

Many thanks to all you who responded

Aivars


2008/10/26 aivars <[EMAIL PROTECTED]>:
> Thanks John and Alan
>
> I get the following error when I run the script from IDLE:
>
> Traceback (most recent call last):
>  File "C:\Cgi-bin\friends1.py", line 15, in 
>who = form['person'].value
>  File "C:\Python25\lib\cgi.py", line 567, in __getitem__
>raise KeyError, key
> KeyError: 'person'
>
>
> Aivars
> Windows XP, python 2.5
>
> 2008/10/26 John Pomni <[EMAIL PROTECTED]>:
>> what error do you get? It works without any changes on my Linux machine
>> with python 2.5
>>
>> John
>>
>> On Sat, 2008-10-25 at 21:33 +0300, aivars wrote:
>>> It does not work neither as script or from command line. I will try to
>>> find the guy Wesley Chun and ask him
>>>
>>> 2008/10/25 John Pomni <[EMAIL PROTECTED]>:
>>> > Hi,
>>> >
>>> > The script does not work from command line but I guess you do not have
>>> > any problems running it as CGI?
>>> >
>>> > I like cgitb modules for debugging purposes very much.
>>> >
>>> > http://www.python.org/doc/2.5.2/lib/node566.html
>>> >
>>> > Jan
>>> >
>>> > On Fri, 2008-10-24 at 18:55 +0300, aivars wrote:
>>> >> Thanks very much, Kent,
>>> >>
>>> >> So it seems that directory /cgi-bin should be a subdirectory to that
>>> >> directory from which the web server was started/is running. That
>>> >> worked and Deitel's script - getting time displayed finally worked.
>>> >>
>>> >> still banging mu head with Wesley Chun's simple example -
>>> >>
>>> >> #!C:\python25\python.exe
>>> >>
>>> >> import cgi
>>> >>
>>> >> reshtml = '''Content-Type: text/html\n
>>> >> 
>>> >> Friends CGI Demo (dynamic screen)
>>> >> 
>>> >> Friends list for: %s
>>> >> Your name is: %s
>>> >> You have %s friends.
>>> >> '''
>>> >>
>>> >> form = cgi.FieldStorage()
>>> >> who = form['person'].value
>>> >> howmany = form['howmany'].value
>>> >> print reshtml % (who, who, howmany)
>>> >>
>>> >> It gives me the following error:
>>> >> Traceback (most recent call last):
>>> >>   File "C:\Cgi-bin\friends1.py", line 15, in 
>>> >> who = form['person'].value
>>> >>   File "C:\Python25\lib\cgi.py", line 567, in __getitem__
>>> >> raise KeyError, key
>>> >> KeyError: 'person'
>>> >>
>>> >> I understand python is saying that there is no such a key in a directory.
>>> >>
>>> >> The HTML form looks like this. it is displayed correctly both in FF and 
>>> >> IE
>>> >>
>>> >>
>>> >> 
>>> >> Friends CGI Demo (static screen)
>>> >>
>>> >>   Friends list for: NEW USER
>>> >>
>>> >>   Enter your Name:
>>> >>   
>>> >>How many friends do you have?
>>> >> 0
>>> >>10
>>> >>25
>>> >>50
>>> >>100
>>> >>   
>>> >>
>>> >> Thanks again,
>>> >>
>>> >> Aivars
>>> >>
>>> >>
>>> >>
>>> >>
>>> >>
>>> >>
>>> >> 2008/10/24 Kent Johnson <[EMAIL PROTECTED]>:
>>> >> > On Fri, Oct 24, 2008 at 10:25 AM, aivars <[EMAIL PROTECTED]> wrote:
>>> >> >> Hello,
>>> >> >>
>>> >> >> I am learning python.
>>> >> >>
>>> >> >> I start the python CGI server like this:
>>> >> >>
>>> >> >> python -m CGIHTTPServer (this syntax I saw in Wesley Chun's Core
>>> >> >> Python Programming chapter 20.5)
>>> >> >>
>>> >> >> The server starts in command prompt on windows XP by answering:
>>> >> >> Serving HTTP on 0.0.0.0 port 8000...
>>> >> >>
>>> >> >> Next I want to run this simple CGI script (from Deitel Python How to
>>> >> >> Program chapter 6). it is supposed to print out current date and time
>>> >> >> in a browser
>>> >> >
>>> >> > The CGI script should me in a /cgi-bin subdirectory of the dir where
>>> >> > you run the script. The URL to run the CGI will then be something like
>>> >> > http:://localhost:8000/cgi-bin/myscript.py
>>> >> >
>>> >> > Kent
>>> >> >
>>> >> ___
>>> >> Tutor maillist  -  Tutor@python.org
>>> >> http://mail.python.org/mailman/listinfo/tutor
>>> >
>>> >
>>
>>
>
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] please help with simple python CGI script

2008-10-25 Thread aivars
Thanks John and Alan

I get the following error when I run the script from IDLE:

Traceback (most recent call last):
  File "C:\Cgi-bin\friends1.py", line 15, in 
who = form['person'].value
  File "C:\Python25\lib\cgi.py", line 567, in __getitem__
raise KeyError, key
KeyError: 'person'


Aivars
Windows XP, python 2.5

2008/10/26 John Pomni <[EMAIL PROTECTED]>:
> what error do you get? It works without any changes on my Linux machine
> with python 2.5
>
> John
>
> On Sat, 2008-10-25 at 21:33 +0300, aivars wrote:
>> It does not work neither as script or from command line. I will try to
>> find the guy Wesley Chun and ask him
>>
>> 2008/10/25 John Pomni <[EMAIL PROTECTED]>:
>> > Hi,
>> >
>> > The script does not work from command line but I guess you do not have
>> > any problems running it as CGI?
>> >
>> > I like cgitb modules for debugging purposes very much.
>> >
>> > http://www.python.org/doc/2.5.2/lib/node566.html
>> >
>> > Jan
>> >
>> > On Fri, 2008-10-24 at 18:55 +0300, aivars wrote:
>> >> Thanks very much, Kent,
>> >>
>> >> So it seems that directory /cgi-bin should be a subdirectory to that
>> >> directory from which the web server was started/is running. That
>> >> worked and Deitel's script - getting time displayed finally worked.
>> >>
>> >> still banging mu head with Wesley Chun's simple example -
>> >>
>> >> #!C:\python25\python.exe
>> >>
>> >> import cgi
>> >>
>> >> reshtml = '''Content-Type: text/html\n
>> >> 
>> >> Friends CGI Demo (dynamic screen)
>> >> 
>> >> Friends list for: %s
>> >> Your name is: %s
>> >> You have %s friends.
>> >> '''
>> >>
>> >> form = cgi.FieldStorage()
>> >> who = form['person'].value
>> >> howmany = form['howmany'].value
>> >> print reshtml % (who, who, howmany)
>> >>
>> >> It gives me the following error:
>> >> Traceback (most recent call last):
>> >>   File "C:\Cgi-bin\friends1.py", line 15, in 
>> >> who = form['person'].value
>> >>   File "C:\Python25\lib\cgi.py", line 567, in __getitem__
>> >> raise KeyError, key
>> >> KeyError: 'person'
>> >>
>> >> I understand python is saying that there is no such a key in a directory.
>> >>
>> >> The HTML form looks like this. it is displayed correctly both in FF and IE
>> >>
>> >>
>> >> 
>> >> Friends CGI Demo (static screen)
>> >>
>> >>   Friends list for: NEW USER
>> >>
>> >>   Enter your Name:
>> >>   
>> >>How many friends do you have?
>> >> 0
>> >>10
>> >>25
>> >>50
>> >>100
>> >>   
>> >>
>> >> Thanks again,
>> >>
>> >> Aivars
>> >>
>> >>
>> >>
>> >>
>> >>
>> >>
>> >> 2008/10/24 Kent Johnson <[EMAIL PROTECTED]>:
>> >> > On Fri, Oct 24, 2008 at 10:25 AM, aivars <[EMAIL PROTECTED]> wrote:
>> >> >> Hello,
>> >> >>
>> >> >> I am learning python.
>> >> >>
>> >> >> I start the python CGI server like this:
>> >> >>
>> >> >> python -m CGIHTTPServer (this syntax I saw in Wesley Chun's Core
>> >> >> Python Programming chapter 20.5)
>> >> >>
>> >> >> The server starts in command prompt on windows XP by answering:
>> >> >> Serving HTTP on 0.0.0.0 port 8000...
>> >> >>
>> >> >> Next I want to run this simple CGI script (from Deitel Python How to
>> >> >> Program chapter 6). it is supposed to print out current date and time
>> >> >> in a browser
>> >> >
>> >> > The CGI script should me in a /cgi-bin subdirectory of the dir where
>> >> > you run the script. The URL to run the CGI will then be something like
>> >> > http:://localhost:8000/cgi-bin/myscript.py
>> >> >
>> >> > Kent
>> >> >
>> >> ___
>> >> Tutor maillist  -  Tutor@python.org
>> >> http://mail.python.org/mailman/listinfo/tutor
>> >
>> >
>
>
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] please help with simple python CGI script

2008-10-25 Thread Alan Gauld


"aivars" <[EMAIL PROTECTED]> wrote 




still banging mu head with Wesley Chun's simple example -


I'm not sure if this is significant but


It gives me the following error:
Traceback (most recent call last):
 File "C:\Cgi-bin\friends1.py", line 15, in 


Notice that the file path has Cgi not cgi
Case may be significant...


  


The action expects cgi

Just a thought.


--
Alan Gauld
Author of the Learn to Program web site
http://www.freenetpages.co.uk/hp/alan.gauld

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] please help with simple python CGI script

2008-10-25 Thread aivars
It does not work neither as script or from command line. I will try to
find the guy Wesley Chun and ask him

2008/10/25 John Pomni <[EMAIL PROTECTED]>:
> Hi,
>
> The script does not work from command line but I guess you do not have
> any problems running it as CGI?
>
> I like cgitb modules for debugging purposes very much.
>
> http://www.python.org/doc/2.5.2/lib/node566.html
>
> Jan
>
> On Fri, 2008-10-24 at 18:55 +0300, aivars wrote:
>> Thanks very much, Kent,
>>
>> So it seems that directory /cgi-bin should be a subdirectory to that
>> directory from which the web server was started/is running. That
>> worked and Deitel's script - getting time displayed finally worked.
>>
>> still banging mu head with Wesley Chun's simple example -
>>
>> #!C:\python25\python.exe
>>
>> import cgi
>>
>> reshtml = '''Content-Type: text/html\n
>> 
>> Friends CGI Demo (dynamic screen)
>> 
>> Friends list for: %s
>> Your name is: %s
>> You have %s friends.
>> '''
>>
>> form = cgi.FieldStorage()
>> who = form['person'].value
>> howmany = form['howmany'].value
>> print reshtml % (who, who, howmany)
>>
>> It gives me the following error:
>> Traceback (most recent call last):
>>   File "C:\Cgi-bin\friends1.py", line 15, in 
>> who = form['person'].value
>>   File "C:\Python25\lib\cgi.py", line 567, in __getitem__
>> raise KeyError, key
>> KeyError: 'person'
>>
>> I understand python is saying that there is no such a key in a directory.
>>
>> The HTML form looks like this. it is displayed correctly both in FF and IE
>>
>>
>> 
>> Friends CGI Demo (static screen)
>>
>>   Friends list for: NEW USER
>>
>>   Enter your Name:
>>   
>>How many friends do you have?
>> 0
>>10
>>25
>>50
>>100
>>   
>>
>> Thanks again,
>>
>> Aivars
>>
>>
>>
>>
>>
>>
>> 2008/10/24 Kent Johnson <[EMAIL PROTECTED]>:
>> > On Fri, Oct 24, 2008 at 10:25 AM, aivars <[EMAIL PROTECTED]> wrote:
>> >> Hello,
>> >>
>> >> I am learning python.
>> >>
>> >> I start the python CGI server like this:
>> >>
>> >> python -m CGIHTTPServer (this syntax I saw in Wesley Chun's Core
>> >> Python Programming chapter 20.5)
>> >>
>> >> The server starts in command prompt on windows XP by answering:
>> >> Serving HTTP on 0.0.0.0 port 8000...
>> >>
>> >> Next I want to run this simple CGI script (from Deitel Python How to
>> >> Program chapter 6). it is supposed to print out current date and time
>> >> in a browser
>> >
>> > The CGI script should me in a /cgi-bin subdirectory of the dir where
>> > you run the script. The URL to run the CGI will then be something like
>> > http:://localhost:8000/cgi-bin/myscript.py
>> >
>> > Kent
>> >
>> ___
>> Tutor maillist  -  Tutor@python.org
>> http://mail.python.org/mailman/listinfo/tutor
>
>
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] please help with simple python CGI script

2008-10-24 Thread aivars
Thanks very much, Kent,

So it seems that directory /cgi-bin should be a subdirectory to that
directory from which the web server was started/is running. That
worked and Deitel's script - getting time displayed finally worked.

still banging mu head with Wesley Chun's simple example -

#!C:\python25\python.exe

import cgi

reshtml = '''Content-Type: text/html\n

Friends CGI Demo (dynamic screen)

Friends list for: %s
Your name is: %s
You have %s friends.
'''

form = cgi.FieldStorage()
who = form['person'].value
howmany = form['howmany'].value
print reshtml % (who, who, howmany)

It gives me the following error:
Traceback (most recent call last):
  File "C:\Cgi-bin\friends1.py", line 15, in 
who = form['person'].value
  File "C:\Python25\lib\cgi.py", line 567, in __getitem__
raise KeyError, key
KeyError: 'person'

I understand python is saying that there is no such a key in a directory.

The HTML form looks like this. it is displayed correctly both in FF and IE



Friends CGI Demo (static screen)
   
  Friends list for: NEW USER
   
  Enter your Name:
  
   How many friends do you have?
0
   10
   25
   50
   100
  

Thanks again,

Aivars






2008/10/24 Kent Johnson <[EMAIL PROTECTED]>:
> On Fri, Oct 24, 2008 at 10:25 AM, aivars <[EMAIL PROTECTED]> wrote:
>> Hello,
>>
>> I am learning python.
>>
>> I start the python CGI server like this:
>>
>> python -m CGIHTTPServer (this syntax I saw in Wesley Chun's Core
>> Python Programming chapter 20.5)
>>
>> The server starts in command prompt on windows XP by answering:
>> Serving HTTP on 0.0.0.0 port 8000...
>>
>> Next I want to run this simple CGI script (from Deitel Python How to
>> Program chapter 6). it is supposed to print out current date and time
>> in a browser
>
> The CGI script should me in a /cgi-bin subdirectory of the dir where
> you run the script. The URL to run the CGI will then be something like
> http:://localhost:8000/cgi-bin/myscript.py
>
> Kent
>
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] please help with simple python CGI script

2008-10-24 Thread Kent Johnson
On Fri, Oct 24, 2008 at 10:25 AM, aivars <[EMAIL PROTECTED]> wrote:
> Hello,
>
> I am learning python.
>
> I start the python CGI server like this:
>
> python -m CGIHTTPServer (this syntax I saw in Wesley Chun's Core
> Python Programming chapter 20.5)
>
> The server starts in command prompt on windows XP by answering:
> Serving HTTP on 0.0.0.0 port 8000...
>
> Next I want to run this simple CGI script (from Deitel Python How to
> Program chapter 6). it is supposed to print out current date and time
> in a browser

The CGI script should me in a /cgi-bin subdirectory of the dir where
you run the script. The URL to run the CGI will then be something like
http:://localhost:8000/cgi-bin/myscript.py

Kent
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] please help formating

2007-05-25 Thread Kent Johnson
Just for fun, here is a parser written with pyparsing. It treats 
newlines as whitespace so it will work with the split data you posted.
http://pyparsing.wikispaces.com/

data = '''(39577484, 39577692) [['NM_003750']]
(107906, 108011) [['NM_002443']]
(113426, 113750) [['NM_138634', 'NM_002443']]
(106886, 106991) [['NM_138634', 'NM_002443']]
(100708, 100742) [['NM_138634', 'NM_002443']]
(35055935, 35056061) [['NM_002313', 'NM_001003407',
  'NM_001003408']]
'''

from pyparsing import *
keys = Suppress('(') + Word(nums) + Suppress(',') + Word(nums) + 
Suppress(')')
values = Group(Suppress('[[') + 
delimitedList(sglQuotedString.setParseAction(removeQuotes)) + 
Suppress(']]'))
expr = keys + values

for result, start, end in expr.scanString(data):
 print '%s %s\t%s' % (result[0], result[1], ','.join(result[2]))


Kent
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] please help formating

2007-05-25 Thread Kent Johnson
kumar s wrote:
> hi group,
> 
> i have a data obtained from other student(over 100K)
> lines that looks like this:
> (39577484, 39577692) [['NM_003750']]
> (107906, 108011) [['NM_002443']]
> (113426, 113750) [['NM_138634', 'NM_002443']]
> (106886, 106991) [['NM_138634', 'NM_002443']]
> (100708, 100742) [['NM_138634', 'NM_002443']]
> (35055935, 35056061) [['NM_002313', 'NM_001003407',
> 'NM_001003408']]
> 
> I know that first two items in () are tuples, and the
> next [[]] a list of list. I was told that the tuples
> were keys and the list was its value in a dictionary.
> 
> how can I parse this into a neat structure that looks
> like this:
> 39577484, 39577692 \t NM_003750
> 107906, 108011 \t NM_002443
> 113426, 113750 \t  NM_138634,NM_002443
> 106886, 106991 \t  NM_138634,NM_002443
> 100708, 100742 \t  NM_138634,NM_002443
> 35055935, 35056061 \t
> NM_002313,NM_001003407,NM_001003408

How about this (assuming the line wrap at the end was done by mail; if 
it is in the data it is a little harder to parse it):

data = '''(39577484, 39577692) [['NM_003750']]
(107906, 108011) [['NM_002443']]
(113426, 113750) [['NM_138634', 'NM_002443']]
(106886, 106991) [['NM_138634', 'NM_002443']]
(100708, 100742) [['NM_138634', 'NM_002443']]
(35055935, 35056061) [['NM_002313', 'NM_001003407', 'NM_001003408']]
'''.splitlines()

import re
for line in data:
 match = re.match(r'\((\d*), (\d*)\) \[\[(.*)\]\]', line)
 if match:
 t1, t2, data = match.group(1, 2, 3)
 data = data.replace("'", "").replace(' ', '')
 print '%s %s\t%s' % (t1, t2, data)
 else:
 print 'no match:', line


Note the format of the data here is different from what you showed in 
your post last night...

Kent
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] please help formating

2007-05-22 Thread Andreas Kostyrka
-BEGIN PGP SIGNED MESSAGE-
Hash: SHA1

Why does my "homework-alert" ring with this post?

Andreas

kumar s wrote:
> hi group,
> 
> i have a data obtained from other student(over 100K)
> lines that looks like this:
> (39577484, 39577692) [['NM_003750']]
> (107906, 108011) [['NM_002443']]
> (113426, 113750) [['NM_138634', 'NM_002443']]
> (106886, 106991) [['NM_138634', 'NM_002443']]
> (100708, 100742) [['NM_138634', 'NM_002443']]
> (35055935, 35056061) [['NM_002313', 'NM_001003407',
> 'NM_001003408']]
> 
> I know that first two items in () are tuples, and the
> next [[]] a list of list. I was told that the tuples
> were keys and the list was its value in a dictionary.
> 
> how can I parse this into a neat structure that looks
> like this:
> 39577484, 39577692 \t NM_003750
> 107906, 108011 \t NM_002443
> 113426, 113750 \t  NM_138634,NM_002443
> 106886, 106991 \t  NM_138634,NM_002443
> 100708, 100742 \t  NM_138634,NM_002443
> 35055935, 35056061 \t
> NM_002313,NM_001003407,NM_001003408
> 
> 
> I treid substituting in vim editor but it is not
> effective. 
> 
> Thank you
> 
> kum
> 
> 
>
> Pinpoint
>  customers who are looking for what you sell. 
> http://searchmarketing.yahoo.com/
> ___
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
-BEGIN PGP SIGNATURE-
Version: GnuPG v1.4.2 (GNU/Linux)
Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org

iD8DBQFGU2ZmHJdudm4KnO0RAnIgAJ4oHRPSfYFId7C7TzeWYXPobf9l+QCg34Ja
bRtlufQ7K/TKPsLOOBNEmJI=
=QeIu
-END PGP SIGNATURE-
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] please help me

2007-04-13 Thread Greg Perry
Let no good deed go unpunished!

-Original Message-
From: Daniel Yoo
Date: Friday, Apr 13, 2007 8:24 pm
Subject: Re: [Tutor] please help me

> If this is homework, please tell your teacher I helped - I need the 
> extra credit.
>
>Please avoid giving homework answers like this.  Rather than actually help 
>the person, it can do harm, because it encourages a lazy attitude toward 
>solving problems.



___
Tutor maillist  -  [EMAIL PROTECTED]
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] please help me

2007-04-13 Thread Daniel Yoo
> If this is homework, please tell your teacher I helped - I need the 
> extra credit.

Please avoid giving homework answers like this.  Rather than actually help 
the person, it can do harm, because it encourages a lazy attitude toward 
solving problems.
___
Tutor maillist  -  [EMAIL PROTECTED]
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] please help me!

2007-04-12 Thread Ben Sherman
You

On 4/12/07, suryo agung <[EMAIL PROTECTED]> wrote:
> pleate tell me how to make
>
> input number=4
> result
>
> 1
> 22
> 333
> 
>
> in python
> please give me your answer.

input_number = 4

for i in range(1,input_number + 1):
  print str(i) * i

If this is homework, please tell your teacher I helped - I need the
extra credit.
___
Tutor maillist  -  [EMAIL PROTECTED]
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] please help me!

2007-04-12 Thread Kent Johnson
suryo agung wrote:
> pleate tell me how to make
> 
> input number=4
> result
> 
> 1
> 22
> 333
> 
> 
> in python
> please give me your answer.

This looks a lot like homework to me. What have you tried? What have you 
learned?

Kent
___
Tutor maillist  -  [EMAIL PROTECTED]
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Please help to resolve this...

2006-11-08 Thread Danny Yoo
>> def hello():
>>   return "Hello World"
>>
>>   server = SOAP.SOAPServer(("localhost", 23000))
>>   server.registerFunction(hello)
>>   server.serve_forever()
>
> Have you tried running server.py?  There's a glaring error in it. (Hint: SOAP 
> != SOAPpy)


Actually, there's a much more glaring error in it.  Note the early exit 
from 'return "hello world".  The program is escaping out too quickly.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Please help to resolve this...

2006-11-08 Thread Danny Yoo
> *#server.py*
> import SOAPpy
>
>
> def hello():
>   return "Hello World"
>
>   server = SOAP.SOAPServer(("localhost", 23000))
>   server.registerFunction(hello)
>   server.serve_forever()

Hi Asrarahmed,

I also want to reiterate what Luke said: it does get a little irritating 
if we see the same question repeated.  Try reading:

 http://catb.org/esr/faqs/smart-questions.html

to get a better feel for what kind of things help us answer your questions 
better.


Have you tried running server.py?  There's a glaring error in it. (Hint: 
SOAP != SOAPpy)

I know it might sound silly, but just to make sure you understand: the 
server must be up and running before you try contacting it with the 
client.

Also, you may want to reconsider SOAPpy: we've had previous discussion 
where it was apparent SOAPpy is a dead project:

 http://mail.python.org/pipermail/tutor/2006-November/050530.html
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Please help to resolve this...

2006-11-08 Thread Luke Paireepinart
Asrarahmed Kadri wrote:
> Hi,
Asrarahmed:
You posted this exact question only 4 hours ago.
Reposting questions this quickly is an abuse of the mailing list, as far 
as I'm concerned.
If you don't wait at _minimum_ a full day, preferably at least 2, for an 
answer, it just irritates
people and makes it less likely for you to get an answer.
People may completely disregard this question now, just as a matter of 
principle,
so that they don't give you the idea that reposting is appreciated.
Not mad or anything, just informing you.

HTH,
-Luke
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Please help to resolve this...

2006-11-08 Thread Andreas Kostyrka
* Asrarahmed Kadri <[EMAIL PROTECTED]> [061108 19:51]:
> Hi,
> 
> I have successfully installed the SOAPpy module. The version is 0.11.6
> 
> I am trying to run simple test program for server and cliet. The script for
> server is executing without any error; but the client script is giving me

Well, the error means that nothing is listening on port 23000 on localhost. 
Firewall?

Andreas
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Please help to debug this function..

2006-11-07 Thread ALAN GAULD
Reposting to the list.

--- Asrarahmed Kadri <[EMAIL PROTECTED]> wrote:

> > >except ValueError:
> > >flag = False
> > >startdate = None
> > >enddate = None
> > >err_msg = traceback.format_exc()
> > >index = string.find(err_msg,'Value')
> > >print err_msg[index:]
> > >return (flag,startdate,enddate)
> >
> >Since this block is essentially identical to the except
> >block above you could package them both as a function 
> >which would shorten the code a little.

> It might seem silly, but can you just give a hint as to how to
> put the code in a function..

def handleValueError():
flag = False
startdate = None
enddate = None
err_msg = traceback.format_exc()
index = err_msg.find('Value')
print err_msg[index:]
return (flag,startdate,enddate)

And in your code above:

except ValueError:
return handleValueError()

> > It would be better to raise a ValueError which can be caught
> > by the external program:

> How to catch the exception from one module into another ..???

Just use try/except as usual. There is no difference 
to exceptions thrown by your code and the ones thrown 
by the standard Python functions. Consider:

### module.py ###

def f():
   raise ValueError

##

## main.py ##
import module

try:
   module.f()
except ValueError:
   print "It broke!"

#

Is that clear?

Alan G








___ 
All new Yahoo! Mail "The new Interface is stunning in its simplicity and ease 
of use." - PC Magazine 
http://uk.docs.yahoo.com/nowyoucan.html
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Please help to debug this function.. it takes a date and num. of days and returns startdate and enddate (fwd)

2006-11-06 Thread Danny Yoo
[Forwarding to Tutor; busy at the moment]

-- Forwarded message --
Date: Mon, 6 Nov 2006 18:41:54 +
From: Asrarahmed Kadri <[EMAIL PROTECTED]>
To: Danny Yoo <[EMAIL PROTECTED]>
Subject: Re: [Tutor] Please help to debug this function.. it takes a date and
 num. of days and returns startdate and enddate

Hi Danny,

Can you please test it !!!
Also I would like to know if it can be coded in a better way...

TIA.

Regards,
Asrarahmed


On 11/6/06, Danny Yoo <[EMAIL PROTECTED]> wrote:
>
>
>
> On Mon, 6 Nov 2006, Asrarahmed Kadri wrote:
>
>> I have written a function that takes a date and an integer representing
>> the number of days.
>>
>> Please test it, comment on the logic .
>
>
> Hi Asrarahmed,
>
> You should be able to write your own tests too.  You might want to look
> at:
>
> http://www.diveintopython.org/unit_testing/index.html
>
> for an example of how to write unit tests; the author there goes through
> an example with a Roman Numeral program written with unit tests.
>



-- 
To HIM you shall return.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Please help to debug this function.. it takes a date andnum. of days and returns startdate and enddate

2006-11-06 Thread Alan Gauld

"Asrarahmed Kadri" <[EMAIL PROTECTED]> wrote

> Please test it, comment on the logic .

I haven't tested it but here are some comments:

> import string
> import datetime
> import traceback
>
> def dateCheck(date1,num_days):
>flag = True
>startdate = None
>enddate = None
>
>if num_days < 0 or num_days > 31:
>flag = False
>print "The argument for -n has to be between 0 and 31"
>return (flag,startdate,enddate)
>
>else:

You don't need the else since the if block returns.
Thus you only reach the followiong code if the test is false.
This reduces the anumber of levels of indenting by one which
improves readability and thus maintenance.

>date_lst = string.split(date1,"/")

better to use the string methods. ie date1.split('/')

>ln = len(date_lst)
>if ln != 3 :

you could have combined those lines into one since you never
use 'ln' except in the test.

if len(date1.split('/') != 3:


>flag = False
>print "The argument for -D option has to be in the 
> format:
> dd/mm/"
>return (flag,startdate,enddate)
>else:

Same as above, the else is just adding levels of indentation.

>date_lst.reverse()
>print date_lst
>try:
>if int(date_lst[0]) < 2000:
>flag = False
>print "The year cannot be earlier than 2000 and 
> it
> should be in the format ''."
>return (flag,startdate,enddate)
>except ValueError:
>flag = False
>err_msg = traceback.format_exc()
>index = string.find(err_msg,'Value')

Again use the string method:

index = err_msg.find('Value')

>print err_msg[index:]
>return (flag,startdate,enddate)
>
>try:
>startdate = datetime.date
> (int(date_lst[0]),int(date_lst[1]),int(date_lst[2]))
>enddate = startdate + 
> datetime.timedelta(days=num_days)
>print startdate, enddate
>
>except ValueError:
>
>flag = False
>startdate = None
>enddate = None
>err_msg = traceback.format_exc()
>index = string.find(err_msg,'Value')
>print err_msg[index:]
>return (flag,startdate,enddate)

Since this block is essentially identical to the except block above
you could package them both as a function which would shorten
the code a little.

>if enddate > datetime.date.today():
>enddate = datetime.date.today()
>if startdate > datetime.date.today():
>flag = False
>startdate = None
>enddate = None
>print "The -D option should have a date not later 
> than
> today's date"

Since this is a function and not part of the user interface there
shouldn't really be any knowledge of the -D option in this code.
What if you want to call it from another module that uses
different options?

It would be better to raise a ValueError which can be caught
by the external program:

 raise ValueEerror ("startdate later than today")


>return (flag,startdate,enddate)
> 

HTH,

-- 
Alan Gauld
Author of the Learn to Program web site
http://www.freenetpages.co.uk/hp/alan.gauld 


___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Please help to debug this function.. it takes a date and num. of days and returns startdate and enddate

2006-11-06 Thread Danny Yoo


On Mon, 6 Nov 2006, Asrarahmed Kadri wrote:

> I have written a function that takes a date and an integer representing 
> the number of days.
>
> Please test it, comment on the logic .


Hi Asrarahmed,

You should be able to write your own tests too.  You might want to look 
at:

 http://www.diveintopython.org/unit_testing/index.html

for an example of how to write unit tests; the author there goes through 
an example with a Roman Numeral program written with unit tests.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Please help!!

2006-05-21 Thread Kent Johnson
MATATA EMMANUEL wrote:
> Alan,
> 
> Man!  I was thinking that it was simple. This is a little bit hard but 
> will try to make sense of it as I can.

How would you fetch the shapefile with your browser? Is there a url to 
download the file? It's pretty simple to fetch a web page or other 
resource from a URL and save it to a local file. urllib.urlretrieve() 
will do it.

If you have to authenticate (login) to the web site it gets a little 
more complex. urllib2 is similar to urllib but it has more options and 
supports authentication. There is a tutorial for urllib2 here:
http://www.voidspace.org.uk/python/articles/urllib2.shtml

Kent

> 
> Thank you for your assistance. I'm glad you're up there to assist.
> 
> Matt
> 
>  
> 
>  
> 
> 
> From:  /"Alan Gauld" <[EMAIL PROTECTED]>/
>     To:  /"MATATA EMMANUEL" <[EMAIL PROTECTED]>/
> CC:  //
> Subject:  /Re: [Tutor] Please help!!/
> Date:  /Sat, 20 May 2006 17:58:20 +0100/
>  >[CCing back to list]
>  >
>  >>I know HTML even if I haven't used it for sometimes. I Also know
>  >>couple other programming languages (Visual basic, some C++).
>  >>I just taken a Python course of writting Python scripts for ArcGIS
>  >>so that if you sent me a script, I will be able to understand it.
>  >
>  >OK, now we know the background we know where to pitch the reply.
>  >I don't have a script that will do exactly what you want but someone
>  >else posted a snippet showing how to use urllib.
>  >
>  >If you need to parse the html that you read from urllib then you
>  >might
>  >find BeautifulSoup worth a look.
>  >
>  >http://www.crummy.com/software/BeautifulSoup/
>  >
>  >It makes extracting elements from html fairly painless.
>  >
>  >But if its easy to find a simple search of the string for the img
>  >tag
>  >may suffice.
>  >
>  >HTH,
>      >
>      >Alan Gauld
>  >Author of the Learn to Program web site
>  >http://www.freenetpages.co.uk/hp/alan.gauld
>  >
>  >>
>  >>  From:  "Alan Gauld" <[EMAIL PROTECTED]>
>  >>  To:  "MATATA EMMANUEL" <[EMAIL PROTECTED]>,
>  >>  Subject:  Re: [Tutor] Please help!!
>  >>  Date:  Sat, 20 May 2006 13:15:41 +0100
>  >>  >>I'm tasked to write a Paython script which is supposed to hit a
>  >>web >>site and download a shapefile from that web site.
>  >>  >
>  >>  >The urllib module should do that for you but...
>  >>  >
>  >>  >>I don't have any clue and would like your help.
>  >>  >
>  >>  >What do you know?
>  >>  >Do you understand HTML? and specifically how to create and read
>  >>img >tags?
>  >>  >
>  >>  >Do you know any Python? Do you know any other programming
>  >>language?
>  >>  >
>  >>  >>I use 9.x if this matter.
>  >>  >
>  >>  >Version 9.x of what?
>  >>  >Operating System - on a Mac perhaps?
>  >>  >If so it shouldn't matter since Python's urllib works OK on the  
>  >> >older versions.
>  >>  >
>  >>  >We really need a liittle more background to help further.
>  >>  >
>  >>  >HTH,
>  >>  >
>  >>  >Alan G.
>  >>  >
>  >>
>  >
>  >
> 
> 
> 
> 
> ___
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor


___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Please help!!

2006-05-20 Thread Alan Gauld
> Man!  I was thinking that it was simple. This is a little bit hard 
> but will try to make sense of it as I can.

OK, the way this list operates is that you try to solve it yourself.
When it doesn't work you tell us what you tried to do and what
went wrong. We then try to point you in the right direction.

> Thank you for your assistance. I'm glad you're up there to assist.

The tutor list are all here waiting to help. We are like any good
teacher, we don't just give answers out will-nilly but we do try
to steer you to the solution so that you understand it for the future.

If you do have a problem post the code that causes the problem
and also paste in any error messages you get - the whoile error
not just the last line.

Have a go, let us see what is sticking you, we are here to help,

Alan G 


___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Please help!!

2006-05-20 Thread MATATA EMMANUEL

Alan,
Man!  I was thinking that it was simple. This is a little bit hard but will try to make sense of it as I can.
Thank you for your assistance. I'm glad you're up there to assist.
Matt
 
 




From:  "Alan Gauld" <[EMAIL PROTECTED]>To:  "MATATA EMMANUEL" <[EMAIL PROTECTED]>CC:  Subject:  Re: [Tutor] Please help!!Date:  Sat, 20 May 2006 17:58:20 +0100>[CCing back to list]>>>I know HTML even if I haven't used it for sometimes. I Also know >>couple other programming languages (Visual basic, some C++).>>I just taken a Python course of writting Python scripts for ArcGIS >>so that if you sent me a script, I will be able to understand it.>>OK, now we know the background we know where to pitch the reply.>I don't have a script that will do exactly what you want but someone>else posted a snippet showing how to use urllib.>>If you need to 
parse the html that you read from urllib then you >might>find BeautifulSoup worth a look.>>http://www.crummy.com/software/BeautifulSoup/>>It makes extracting elements from html fairly painless.>>But if its easy to find a simple search of the string for the img >tag>may suffice.>>HTH,>>Alan Gauld>Author of the Learn to Program web site>http://www.freenetpages.co.uk/hp/alan.gauld>>>>>  From:  "Alan Gauld" <[EMAIL PROTECTED]>>>  To:  "MATATA EMMANUEL" <[EMAIL PROTECTED]>,>>  Subject:  Re: [Tutor] Please help!!>>  Date:  Sat, 20 May 2006 13:15:41 +0100>>  >>I'm tasked to write 
a Paython script which is supposed to hit a >>web >>site and download a shapefile from that web site.>>  >>>  >The urllib module should do that for you but...>>  >>>  >>I don't have any clue and would like your help.>>  >>>  >What do you know?>>  >Do you understand HTML? and specifically how to create and read >>img >tags?>>  >>>  >Do you know any Python? Do you know any other programming >>language?>>  >>>  >>I use 9.x if this matter.>>  >>>  >Version 9.x of what?>>  >Operating System - on a Mac 
perhaps?>>  >If so it shouldn't matter since Python's urllib works OK on the  >> >older versions.>>  >>>  >We really need a liittle more background to help further.>>  >>>  >HTH,>>  >>>  >Alan G.>>  >>>>>

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Please help!!

2006-05-20 Thread Alan Gauld
[CCing back to list]

> I know HTML even if I haven't used it for sometimes. I Also know 
> couple other programming languages (Visual basic, some C++).
> I just taken a Python course of writting Python scripts for ArcGIS 
> so that if you sent me a script, I will be able to understand it.

OK, now we know the background we know where to pitch the reply.
I don't have a script that will do exactly what you want but someone
else posted a snippet showing how to use urllib.

If you need to parse the html that you read from urllib then you might
find BeautifulSoup worth a look.

http://www.crummy.com/software/BeautifulSoup/

It makes extracting elements from html fairly painless.

But if its easy to find a simple search of the string for the img tag
may suffice.

HTH,

Alan Gauld
Author of the Learn to Program web site
http://www.freenetpages.co.uk/hp/alan.gauld

>
>  From:  "Alan Gauld" <[EMAIL PROTECTED]>
>  To:  "MATATA EMMANUEL" <[EMAIL PROTECTED]>,
>  Subject:  Re: [Tutor] Please help!!
>  Date:  Sat, 20 May 2006 13:15:41 +0100
>  >>I'm tasked to write a Paython script which is supposed to hit a 
> web >>site and download a shapefile from that web site.
>  >
>  >The urllib module should do that for you but...
>  >
>  >>I don't have any clue and would like your help.
>  >
>  >What do you know?
>  >Do you understand HTML? and specifically how to create and read 
> img >tags?
>  >
>  >Do you know any Python? Do you know any other programming 
> language?
>  >
>  >>I use 9.x if this matter.
>  >
>  >Version 9.x of what?
>  >Operating System - on a Mac perhaps?
>  >If so it shouldn't matter since Python's urllib works OK on the 
>  >older versions.
>  >
>  >We really need a liittle more background to help further.
>  >
>  >HTH,
>  >
>  >Alan G.
>  >
> 


___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Please help!!

2006-05-20 Thread Alan Gauld
> I'm tasked to write a Paython script which is supposed to hit 
> a web site and download a shapefile from that web site. 

The urllib module should do that for you but...

> I don't have any clue and would like your help. 

What do you know?
Do you understand HTML? and specifically how to 
create and read img tags?

Do you know any Python? 
Do you know any other programming language?

> I use 9.x if this matter.

Version 9.x of what?
Operating System - on a Mac perhaps?
If so it shouldn't matter since Python's urllib works OK on 
the older versions.

We really need a liittle more background to help further.

HTH,

Alan G.

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Please help!!

2006-05-19 Thread Bernd Prager
Hey Matata,

>From the website  http://www.boddie.org.uk/python/HTML.html:

import urllib
# Get a file-like object for the Python Web site's home page.
f = urllib.urlopen("http://www.python.org";)
# Read from the object, storing the page's contents in 's'.
s = f.read()
f.close()


Hope this helps,
-- Bernd

MATATA EMMANUEL wrote:
>
> Hi there,
>
> I'm tasked to write a Paython script which is supposed to hit a web
> site and download a shapefile from that web site. I don't have any
> clue and would like your help. I use 9.x if this matter.
>
> Thank you.
>
> Matt.
>
>  
> 
>
> ___
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
>   

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Please help!!

2006-05-19 Thread Henry Finucane
On 5/19/06, MATATA EMMANUEL <[EMAIL PROTECTED]> wrote:
>
>
>
> Hi there,
Hi!
>
> I'm tasked to write a Paython script which is supposed to hit a web site and
> download a shapefile from that web site.

Cool. Look at urllib in your python documentation.

> I don't have any clue and

Me neither :)

> would like your help. I use 9.x if this matter.

9.x what? Python has yet to release 2.6, if I'm not mistaken.

>
> Thank you.
>
> Matt.

Good luck.

>
>
>
>
> ___
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
>
>
>


-- 
--H.F.
My penguin is bigger than yours, mister...
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Please help with comparision in range of numbers

2005-09-16 Thread Kent Johnson
Srinivas Iyyer wrote:
> I want to find such instances of jack and jill's that
> fall in the same ranges and they should be in opposite
> to each other. 
> 
> Truely, I always flunk and my mind gets blackedout
> when I see these number ranges.  I do not know how to
> write : check "if a range of numbers fall in the other
> range of numbers" condition. 

You might be interested in the interval module available here:
http://members.cox.net/apoco/interval/

It implements Interval and IntervalSet. It seems to use a brute-force algorithm 
but at least it gives you a tested and packaged starting point.

Kent

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Please help with comparision in range of numbers

2005-09-15 Thread Danny Yoo


> 1427021_s_at  chr7:102786983-102794499(+)
> 1452285_a_at  chr7:102786983-102794499(+)
> 1445553_atchr7:102848766-102910961(-)
> 1420925_atchr7:102863841-102887410(+)
> 1450041_a_at  chr7:102863841-102887410(+)
> 1447553_x_at  chr7:102899711-10285(-)
> 1418478_atchr7:102991513-103023463(-)
> 1452892_atchr7:103132162-103291925(-)
> 1430157_atchr7:103292083-103297768(+)

[some text cut]

> I want to find such instances of jack and jill's that fall in the same
> ranges and they should be in opposite to each other.


Hi Srinivas,


Let's break this down into two separate problems:

1.  Finding Ranges that overlap.
2.  Given two Ranges, see if they're in opposite directions.

I'm going to ignore problem 2 at the moment.  *grin*


If we don't care too much about efficiency, the following should help you
solve problem 1.

##
class Range(object):
def __init__(self, low, high):
assert low <= high
self.low, self.high = low, high

def is_overlapping(self, other):
"""Returns true if this range overlaps the other range.
The exact boolean condition is copied from the
classic textbook "Introduction to Algorithms, 2nd edition",
section 14.3.
"""
return (self.low <= other.high) and other.low <= self.high
##


For example:

##
>>> Range(1, 2).is_overlapping(Range(2, 3))
True
>>> Range(1, 2).is_overlapping(Range(3, 3))
False
>>> Range(1, 2).is_overlapping(Range(-2, 0))
False
>>> Range(1, 2).is_overlapping(Range(-42, 42))
True
##

So if you have sequence of Ranges like this, you can brute force and just
loop across all possible pairs, and do this is_overlapping() check.  You
may want to test this on a small sample dataset just to see that it works.

This approach, however, is slow, and gets slower as the dataset grows.
If we do care about efficiency, we have to do something a little smarter.

Interval trees or K-d Tree data structures are examples of data structures
that can help you do range-intersection queries much more quickly than a
brute-force approach.  There's an implementation of K-d trees in
biopython:

http://biopython.org/docs/api/public/Bio.KDTree-module.html

so you may want to investigate this with the Biopython folks if speed is a
concern.  John Bentley wrote a nice survey article talking about these
range-searching algorithms here:

http://portal.acm.org/citation.cfm?id=356797

although you might need an ACM account to get at the article.



> Truely, I always flunk and my mind gets blackedout when I see these
> number ranges.  I do not know how to write : check "if a range of
> numbers fall in the other range of numbers" condition.

Yeah, me too.  Check out the book reference in the code above: it helps to
clear things up about intervals and range checking.

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Please help

2005-08-03 Thread Alan G

> sorry for repost.

OK, since nobody respoinded I'll make a few suggestions.


> I have a file (3339203 lines) that looks like this:

Get it working first then worry about tuning it for the volumes later.

>
> (col:1)(col:2) (col:3)

Is the above explanatory or part of the file?
Doesn't matter juch but just to be clear.

> AD134KL
>X   X
>X   X
>X   X


> AD134KL
> AD134KL X   X
> AD134KL X   X
> AD134KL X   X


So when you find a line with one field you need to store that
value and preppend it to all subsequent lines until you get
an empty line or another with a single field?

In pseudo code:

for line in infile
if len(line) == 1:  # just a newline
   outfile.write(line)
   continue
fields = line.strip().split()
if len(fields) == 1
   tag = fields[0]
   output = line
else:
   fields.insert(0,tag)
   output = "%12s%12s%12s\n" % tuple(fields)
outfile.write(output)

Does that make any kind of sense?

Alan G.

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Please help

2005-08-03 Thread Allen John Schmidt, Jr.
Whoops! Had to correct it!

Hey, I had a similar problem not too long ago. My data came in the first
format, but I didn't need it formated like that.

Here is how I would have written it:

import re
col=re.compile('(AD.*?)\s*$')
datas=re.compile('\s*(.+?)\s+(.+?)')
f1 = open('xx','r')
mind={}
matching=''

for i in fl:
match=col.find(i)
if match:
mind[match.group(1)]=[]
matching=match.group(1)
match=datas.find(i)
if match:
mind[matching].append([match.group(1),match.group(2)])


That would collect the data and put it into a dictionary with the values
being a list of the two part data. You could print like this:

for each in mind.keys():
print each
for value in mind[each]:
print each+""+value[0]+""+value[1]


That should do it!

Ask if you don't understand any part of it.

Allen J. Schmidt, Jr.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Please help

2005-08-03 Thread Allen John Schmidt, Jr.
Hey, I had a similar problem not too long ago. My data came in the first 
format, but I didn't need it formated like that.

Here is how I would have written it:

import re
col=re.compile('(AD.*?)\s*$')
datas=re.compile('\s*(.+?)\s+(.+?)')
f1 = open('xx','r')
mind={}
matching=''

for i in meat:
match=col.find(i)
if match:
mind[match.group(1)]=[]
matching=match.group(1)
match=datas.find(i)
if match:
mind[matching].append([match.group(1),match.group(2)])


That would collect the data and put it into a dictionary with the values 
being a list of the two part data. You could print like this:

for each in mind.keys():
print each
for value in mind[each]:
print each+""+value[0]+""+value[1]


That should do it!

Ask if you don't understand any part of it.

Allen J. Schmidt, Jr.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Please Help: Hacking

2005-07-22 Thread byron
Quoting Jeremy Jones <[EMAIL PROTECTED]>:
> Here you go.  This should be enlightening:
>
> http://www.catb.org/~esr/writings/unix-koans/script-kiddie.html

Hi Jeremy,

That's great...  Thanks for sharing the link.

Byron
---



This message was sent using IMP, the Internet Messaging Program.

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Please Help: Hacking

2005-07-22 Thread Jeremy Jones
Suranga Sarukkali wrote:

> Python's Great fro Hacking Right? Please tell me more like when you 
> tell it to a College Student (That tell's What I'm) and since I 
> Sort of new to Programming in Python it's going be easy if done so. 
> Please reply to me at your earliest convenience and by the way General 
> Hacking Education will be Cool since the only hacking I've done is on 
> a Hacking Simulation Game I downloaded yeas ago from 
> http://g1.acid-play.com/download/a599b964/Hackerv1.zip witch got all 
> the tools like Password Crackers Inbuilt to Simulate Hacking Large 
> Company's and making cash from it. You can privately email me on 
> [EMAIL PROTECTED] 
>  
> I've been on the Mailing List some time and It's Great! Thanks for the 
> People Developed it.
>
>___
>Tutor maillist  -  Tutor@python.org
>http://mail.python.org/mailman/listinfo/tutor
>  
>
Here you go.  This should be enlightening:

http://www.catb.org/~esr/writings/unix-koans/script-kiddie.html


Jeremy Jones
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Please Help: Hacking

2005-07-22 Thread Adam Bark
How to become a hackerOn 7/17/05, Suranga Sarukkali <
[EMAIL PROTECTED]> wrote:






Python's Great fro Hacking Right? Please tell me more like 
when you tell it to a College Student (That tell's What I'm) 
and since I Sort of new to Programming in Python it's going be 
easy if done so. Please reply to me at your earliest convenience and by the way 
General Hacking Education will be Cool since the only hacking I've done is on a 
Hacking Simulation Game I downloaded yeas ago from http://g1.acid-play.com/download/a599b964/Hackerv1.zip
 witch 
got all the tools like Password Crackers Inbuilt to Simulate Hacking Large 
Company's and making cash from it. You can privately email me on [EMAIL PROTECTED] 
 
I've been on the Mailing List some time and It's Great! Thanks 
for the People Developed it. 

___Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] PLEASE HELP ON PYTHON

2005-07-16 Thread Alan G
Hello,

> Downloaded from the Original WebSite

Did you get it installed OK? I'll assume you use Windows,
if another OS let us know which. Is there a Python menu
in your Start->Programs menu?

If you select Python GUI dows a window open called
Python Shell or similar? It should contain a prompt like

>>>

at which you can type Python commands.


> ...all that Tutorials available make it like hell to get started

Which tutorials have you used? The standard one that comes with Python
is intended for experienced programmers converting to Python. There
is a separate page of tutorials for non programmers (Including mine)?

Have you tried any of those ones? If so which?
They all have strengths and weaknesses.

If you are stuck at a particular biyt then ask questions here, the
more specific the better. Also if you can include any error messages
that Python presents that will help a lot. They may look meaningless
to a beginner but they actually contain a lot of useful information
once you learn how to read them!

Alan G
Author of the Learn to Program web tutor
http://www.freenetpages.co.uk/hp/alan.gauld 

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] PLEASE HELP ON PYTHON

2005-07-16 Thread Rob Andrews
On 7/15/05, Suranga Sarukkali <[EMAIL PROTECTED]> wrote:
>  
> Hai, I (Suranga) started using Python2.4 Downloaded from the Original
> WebSite www.python.org a week ago but still I have not made any good
> progress on Programming and all that Tutorials available make it like hell
> to get started at all! whatever please tell me on [EMAIL PROTECTED] how to
> get started and start programming and since I never programmed before or
> haven't done any big Math Tests but a k-12 School still I'm a Student of 14
> but I'm loving the name programming even, reply to me as soon as possible. 

We'll be happy to help.

What sort of programming interests you? Since I'm one of the world's
most incompetent programmers and find that I can work out the
occasional python program, I'm sure you'll be just fine.

There are quite a few tutorials to help get you started. Have you
checked out: http://hkn.eecs.berkeley.edu/~dyoo/python/idle_intro/index.html
?

namaste,
Rob
-- 
Golf with an attitude:
http://www.ragingolf.com/
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] PLEASE HELP ON PYTHON

2005-07-16 Thread Brian van den Broek
Suranga Sarukkali said unto the world upon 16/07/2005 00:18:
> Hai, I (Suranga) started using Python2.4 Downloaded from the
> Original WebSite www.python.org a week ago but still I have not
> made any good progress on Programming and all that Tutorials
> available make it like hell to get started at all! whatever please
> tell me on [EMAIL PROTECTED] how to get started and start
> programming and since I never programmed before or haven't done any
> big Math Tests but a k-12 School still I'm a Student of 14 but I'm
> loving the name programming even, reply to me as soon as possible.


Hi Suranga,

welcome to this list and to Python!

I think you have found one of the very best resources for learning 
Python, so you are off to a good start. The way to use this list best, 
in my opinion, is to post specific questions. Questions with some code 
are even better. (It is hard for people to know what would help you 
without seeing what you don't understand.)

The people who do a lot of answering here are very patient -- they've 
put up with all sorts of questions from me :-)

One tutorial I think you might find useful is 
. It is aimed at high school 
students, but does not condescend. Why don't you try that from the 
beginning, and when stuck on something, post here asking about it?

Best of luck.

Brian vdB

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] please help

2005-07-10 Thread Alan G
> The line that Ive been writing (of course wrong
> script):
> 
> f1 = open('myfile','r')
> stuff = f1.read().split('\n')
> for i in stuff:
>   if i != '//':
>trcode = line.split('\t')[0]
>trquant = line.split('\t')[1]
>print trcode+'\t'+trquant
> 

You use i in the for loop but line in the code block inside?

try

for line in file('myfile'):
   if line != '\\':
  trcode = line.split('\t')[0]
  etc...

HTH,

Alan G.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] please help

2005-07-10 Thread Danny Yoo


On Sun, 10 Jul 2005, Srinivas Iyyer wrote:

> I have a file that looks like this:
>
> //
> AB32456\tTransaction from India
> \t 43 \t 34
> \t 34 \t 65
> \t 12 \t 35
> //

[some lines cut]


> What I have to do:
> //
> AB32456\tTransaction from India
> AB32456\t 43 \t 34
> AB32456\t 34 \t 65
> AB32456\t 12 \t 35

[some lines cut]


Ok, so it looks like we want to then remember the first column at the
beginning of a transaction, and then have duplicate that value for the
rest of the transaction.  Let's look at what you have so far.

> f1 = open('myfile','r')
> stuff = f1.read().split('\n')
> for i in stuff:
>if i != '//':
> trcode = line.split('\t')[0]
> trquant = line.split('\t')[1]


It might help to simplify the problem a little.  I think you might be
getting stuck because you're trying to handle the '\\' end of a
transaction as well as the column value-trickling stuff, so there's a bit
of mixing going on.


One way to simplifying a problem is to concentrate on handling a single
thing.  Let's say that we have a list of lines from a single transaction:

##
sample_data = ["AB32456\tTransaction from India",
   "\t 43 \t 34",
   "\t 34 \t 65",
   "\t 12 \t 35"]
##

Can you transform these lines so that the AB32456 value trickles into the
other lines of the transaction?  Don't worry about "//" stuff at all in
this subproblem.

Try handling this first: it's the core of your program anyway, so might as
well figure that part out.  *grin*


If you have more questions, please feel free to ask.  Best of wishes to
you!

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Please help me get started on how to program useing python 2.4!!! (fwd)

2005-03-11 Thread Danny Yoo
[Forwarding to [EMAIL PROTECTED]  Sorry about the repetition.]


-- Forwarded message --
Date: Fri, 11 Mar 2005 17:18:03 EST
From: [EMAIL PROTECTED]
To: [EMAIL PROTECTED]
Subject: Re: [Tutor] Please help me get started on how to program useing
python 2.4!!!

ok heres where i got the for,in, and
rangehttp://hkn.eecs.berkeley.edu/~dyoo/python/idle_intro/index.html
and i tryed what it say and the...print "hello world"..and the next step
works...print "here are the ten numbers from 0 to 9".but the next dose 
not...
for i in range(10):
  print i,..


___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Please help me get started on how to program useing python 2.4!!! (fwd)

2005-03-11 Thread Danny Yoo
[Forwarding to [EMAIL PROTECTED]  Please use your email client's
"Reply-to-all" feature whenever you're replying to messages on the tutor
list.  Otherwise, no one else gets to see your questions.]


-- Forwarded message --
Date: Fri, 11 Mar 2005 17:07:15 EST
From: [EMAIL PROTECTED]
To: [EMAIL PROTECTED]
Subject: Re: [Tutor] Please help me get started on how to program useing
python 2.4!!!

ok i understand some of that like the = things being ture or false but i am
not realy wanting to know if its = or not, i was just trying to figer out how
to make a progarm or just program... and figer out the language..lol.if you
can help me do that i would
be realy thankful

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


  1   2   >