snippsat 661 Master Poster

Can clean it up little.

import random

count = 0
for x in range (100):
    i = random.randint(1,10)
    if i == 3:
        count = count + 1    
print count

There are other way to write this,here is one.

>>> import random
>>> [random.randint(1,10) for i in range(100)].count(3)
7
snippsat 661 Master Poster

Use "else" block.

if andexfield == elem:
    do bladibla
else:
    print "Error, no andexfield in fname" 

Error would be more normal to occur before you compare with ==.
Like open file or get index/iterate list lstData[0] lstLine[1:]

snippsat 661 Master Poster

thanks but why doesn't the sleep work...?

If you look at the documentation for time.sleep(), you see that it basically blocks execution of that thread for the specified interval.
The problem is that GUI is a single thread,so if you block the thread then you block all execution in that thread.
This means that the GUI is unusable during the sleep and will in may cases lock up.

Most GUI toolkit has bulid in soultion for this.
In Tkinter it's after
Wxpython has wx.timer

snippsat 661 Master Poster

a = [0,1,2,3,4,5,6,7,8,9]

a[0]=input()
a[1]=input()
a[2]=input()
a[3]=input()
a[4]=input()
a[5]=input()
a[6]=input()
a[7]=input()
a[8]=input()
a[9]=input()

In Python we dont like long code that dos repating stuff.

>>> [int(raw_input('Enter numbers: ')) for i in range(10)]
[90, 5, 27, 63, 12, 47, 10, 150, 120, 40]

After sorting you can use zip() to make number par.

>>> lst
[5, 10, 12, 27, 47, 48, 63, 90, 120, 150]
>>> zip(lst,lst[1:])
[(5, 10),
 (10, 12),
 (12, 27),
 (27, 47),
 (47, 48),
 (48, 63),
 (63, 90),
 (90, 120),
 (120, 150)]

The next step can be to iterate over number par and and get subtract result.
Then from that list take out min() number index value in zip() list.

So here is here is my version,not tested probably only with this list.

def foo(lst):
    lst = sorted(set(lst))
    number_par = zip(lst,lst[1:])
    lowest_par_result = [abs(y-x) for x,y in number_par]
    lowest_par_index = lowest_par_result.index(min(lowest_par_result))
    return number_par[lowest_par_index]

lst = [90, 5, 27, 63, 12, 47, 10, 150, 120, 48]
print foo(lst) #(47, 48)
Gribouillis commented: best n*log(n) approach +13
snippsat 661 Master Poster

The file i use num.txt is just a copy of contend in your post.
I have tested code in python 2.7 and 3.2,works fine for me.

darealsavage commented: yea i think i know why, i have to run the whole program in unix i think its called?, we just call it terminal. it's like a command prompt on linux. im all about ready to just give up for this one haha.. +0
snippsat 661 Master Poster

also i still have no idea how to just import the excell spreadsheet into python to use,

You most use using something like xldr
A example of use here by Gribouillis.

ive also tryed just using the numbers in a .txt file.. like so.

An example of how to do this,and doing som calulation.

with open('num.txt') as f:
    numb_list = [[float(i) for i in list(i.strip())] for i in f]

for index,numbs in enumerate(numb_list, 1):
    print('{:<2} {} : {:.2f} {}'.format(index,numbs, sum(numbs)/len(numbs), sum(numbs)))

"""Output-->
1  [0.0, 0.0, 2.0, 0.0, 5.0, 6.0, 3.0, 0.0] : 2.00 16.0
2  [5.0, 1.0, 9.0, 0.0, 0.0, 2.0, 3.0, 2.0] : 2.75 22.0
3  [0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0] : 0.12 1.0
4  [1.0, 1.0, 1.0, 0.0, 2.0, 2.0, 2.0, 1.0] : 1.25 10.0
5  [5.0, 3.0, 2.0, 0.0, 0.0, 2.0, 5.0, 5.0] : 2.75 22.0
6  [2.0, 2.0, 1.0, 0.0, 1.0, 1.0, 0.0, 0.0] : 0.88 7.0
7  [3.0, 2.0, 5.0, 0.0, 1.0, 2.0, 0.0, 4.0] : 2.12 17.0
8  [3.0, 0.0, 7.0, 1.0, 3.0, 5.0, 2.0, 4.0] : 3.12 25.0
9  [0.0, 2.0, 6.0, 1.0, 0.0, 5.0, 2.0, 1.0] : 2.12 17.0
10 [4.0, 0.0, 2.0, 0.0, 3.0, 2.0, 1.0, 0.0] : 1.50 12.0
11 [1.0, 1.0, 1.0, 0.0, 2.0, 2.0, 2.0, 1.0] : 1.25 10.0
12 [5.0, 3.0, 2.0, 0.0, 0.0, 2.0, 5.0, 5.0] : 2.75 22.0
"""
darealsavage commented: @snippsat hey thanks for trying to help me, i tryed using your method but i get an error saying cant convert string to float: ',' +0
snippsat 661 Master Poster

Looking at code you are doing some stuff that are not so good.
str(idList[index][:-1] this is not nessessay and don't do it inside open()
Look at this.

""" url.txt
ttp://www.youtube.com/
ttp://www.google.no/
ttp://www.sol.no/
""" 

with open('url.txt') as f:
    idList = [item.strip() for item in f]

print idList
#--> ['ttp://www.youtube.com/', 'ttp://www.google.no/', 'ttp://www.sol.no/']

As you see i get a list list without \n
Some test code you can lok at.

>>> index = 0
>>> for i in range(3):
...     i, idList[index]
...     index +=1
...     
(0, 'ttp://www.youtube.com/')
(1, 'ttp://www.google.no/')
(2, 'ttp://www.sol.no/')
>>> for i in range(4):
...     i, idList[index]
...     index +=1
...     
Traceback (most recent call last):
  File "<interactive input>", line 2, in <module>
IndexError: list index out of range

This can be shorter look at this.

>>> for i in range(3):
...     i, idList[i]
...     
...     
(0, 'ttp://www.youtube.com/')
(1, 'ttp://www.google.no/')
(2, 'ttp://www.sol.no/')
>>> for i in range(4):
...     i, idList[i]
...     
...     
(0, 'ttp://www.youtube.com/')
(1, 'ttp://www.google.no/')
(2, 'ttp://www.sol.no/')
Traceback (most recent call last):
  File "<interactive input>", line 2, in <module>
IndexError: list index out of range
snippsat 661 Master Poster

As posted over the full Traceback tell you where in code you get the error.

Im getting an index out of range error? Please help!

So to make a index out of range error.

>>> l = [1,2,3,4]
>>> l[3]
4
>>> l[4]
Traceback (most recent call last):
  File "<interactive input>", line 1, in <module>
IndexError: list index out of range

The print statement explain what happened.

>>> try:
        l[4]
    except IndexError:  
        print "Trying to access an item in a list that isn't there"

Trying to access an item in a list that isn't there
snippsat 661 Master Poster

This will do it,try not to use bare except.
except (<some error>, <another error>)

You can also use except IOError as error: print error
This will give you an error message with specific information about the caught exception.

def file_exists():
    while True:
        file_name = input("Enter a file name: ")
        try:
            with open(file_name) as a_file:
                return a_file.read()
        except IOError:
            print('No file with name: <{}> found'.format(file_name))
            pass

print file_exists()
snippsat 661 Master Poster

I did not flag it was happygeek,read Comments.

The code you gave me does not allowed the people to type quit to quit in the middle of the game.

I can change code so that is possible,but what's the logic in that?
The user get a chooice of how many question,if user choose 4 question the he/she get 4 question.
Maybe user get tired after 3 and want to quit.

woooee commented: Up vote for excellent logic +13
snippsat 661 Master Poster

Hi rrashkin nice to see you here,do you know status of "python-forum.org"?

snippsat 661 Master Poster

dean.ong.14 you have asked this qustion before.
In the last post i tok time to structured and change code for a better soultion,did you even look at that?
http://www.daniweb.com/software-development/python/threads/438691/import-random-failed..-please-help-me#post1886678

snippsat 661 Master Poster

You can read direct from web,then you dont have to save and read from txt.
This way you always get uppdatet info when website change.
Example.

from bs4 import BeautifulSoup

#Use urllib to read html source code
html = '<b>Mostly Cloudy, 50 F</b>'

soup = BeautifulSoup(html)
tag = soup.find('b')
weather_info = tag.text.split(',')

#Text that can go into speak engine
print 'Today`s weather will be {} and temprature of{}.'.format(weather_info[0], weather_info[1])
#--> Today`s weather will be Mostly Cloudy and temprature of 50 F.
snippsat 661 Master Poster

i have to copy paste my downloaded python packages for them to work?

You do not copy/paste into site-packages folder yourself,you can but that's not the correct way(and it may not work).

3 methods:
First the manual way.
You download a packages extract to where-ever you want.
From command line cmd naviagte to extract folder then write python setup.py install
Under this install will files go to site-packages folder and package is installed.

There are two tool for eaiser install easy_install and pip(recommended)
pip also have an uninstall function for packages.
Both of these tool will download a package from web and install it.
So as an example from cmd you write pip install numpy then download and install happens automatically.

Rembere to check environment variables Path
In Path if not there add ;C:\python27\;C:\python27\scripts
Or for python 3 ;C:\python33\;C:\python33\scripts
Restart to make it work.
This can be needed to be correct for all method i postet over to work fine.

snippsat 661 Master Poster

If you want to use getter/setter you follow advice from JasonHippy,i have tested it and it's works.
If you wanne use my code is complete in my last post.
Dont mix stuff together.

the book wants them there (and I'm graded on if I do what the book asks)

If you want to learn python you can burn that book,and get a book that learn you python in a correct manner
and not mixing in stuff from other languages that dos not make any sense in python.

snippsat 661 Master Poster

using this code with the above class for Triangle and GeometricObject from snippsat. If I use the get and set for for color and filled I get a traceback error that says GeometricObject has no attribute setColor. What can I do to get the color and filled properties to display?

If you are gone use my class you can of course not use old method name from your class.
So if i also put in __str__ method it can look like this.

from math import sqrt

class GeometricObject:
    def __init__(self, color="green", filled=True):
        self.color = color
        self.filled = filled

    def __str__(self):
        return 'Color {} and filled {}'.format(self.color, self.filled)    

class Triangle(GeometricObject):
    def __init__(self, side1=1, side2=1, side3=1):
        super().__init__()
        self.side1 = float(side1)
        self.side2 = float(side2)
        self.side3 = float(side3)

    def calulate(self):
        self.perimeter = self.side1 + self.side2 + self.side3
        s = (self.side1 + self.side2 + self.side3) / 2
        self.area = sqrt(s* (s-self.side1) * (s-self.side2) * (s-self.side3))

    def __str__(self):
        return "Triangle:\nside 1 = {}\n"\
                         "side 2 = {}\n"\
                         "side 3 = {}".format(self.side1,self.side2,self.side3)

# User input
side1 = 3.0
side2 = 4.0
side3 = 5.0
color = 'Yellow'
filled = 1 

Use it:

>>> go = GeometricObject(color, filled)
>>> tri = Triangle(side1, side2, side3)
>>> print('{}\n{}'.format(tri, go))    
Triangle:
side 1 = 3.5
side 2 = 4.0
side 3 = 5.0
Color Yellow and filled 1

>>> tri.calulate()
>>> print("The area is: ", tri.area)
The area is:  6.0

>>> print("The perimeter is: ", tri.perimeter)
The perimeter is:  12.0

>>> tri.side1
3.0    
>>> tri.side1 …
snippsat 661 Master Poster

JasonHippy has give advice of why you get that error and how to fix it.
If you scrap the setArea and setPerimeter method and use recalculate it look like this.

>>> tri = Triangle(side1, side2, side3)
>>> tri.recalculate()
>>> tri.getArea()
11.61895003862225
>>> tri.getPerimeter()
18.0
>>> tri._GeometricObject__color
'green'

So a rewrite to get the same.

from math import *

class GeometricObject():
    def __init__(self, color = "green", filled = True):
        self.color = color
        self.filled = filled

class Triangle(GeometricObject):
    def __init__(self, side1=1, side2=1, side3=1):
        super().__init__()
        self.side1 = float(side1)
        self.side2 = float(side2)
        self.side3 = float(side3)

    def calulate(self):
        self.perimeter = self.side1 + self.side2 + self.side3
        s = (self.side1 + self.side2 + self.side3) / 2
        self.area = sqrt(s* (s-self.side1) * (s-self.side2) * (s-self.side3))

    '''
    side1 = 8
    side2 = 4
    side3 = 6
    color = 'Yellow'
    filled = 1
    '''

Use it:

>>> tri = Triangle(side1, side2, side3)
>>> tri.calulate()
>>> tri.area
11.61895003862225
>>> tri.perimeter
18.0
>>> tri.color
'green'

Do not use use eval
side1 = int(input("Enter a value for side 1: "))

Actually, I have a C# background and the book is written to be a step into Java

Please do not try to learn any programming language by leveraging knowledge of another programming language.
Programming languages (with a few exceptions) are more different than alike.
It's much easier on your brain to start "from scratch" when learning a new language.
Try to avoid comparing syntax or semantics between languages.

snippsat 661 Master Poster

No one can help if you dont give more info than this,should not be so hard to understand.
Here one with same error,he post where in code error come from and full traceback.
http://stackoverflow.com/questions/8164704/text-to-xml-in-python

snippsat 661 Master Poster

I think you have teacher with java background.

There are really no need for getters/setters in both of these Class.
Java programmers will often introduce private members, and then add getters and setters.
This is evil; the attribute should have been public in the first place.

Something to read Python is not Java

Getters and setters are evil. Evil, evil, I say! Python objects are not Java beans. Do not write getters and setters. This is what the 'property' built-in is for. And do not take that to mean that you should write getters and setters, and then wrap them in 'property'. That means that until you prove that you need anything more than a simple attribute access, don't write getters and setters. They are a waste of CPU time, but more important, they are a waste of programmer time. Not just for the people writing the code and tests, but for the people who have to read and understand them as well.

Just a demo with GeometricObject class.
Use it:

>>> c = GeometricObject('Yellow', False)
>>> c._GeometricObject__color
'Yellow'
>>> c._GeometricObject__filled
False
>>> c._GeometricObject__color = 'Black'
>>> c._GeometricObject__filled = True
>>> c._GeometricObject__color
'Black'
>>> c._GeometricObject__filled
True

Rewrite it.

class GeometricObject():
    def __init__(self, color = "green", filled = True):
        self.color = color
        self.filled = filled

        def __str__(self):
            return 'Color {} and filled {}'.format(self.color, self.filled)

Use it:

>>> c = GeometricObject('Yellow', False)
>>> c.color
'Yellow'
>>> c.filled
False
>>> c.color …
snippsat 661 Master Poster

That's not the whole traceback.
Post whole traceback and code where traceback occur.

snippsat 661 Master Poster

As postet Lardmeister there are no official wxpython version for python 3 yet.

The porting to python 3 is under way with Project Phoenix
http://wiki.wxpython.org/ProjectPhoenix

There are working version to test here.
http://wxpython.org/Phoenix/snapshot-builds/

I have tested code over and it work in python 3.2.

snippsat 661 Master Poster

Yes a for loop and using comparison operators will work.
Here is a hint.

t = (20, 58, 70, 92, 98)
A,F = 0,0

for mark in t:
    if mark < 60:
        F += 1
    elif mark >= 90:
        A += 1
    else:
        pass

print('{} people got A\n{} people got F'.format(A, F))

Run this,here i use list comprehension,it can be written without and just append to a list.
Just to show that a loop can save you from writing test1,test2.....

score_lst = [int(input('What is the score of test number {}? '.format(i))) for i in range(1,6)]
print(score_lst)
snippsat 661 Master Poster

I just need the output [' 6', ' 4.5', ' 10', ' 4', ' 10'] to be (' 6', ' 4', ' 10', ' 4', ' 10')

>>> lst = [' 6', ' 4.5', ' 10', ' 4', ' 10'] 
>>> [str(int(float(i))) for i in lst] 
['6', '4', '10', '4', '10']
snippsat 661 Master Poster

Based on previous post this is your output.
[' 6', ' 4.5', ' 10', ' 4', ' 10']

#print(grade)
#string_grades = str(grade)
print([float(i) for i in grade]) # [6.0, 4.5, 10.0, 4.0, 10.0]
print([i.strip() for i in grade]) #Clean string list ['6', '4.5', '10', '4', '10']
print(','.join([i.strip() for i in grade])) #Only string 6,4.5,10,4,10

You have made code worse,follow advice you did get in previous post.
http://www.daniweb.com/software-development/python/threads/439406/reading-a-.txt-file
Do not use readline() two times and do not use file as variable name,file is a reserved word used by python.

With some Pythonic power it can also look like this.

with open('grade.txt', 'r') as inFile:
    lst = [i.strip().split(',') for i in inFile]
    print [float(i) for i in lst[1][-5:]] #[6.0, 5.5, 8.0, 10.0, 8.5]
snippsat 661 Master Poster

how would i convert the output to a list?

with open('grade.txt') as in_file:
    lst = [i.split(',') for i in in_file]
print(lst)

If you don't want new line(\n),use i.strip().split(',')

snippsat 661 Master Poster

You are doing some strange stuff.
Do you get urllib to work for this site?

import urllib2

url = "http://www.blah.fi/"
read_url = urllib2.urlopen(url).read()
print read_url #403 error

This site are blocking use of urllib.
I had to use Requests to get source code.

You can use BeautifulSoup to get all link,no need to use regex.

import requests
from bs4 import BeautifulSoup

url = "http://www.blah.fi/"

url_read = requests.post(url)
soup = BeautifulSoup(url_read.content)
links = soup.find_all('a', href=True)
for link in links:
    print link['href']

urllib2.urlopen('http://www.blah.fi/' + link).read() is this really what you want?

Will give you output like this.

>>> 'http://www.blah.fi/' + 'http://v-reality.info/' + '<hr>'
'http://www.blah.fi/http://v-reality.info/<hr>'

soup = BeautifulSoup(open(html)) not this way,the normal way is.

url = urllib2.urlopen("http://www.blah.fi/")
soup = BeautifulSoup(url) 
tag = soup.find_all(Do stuff you want)

IOError: [Errno 36] File name too long:
The error is pretty clear,put i do not understand that it come from line 3.
A filename can not be longer than 255 character.
Look at output from content = soup.find(id="content")

print content
print type(content)
print repr(content)

I'm not really sure how to test a python library for successful installation though.

import bs4
>>> bs4.__version__
'4.1.0'
>>> from bs4 import BeautifulSoup
>>> print BeautifulSoup.__doc__
#You get description if it work
snippsat 661 Master Poster

Schol-R-LEA you have a couple of mix up(typo error)
while sum in point: while result in point:
Should be if sum in point: no in statement in while loop.

Sorry I guess I should explain after the player rolls the sum of the two die that is 4,5,6,8,9,10 that becomes a point then the game proceeds thru phase 2. So I was trying to create a loop that would do that

Here are som code you can look at.
Se how i have small functions that dos a specific task,and not one big main() function with all code.
You only reach phase 2 function if dice sum is in (4,5,6,8,9,10).
Where you can code some stuff for phase 2.

from random import randint

def dice():
    '''Return sum of two dice trown'''
    return(sum(randint(1,6) for item in range(2)))

def check_score(dice_sum, point):
        if dice_sum in point:
            return dice_sum
        return 0

def phase_2():
    print('welcome to phase_2')
    input('Press enter to exit')

if __name__ == '__main__':
     point = (4,5,6,8,9,10)
     dice_sum = dice()
     check_score = check_score(dice_sum,point)
     #---
     print('Phase_1 your dice sum has to be equal one of these numers(4,5,6,8,9,10)\n')
     if check_score == 0:
        print('Wrong dice sum, Game over')
     else:
        print('Your sum of dice trow was {}'.format(check_score))
        phase_2()
snippsat 661 Master Poster

it apears that when slicing with a negative step, the start and endpoints need to be reversed

With negative step values,slicing will automatically step into in Alice in Wonderland reversed world.

Like this we can look at vaules for seq[start:stop:step]

>>> seq = '123456789'
>>> slice(None,None,1).indices(len(seq)) #[::1] 
(0, 9, 1)
>>> seq[::1]
'123456789'

>>> slice(None,None,-1).indices(len(seq)) #[::-1] 
(8, -1, -1)
>>> seq[::-1]
'987654321'

With this knowledge the rules are simple.
start and stop values will always be the same for posetive step values(default is step=1)
start and stop values will always be the same for negative step values.

We can test that this is True.

#Posetiv step 
>>> seq[::4]
'159'
>>> slice(None,None,4).indices(len(seq)) 
(0, 9, 4)

#Negative step 
>>> seq[::-4]
'951'
>>> slice(None,None,-4).indices(len(seq)) 
(8, -1, -4)
snippsat 661 Master Poster

I have structured code better by using functions and some changes/corrections.
This make it easier to test code and as you want start and stop the quiz.

import random

try:
    input = raw_input
except:
    pass

def all_quest():
    '''All questions that can be used'''
    questions = [("Denis Glover wrote the poem The Magpies ", 'yes'),
    ("God Save the King was New Zealand’s national anthem up to and including during WWII ", 'yes'),
    # several lines omitted for clarity...
    ("Kiri Te Kanawa is a Wellington-born opera singer ", 'no'),
    ("Phar Lap was a New Zealand born horse who won the Melbourne Cup ", 'yes'),
    ("Queen Victoria was the reigning monarch of England at the time of the Treaty ", 'yes'),
    ("Split Enz are a well-known rock group from Australia who became very famous in New Zealand during the 80s ", 'no'),
    ("Te Rauparaha is credited with intellectual property rights of Kamate! ", 'yes'),
    ("The All Blacks are New Zealands top rugby team ", 'yes'),
    ("The Treaty of Waitangi was signed at Parliament ", 'no'),
    ("The Treaty of Waitangi was signed in 1901 ", 'no'),
    ("Aotearoa commonly means Land of the Long White Cloud ", 'yes')]
    random.shuffle(questions)
    return questions

def numb_of_quest(questions):
    '''Return the number of questions to be asked'''
    while True:
        try:
            maxQuestions = int(input("Enter the number of questions to ask (more than 0 and less than to {0}): ".format(len(questions))))
            if 0 <= maxQuestions < len(questions):
                return (maxQuestions)
            else:
                print('Not between 0 and {},try again\n'.format(len(questions)))
        except Exception as e:
            print("Please enter …
snippsat 661 Master Poster

If only value 0xFFFF has duplicate vaules,then set() would be fine.

>>> lst = [0x123D, 0x844F, 0x33E9, 0xFFFF, 0xFFFF, 0xFFFF]
>>> set(lst)
set([4669, 13289, 33871, 65535])

If you want to keep duplicate vaules before 0xFFFF,lety say 0x844F and 0x844F.
Then set() is not way.

snippsat 661 Master Poster

Yes with open(...) always close the file object when a iteration has finished.

The advantage of using a with statement is that it is guaranteed to close the file no matter if nested block exits.
If the nested block were to contain a return statement,or a continue or break statement,
the with statement would automatically close the file in those cases too.

In the background with statement dos exception handling(try-finally)
Look like this at the end.

finally:
    f.close()
snippsat 661 Master Poster

Some additional info.
Sometime it can convenient to not type in filename manually,but extract filename from url.
Like when downloading more than one image or iterate over a list of url`s.

strip() is not needed here for a single image.
But can be needed if iterating over many url`s to strip of new line(\n)

import webbrowser
try:
    # Python2
    from urllib import urlretrieve
except ImportError:
    # Python3
    from urllib.request import urlretrieve

url = "http://www.google.com/intl/en/images/logo.gif"

# Take out filname from url
filename = url.strip().split('/')[-1]
urlretrieve(url.strip(), filename)
print("image saved as {}".format(filename))

# try to show the saved image file ...
webbrowser.open(filename)
snippsat 661 Master Poster
>>> m = 1
>>> oldVelocity = m.v
Traceback (most recent call last):
  File "<interactive input>", line 1, in <module>
AttributeError: 'int' object has no attribute 'v'

As it say int object has no attibute 'v'
The dot "." is the member access operator.
Generally an object of a class has attributes/methods.
So as an example i do this.

>>> class Foo:
        v = 100

>>> m = Foo()
>>> m.v
100

Or.

>>> class Foo:
        @property        
        def v(self):
            return 5000

>>> m = Foo()
>>> m.v
5000

Here you see a class Foo that has attribute and method v.
So int class has no attribute/methods that is called v and give and error.

That was the long explanation of the error,maybe it was just and type error as pyTony metion.

snippsat 661 Master Poster

As posted over we need more info,like input data.
Code use Numpy and it use function add() and dot().
To see what these numpy function dos,look into numpy doc here is add()
To test function so it work i guessed for a nested list as input data.

from numpy import *

def CalcCentre(data):
    centre = array([0,0,0])
    count = 0
    for p in data:
        centre = add(centre, array(p[:3]))
        count += 1
    centre = dot(1./count, centre)
    return centre

print CalcCentre(array([[1,2,3], [4,5,6]]))
#--> [ 2.5  3.5  4.5]
Gribouillis commented: well spotted +13
snippsat 661 Master Poster

I get the step value counting down and was able to get the correct outcome but I am confused on the ending value (-1) and why that made it work.

>>> start = 7
>>> stop = 1
>>> step = -1
>>> for r in range(start,stop,step):
        r        
7
6
5
4
3
2

>>> help(range)
Help on built-in function range in module __builtin__:

range(...)
    range([start,] stop[, step]) -> list of integers

    Return a list containing an arithmetic progression of integers.
    range(i, j) returns [i, i+1, i+2, ..., j-1]; start (!) defaults to 0.
    When step is given, it specifies the increment (or decrement).
    For example, range(4) returns [0, 1, 2, 3].  The end point is omitted!
    These are exactly the valid indices for a list of 4 elements.
snippsat 661 Master Poster

I see you have get good help from Gribouillis.
As a note with open was new in python 2.5.
python 2.2.1 is really old.
Alternatives is to write your own parser that works for your files,it`s not so hard.
If i use config file postet by Grib.

cfg_dict = {}
lst = []
cfg_file = open('essconfig.cfg')
for line in cfg_file:
    if '-' and not '=' in  line:
        line = line.split()
        line.append('None')
        lst.append( line)
    else:
        line = ''.join(line.strip().split('=')).split()
        lst.append(line)
cfg_file.close()

for item in lst:
    cfg_dict[item[0]] = item[1]
print cfg_dict

Test it.

>>> cfg_dict['old_passwords']
'1'
>>> cfg_dict['pid-file']
'/var/run/mysqld/mysqld.pid'
>>> cfg_dict['skip-bdb']
'None'
>>> cfg_dict['user']
'mysql'
snippsat 661 Master Poster

to cups.')) is missing line 5.

snippsat 661 Master Poster

ok lets say every character is 3 digits. i want to read from file and print each character. How to do this?

Something like this.

def foo(filename, chunks):
    with open(filename) as f:
        numb_list = list(f.read())
        return [numb_list[i:i+chunks] for i in range(0, len(numb_list), chunks)]

lst = foo('data.txt', 3)
for item in lst:
    print chr(int(''.join(item)))

"""Output-->
h
e
l
l
o
"""
snippsat 661 Master Poster

But I believe that this is not the best way of writing the program. If you look at the while loop, the condition will never evaluate to true. Is this right?

Yes that loop will not work,only way that will work if you guess right on first attempt.
It better/clearer to use !=(not equal).
As long as guess !=(not equal) secret_number,the while loop will run.

So then it can look like this,see also that i use int(input("")).
so that we compare integer with integer(not string with integer).

#Python 3.x
import random

secret_number = random.randint(1,100)
attempts = 0
guess = 0
while guess != secret_number:
    guess = int(input("Enter Guess Here: ")) 
    if guess > secret_number:
        print('Lower...')
    elif guess < secret_number:
        print('Higher...')
    attempts += 1

print("You guessed it! The number was {0} in {1} attempts".format(secret_number, attempts))
snippsat 661 Master Poster

One more.

with open('original.txt', 'a') as f_out:
    for i in range(0,2):
        text = raw_input("Enter message:")
        f_out.write('{}\n'.format(text))
snippsat 661 Master Poster

To not use ugly "global",a more sensible solution would be to give functions arguments.

def file_read(file_in):
    with open(file_in) as f:
        return(f.read())

def lowercase_letter(text):
    return text.lower()

afile = file_read('savetonight.txt')
print lowercase_letter(afile)

jim.lindberg1 do not use norwegian name for function.

snippsat 661 Master Poster

A sample of input data would help,regex i use under may fail.

What I have been wresting with is getting my program to seemingly work with re.sub

>>> import re
>>> s = "abc [ k '0 ir e ] 123"
>>> re.sub(r'\[.*\]', 'k_ir_e', s)
'abc k_ir_e 123'

Remeber to close file object new.close()
Dont use file as variable name,that is a reserved word in python.
It is better to use with open(),then you dont need to close fileobject.

snippsat 661 Master Poster

enjoy:

Not so much to enjoy in that code.
You dont read file line by line as @vimalya mention.
With read() you read all file into memory.
del we almost never need to use in python.

Example.
data.txt-->

header
1 2 3
4 5 6
7 8 9

---

with open('data.txt') as f:
    line = f.next()
    for line in f:
        #print line
        #You can procces data like this 
        print [int(item) for item in line.split()]

"""Output-->
[1, 2, 3]
[4, 5, 6]
[7, 8, 9]
"""

Next time vimalya try to post some code,not just a task to solve.

snippsat 661 Master Poster

A regex version,but i do like Vega soultion better.

import re

def is_alpha_space(name):
    name_nospace = ''.join((name.split()))
    if re.search(r"\W", name_nospace) or len(name_nospace) < 1:
        return False
    return True

name = "Mark Zumkoff"
print(is_alpha_space(name))  # True

name = "Mark Zumkoff@"
print(is_alpha_space(name))  # False

name = "    "
print(is_alpha_space(name))  # False
snippsat 661 Master Poster

Can simplify code to this.

import re
from ftplib import FTP

with open('params.txt.txt') as f:
    ip = re.search(r"IP.*'(.*)'", f.read()).group(1)

ftp = FTP(ip)
ftp.login()

I made the changes but it still is not working. Now getting

Can be something like port,firewall problem or Active and Passive mode.
http://stackoverflow.com/questions/3451817/python-ftplib-timing-out

snippsat 661 Master Poster

You should uppgarde your pyS60 version if enumerate() not work.
enumerate() was new in python 2.3 in 2003.
It`s difficult to write/learn python if you cannot use features implemented last 10 years.

snippsat 661 Master Poster

I think pyS60 use python 2.5.4,then you have to use old string formatting like this.
You should of course mention in first post that you use pyS60.

import os

for numb,name in enumerate(os.listdir(".")):
    if name.endswith(".png"):
        os.rename(name, '%03i.png' % numb)
snippsat 661 Master Poster

Try.

import os

for numb,name in enumerate(os.listdir(".")):
    if name.endswith(".png"):
        os.rename(name, '{num:03d}.png'.format(num=numb))

Or.
http://people.csail.mit.edu/kapu/symbian/python_old.html

glob, fnmatch
Standard Python modules that are not part of PyS60 distribution, with slight modifications
so they work with PyS60.
Glob allows directory listing with wild cards, fnmatch is used by glob. Used by sync, btconsole.

snippsat 661 Master Poster

It`s simpel with python to,and this is a python forum.
@crishein14 save script in folder with files and run.

import os, glob

for numb,name in enumerate(glob.glob('*png')):
    os.rename(name, '{num:03d}.png'.format(num=numb))
Lardmeister commented: easy +10
snippsat 661 Master Poster

Colons(:) are basic and important in python.
Other languages use { } or other method to indicate/use a code block.
Python use indentation after colons(:) to indicate/use a code block.

word = 'hi'
if word == 'hi':
    print'Now this block get executed an word is equal to hi'
else:
    print'Now this block get executed an word is not equal to hi'

So it look like this.

print "Welcome to the English to Pig Latin translator!"
original = raw_input("Please enter a word: ")
pyg = "ay"
if len(original) >= 1 and original.isalpha():
    word = original.lower()
    first = word[0]
    #if word == a or e or i or o or u:
    if first in 'aeiou':
        print "Your first letter is a vowel"
    else:
        print "You'r first letter is a consonant"
        print "So your word is {}".format(original)
else:
    print "No word detected."
Gribouillis commented: nice help +13