snippsat 661 Master Poster

So are you happy with this code,do you have a question?
Just to post some code without any question is not helping anyone,it's just irritating.

snippsat 661 Master Poster

Some ways,but it can get ugly.
Code in my first post may be the way to go if you want that output.

Vegaseat way is't ok to use '\n'join() method.

>>> print '\n'.join(["%d %s" % pair for pair in enumerate(names)])
0 Google
1 Apple
2 Microsoft

Iterate over list comprehension and print result.

>>> lst = [pair for pair in enumerate(names)]
>>> for i in lst:
        print i[0], i[1]

0 Google
1 Apple
2 Microsoft

Not so nice but it work,maybe there is nicer ways to do this?

>>> print '\n'.join([' '.join([str(index), item]) for index, item in enumerate(names)])
0 Google
1 Apple
2 Microsoft

Or.

>>> print '\n'.join([str(pair[0]) + ' ' + pair[1] for pair in enumerate(names)])    
0 Google
1 Apple
2 Microsoft
snippsat 661 Master Poster

Ok here is list comprehension way.

>>> [(index, item) for index, item in enumerate(names)]
[(0, 'Google'), (1, 'Apple'), (2, 'Microsoft')]
Or.
>>> [pair for pair in enumerate(names)]
[(0, 'Google'), (1, 'Apple'), (2, 'Microsoft')]
snippsat 661 Master Poster
>>> names = ['Google', 'Apple', 'Microsoft']
>>> for index,item in enumerate(names):
        print index,item

0 Google
1 Apple
2 Microsoft
snippsat 661 Master Poster

You should almost never use global varible in function,it's ugly.
Function should take argument an return values out.
Some code you can look at.

#Ver_1
def foo():
    bar = "Just a string"
    return bar

print foo() #Just a string

#Ver_2
def foo(global_bar):
    bar = "Just a string and from ouside {}".format(global_bar)
    return bar

global_bar = "global Variable"
print foo(global_bar) #Just a string and from ouside global Variable

#Ver_3
def foo(global_bar="global Variable"):
    '''Here i use default argument'''
    bar = "Just a string and from default arg {}".format(global_bar)
    return bar

print foo() #Just a string and from default arg global Variable
snippsat 661 Master Poster

However, I don't use punctuation because it breaks any contractions in the text/word list

No problem just use signs in your code,then it will keep contractions.

text = "My!. @car%& can't be good"
print ''.join(c for c in text if c not in "!@#$%^&*().[],{}<>?") #My car can't be good
snippsat 661 Master Poster

You are removing element for nonwordlist in a loop,that's why it's blow up.
A rule is can be,never delete something from or add something to the list you are iterating over.

You can solve this in diffrent ways,the easiest for you now can be to make a copy of list.
for word in nonwordlist[:]:

A couple more tips.
Remove punctuation:

from string import punctuation

text = 'My!.= @car%&'
print ''.join(c for c in text if c not in punctuation) #My car

Read from file to a list,a little shorter than vega code.

with open("Encontract.txt") as fin:
    contrwords = [i.strip() for i in fin]
snippsat 661 Master Poster

Hi some problems with function inputs(),you need to retun values out and assign it to one or two variabels in main.
This should do it.

def inputs():
    '''Get input from user'''
    weight = float(input('Enter weight in pounds: '))
    height = float(input('Enter height in inches: '))
    return weight, height

def hw_to_bmi(weight, height):
    '''Calculate bmi'''
    bmi = (weight / (height * height)) * 703
    print('Your BMI is %.2f' % bmi)

def main():
    weight,height = inputs()
    hw_to_bmi(weight,height)
    print(hw_to_bmi.__doc__)
    help(inputs)

main()
snippsat 661 Master Poster

You don't need to include re it's a python build in module and cxFreeze will find it.
If you want to include moduls you also need to modify setup.

Here is a test i did with regex,as you see i include nothing.
If it work re_test.exe will output ['fast', 'friendly']

''''
Put "my_cx_freeze.py" and "re_test.py"(your script) in same folder.
Run it from command line(cmd) or terminal linux,navigate to folder with script.
Then type python my_cx_freeze.py build
'''

#my_cx_freeze.py
from cx_Freeze import setup,Executable

includefiles = []
includes = []
excludes = []
packages = []

filename = "re_test.py"
setup(
    name = 'myapp',
    version = '0.1',
    description = 'Re test',
    author = 'None',
    author_email = 'someting@my.org',
    options = {'build_exe': {'excludes':excludes,'packages':packages,'include_files':includefiles}},
    executables = [Executable(filename, base = None, icon = None)])

---

#re_test
import re

match = re.findall(r'\bf.*?\b', 'a fast and friendly dog')
print(match)
raw_input('Press enter to exit')
#input('Press enter to exit') #for python 3 use this
snippsat 661 Master Poster

Something like this look better,and 'do' is not used in Python.

s = 'ABsomething'
if s.startswith(('AB','CC','EF','US')):
    print '{}subroutine'.format(s[:2])
else:
    print 'Substring not found'
snippsat 661 Master Poster
>>> flowers = ['rose', 'bougainvillea', 'yucca', 'marigold', 'daylilly', 'lilly of the valley']
>>> thorny = []
>>> #First element in flowers list
>>> flowers[0]
'rose'

>>> #append first element to thorny list
>>> thorny.append(flowers[0])
>>> thorny
['rose']
>>> thorny.append(flowers[1])
>>> thorny
['rose', 'bougainvillea']
>>> thorny.append(flowers[2])
>>> thorny
['rose', 'bougainvillea', 'yucca']

>>> #Remember you can use help or look at Python doc
>>> help(thorny.append)
Help on built-in function append:

append(...)
    L.append(object) -- append object to end

>>> dir(thorny) 
#All function/methods you can use on list,look away from magic methods start with __.
snippsat 661 Master Poster

Some good example over,one more.
Running it interactive can help.
I keep function out from interactive environment,then it's eaiser to keep indentation.

def foo(x):
    print 'foo got called with argument', x
    def wrapped(y):
        return x * y
    return wrapped

Run it.

>>> foo
<function foo at 0x02AA1DB0>
>>> #Memory location of uncalled foo  

>>> foo(4)
foo got called with argument 4
<function wrapped at 0x029955B0>
>>> #We see foo get called and we get memory location of uncalled wrapped

>>> foo(4)(5)
foo got called with argument 4
20
>>> #Both function is called

>>> #So store it in a varible
>>> bar = foo(4)
foo got called with argument 4
>>> #So to get the same as over foo(4)(5)
>>> bar(5)
20
snippsat 661 Master Poster

Some hint that should help you.

>>> lst = [1,2,3,4,5,6]
>>> lst[:3]
[1, 2, 3]

#Assign to list thorny
>>> help(lst.append)
Help on built-in function append:

append(...)
    L.append(object) -- append object to end
#Or
>>> help(lst.extend)
Help on built-in function extend:

extend(...)
    L.extend(iterable) -- extend list by appending elements from the iterable

>>> #Concatenation of lists?
>>> ['Hello'] + ['world']
['Hello', 'world']
snippsat 661 Master Poster

The functional programming way with map() is short and fine for this.
In Python are list comprehension used much and in many cases more prefered than a functional style.

def to_numbers(str_list):
    return [int(i) for i in str_list]

lst = ['1', '2']
print to_numbers(lst)

If you wonder why i have changed to small letter and use _,look at PEP-8.

snippsat 661 Master Poster

Ok thanks.
If it's a school task deliver this for fun,and ask your teacher to explain it.

>>> sum(map(lambda x: str.split(x, ','), lst), [])
['10015', ' John', ' Smith', ' 2', ' 3.01', '10334', ' Jane', ' Roberts', ' 4', ' 3.81', '10208', ' Patrick', ' Green', ' 1', ' 3.95']
snippsat 661 Master Poster
lst = ['10015, John, Smith, 2, 3.01', '10334, Jane, Roberts, 4, 3.81' , '10208, Patrick, Green, 1, 3.95'] 
>>> new_lst = []    
>>> for data in lst:
        for item in data.split(','):
            new_lst.append(item)

>>> print new_lst
['10015', ' John', ' Smith', ' 2', ' 3.01', '10334', ' Jane', ' Roberts', ' 4', ' 3.81', '10208', ' Patrick', ' Green', ' 1', ' 3.95']
snippsat 661 Master Poster

and create a list of this form

That's not a list,if you want only those item in a new list.

lst = ['10015, John, Smith, 2, 3.01', '10334, Jane, Roberts, 4, 3.81' , '10208, Patrick, Green, 1, 3.95']
>>> lst[:2]
['10015, John, Smith, 2, 3.01', '10334, Jane, Roberts, 4, 3.81']

To get the output you show.

>>> new_lst = lst[:2]
>>> for data in new_lst:     
        for item in data.split(', '):
            print item

10015
John
Smith
2
3.01
10334
Jane
Roberts
4
3.81
snippsat 661 Master Poster

mac_address live alone in global space.
If you want it in your class you have pass it in as a instance variable or a agrument for for method resolve.

>>> from foo import Mac
>>> b = Mac(mac_address)
>>> b.resolve()
{'000000': 'xerox0', '000001': 'xerox1', '000002': 'xerox2'}

Or

class Mac:
    def __init__(self,hexmac):
        self.hexmac = hexmac

    def resolve(self, mac_address):
        return self.hexmac, mac_address

mac_address = { \
'000000':'xerox0', \
'000001':'xerox1', \
'000002':'xerox2', \
}

Use class.

>>> b = Mac('123')
>>> b.resolve(mac_address)
('123', {'000000': 'xerox0', '000001': 'xerox1', '000002': 'xerox2'})
snippsat 661 Master Poster

When you iterate over with csv.reader(ins) you get a list output.
['3.2323232312']

>>> map(int, ['3.2323232312'])
Traceback (most recent call last):
  File "<interactive input>", line 1, in <module>
ValueError: invalid literal for int() with base 10: '3.2323232312'

>>> map(float, ['3.2323232312'])
[3.2323232312]

Even if you use float you just get 3 separate list,and sum() would not work.
If you want to add up those numbers,here one way.

with open('e1.csv') as ins:
    print sum(float(i) for i in ins) #14.1092143611

If you have more problem post an example of how E1.csv look,not just a column.
You dont have to post whole file,but some lines that are complete and desired output.

snippsat 661 Master Poster

One more stone turned:

Collections is good,and i think we should also mention the star when it's come to counting stuff collections.Counter.

>>> from collections import Counter
>>> import random
>>> Counter(random.randint(1,10) for i in range(100))[3]
8
>>> Counter(random.randint(1,10) for i in range(100))[3]
9

Some more fun with Counter.

>>> from collections import Counter
>>> lst = [3,3,3,3,9,9,1,3,3,5]
>>> counter = Counter(lst)
>>> counter[3]
6
>>> counter.most_common(2)
[(3, 6), (9, 2)]
>>> counter.most_common(1)
[(3, 6)]


>>> fruits = ['Apple', 'Apple', 'Pear', 'Orange', 'Banana', 'Apple', 'Banana']
>>> fruit_count = Counter(fruits)
>>> fruit_count
Counter({'Apple': 3, 'Banana': 2, 'Orange': 1, 'Pear': 1})
>>> fruit_count.most_common(1)
[('Apple', 3)]
>>> fruit_count.most_common(2)
[('Apple', 3), ('Banana', 2)]
>>> fruit_count['Apple']
3


>>> import itertools
>>> nested_lst = [[1,3,3],[1,2,3]]
>>> nested_counter = Counter(itertools.chain(*nested_lst))
>>> nested_counter[3]
3
>>> nested_counter
Counter({3: 3, 1: 2, 2: 1})
>>> nested_counter.most_common(1)
[(3, 3)]
Gribouillis commented: nice +13
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

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

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

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

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

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

to cups.')) is missing line 5.

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

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
snippsat 661 Master Poster

The best way is to always use raw string(r) when give path in windows.
There is also an option to use \\ or /.

So this do not work.
os.chdir('C:\test')
This work.

os.chdir(r'C:\test')
os.chdir('C:\\test')
os.chdir('C:/test')

The reason why is this way,is that a singel backslashes(\) in python can(do) get read as an escape character.
@sepp2k also metion that you need escape your backslashes.
Take a look at this.

>>> s = 'C:\test'
>>> print s
C:  est
>>> print repr(s)
'C:\test'
>>> repr(s)
"'C:\\test'"

Then with raw string.

>>> s = r'C:\test'
>>> print s
C:\test
>>> print repr(s)
'C:\\test'
>>> repr(s)
"'C:\\\\test'"

One more \

>>> s = 'C:\\test'
>>> print s
C:\test
snippsat 661 Master Poster

You are getting the memory adress of object.

class Foo(object):
    def bar(self):
        return 'Hello'

Test class.

>>> obj = Foo()
>>> print obj
<__main__.Foo object at 0x0356B110>
>>> print obj.bar
<bound method Foo.bar of <__main__.Foo object at 0x0356B110>>
>>> print obj.bar()
Hello

As you see until a make correct call i get memory adress of object at 0x......
You can try something like index(), index.method_name, index.method_name().

snippsat 661 Master Poster

What is the most Pythonic way?

Not to typecheck.
Need to know the type of an object?
Let me make a brief argument: No, you don't.
Just use the object as if it was whatever you expect it to be, and handle any errors that result.
http://www.siafoo.net/article/56

@S.Lott
Actually, a manual type check in Python is almost always a waste of time and code.
It's simply a bad practice to write type checking code in Python.
If an inappropriate type was used by some malicious sociopath, Python's ordinary methods will raise an ordinary exception when the type fails to be appropriate.
You write no code, your program still fails with a TypeError.
There are very rare cases when you must determine type at run-time.

snippsat 661 Master Poster

I only use BeautifulSoup or lxml,because they are by far the two best parser for python.
Can show you on way with BeautifulSoup.
soup.find_all('router') find all ruter tag,i take out router 1 router_tag[0]
Then put id and ip text in a dictionary.

from bs4 import BeautifulSoup

xml_file = """\
<routingTable>
    <router>
        <id>1</id>
        <ip>1.1.1.1</ip>
        <nexthop>1.1.1.2</nexthop>
    </router>
    <router>
        <id>2</id>
        <ip>2.2.2.1</ip>
        <nexthop>2.2.2.2</nexthop>
    </router>
</routingTable>"""

router1_dict = {}
soup = BeautifulSoup(xml_file, 'xml')
router_tag = soup.find_all('router')
router_1 = router_tag[0]
router1_dict[router_1.find('id').text] = router_1.find('ip').text
print router1_dict #--> {u'1': u'1.1.1.1'}
Gribouillis commented: thanks +13
snippsat 661 Master Poster

Nice to use with, not sure when it was introduced?

In python 2.5 september 19, 2006.

Bare "except:", with no exception specified is nasty because it can easily hide bugs.

except: #Dont do this

To use your code as example.

def file_exists(filename):
    '''
    a file exists if you can open and close it
    '''
    try:
        f = ope(filename) # misspelled "open"
        f.close()
        return True
    except:
        return False 

print file_exists('somefile.txt')

The misspelled "open" triggers a NameError,which is caught by the except clause.
So funcion return False,so it hide the real problem that there is NameError.
except IOError will only catch IOError and show that NameError is the problem.

When people see bare "except:" in code they can complain about it.
http://python.6.n6.nabble.com/issue4788-two-bare-quot-except-quot-clauses-are-used-in-the-ssl-module-td701941.html

Gribouillis commented: I totally agree +13
snippsat 661 Master Poster

HiHe function is ok,but some changes that i think make it better.
Bare except(catch all maybe) i dont like this to much.
And with open() is preferred over open(),no need to close file object and it dos some error checking to.

def file_exists(filename):
    try:
        with open(filename) as f:
            return True
    except IOError:
        return False

Or return the specific error masseage to user.

def file_exists(filename):
    try:
        with open(filename) as f:
            return True
    except IOError as error:
        return 'A problem occurred: {}'.format(error)
snippsat 661 Master Poster

Look at os.path.exists and os.path.isfile thats dos what you describe.

>>> help(os.path.exists)
Help on function exists in module genericpath:

exists(path)
    Test whether a path exists.  Returns False for broken symbolic links

>>> help(os.path.isfile)
Help on function isfile in module genericpath:

isfile(path)
    Test whether a path is a regular file

Or try/except that is a safe an pythonic way to solve this.

try:
   open()
except IOError as e:
   print 'No file found'
snippsat 661 Master Poster

or how would you change it (or may be some part of it) to looks it more elegant and to be more efficient.

here is the code:

You are making 88 random numbers in range 0 to 9 and want to count occurrence.
use randint() because it are bettter suited for this than choice().
In python 2.7--> collections.Counter is nice

>>> from collections import Counter
>>> from random import randint
>>> print Counter([randint(0,9) for i in range(88)])
Counter({7: 12, 1: 11, 3: 10, 8: 10, 9: 10, 0: 9, 2: 7, 4: 7, 5: 7, 6: 5})

So you see it dos the same,or maybe if i do this you see it clearer.

from collections import Counter
from random import randint

runs = 88
numbers = Counter(randint(0,9) for i in range(runs))
for numb in numbers:
    print 'Number {0} occurred {1}'.format(numb, numbers[numb])

'''Output-->
Number 0 occurred 4
Number 1 occurred 7
Number 2 occurred 13
Number 3 occurred 10
Number 4 occurred 5
Number 5 occurred 10
Number 6 occurred 10
Number 7 occurred 11
Number 8 occurred 10
Number 9 occurred 8
'''

Before python 2.7 and still is using dictionary a common way to count stuff.

>>> d = {}
>>> numbers = [randint(0,9) for i in range(88)]
>>> for v in numbers: d[v] = d.get(v, 0) + 1
>>> print d
{0: 4, 1: 11, 2: 10, 3: 4, 4: 13, 5: 8, 6: 12, 7: 7, 8: 11, …
Gribouillis commented: good help +13
snippsat 661 Master Poster

Using re.split() is also and option.

>>> import re
>>> s = '1--2--3--4---5---6--7---8'
>>> re.split(r'\-+', s)
['1', '2', '3', '4', '5', '6', '7', '8']
TrustyTony commented: True +12
vegaseat commented: nicely done +14
snippsat 661 Master Poster

itertools.product will also do this.

import itertools
import pprint

letters = ['A', 'B', 'C']
pprint.pprint(list(itertools.product(letters, repeat=3)))

"""Output-->
[('A', 'A', 'A'),
 ('A', 'A', 'B'),
 ('A', 'A', 'C'),
 ('A', 'B', 'A'),
 ('A', 'B', 'B'),
 ('A', 'B', 'C'),
 ('A', 'C', 'A'),
 ('A', 'C', 'B'),
 ('A', 'C', 'C'),
 ('B', 'A', 'A'),
 ('B', 'A', 'B'),
 ('B', 'A', 'C'),
 ('B', 'B', 'A'),
 ('B', 'B', 'B'),
 ('B', 'B', 'C'),
 ('B', 'C', 'A'),
 ('B', 'C', 'B'),
 ('B', 'C', 'C'),
 ('C', 'A', 'A'),
 ('C', 'A', 'B'),
 ('C', 'A', 'C'),
 ('C', 'B', 'A'),
 ('C', 'B', 'B'),
 ('C', 'B', 'C'),
 ('C', 'C', 'A'),
 ('C', 'C', 'B'),
 ('C', 'C', 'C')]
 """
snippsat 661 Master Poster

Does first alternative not work in Python 3?

No,in python 3 print is a function.

Read about diffrence.
http://diveintopython3.ep.io/porting-code-to-python-3-with-2to3.html

snippsat 661 Master Poster

Pyscripter as mention is great(windows only)
I will also mention Spyder 2 and Pydev

snippsat 661 Master Poster

Hmm that type-checking is from outer space.
You should not use vars() . vars() or locals(),globals() provides low level access to variables created by python.
Dont use python internal working in your code.

To check for integer or float here a couple of way.
Here you only get out of loop if input is a integer or float.

while True:
    try:
        number = float(input('Enter a number: '))
        print('val correct %s' % number)
        break
    except ValueError:
        print('Please only numbers,try again')

type() is not good to use,we can use isinstance() instead.

l = [1, 2.5, 'a']

for item in l:
      if isinstance(item, (int,float)):
          print('%s is a number' % item)
      else:
        print('%s is not number' % item)

"""Otuput-->
1 is a number
2.5 is a number
a is not number
"""

Type-checking in python is something that not so popular.

Need to know the type of an object? Let me make a brief argument: No, you don't.
Just use the object as if it was whatever you expect it to be, and handle any errors that result.

snippsat 661 Master Poster

I wonder about the same as woooee.
Using a parser can be better for this task as BeautifulSoup or lxml.
A quick demo.

from BeautifulSoup import BeautifulStoneSoup

xml = '''\
<tag>
<number>1</number>
<info>blah blah</info>
<more>Lorem Ipsum</more>
<anothertag>The quick brown fox...</anothertag>
<id>32444</id>
<yetmore>blah blah</yetmore>
</tag>
<tag>
<number>2</number>
<info>qwerty</info>
<more>yada yada qwerty</more>
<anothertag>yada yada qwerty</anothertag>
<id>32344</id>
<yetmore>yada yada qwerty</yetmore>
</tag>
<tag>
<number>3</number>
<info>yada yada qwerty</info>
<more>yada yada qwerty</more>
<anothertag>yada yada</anothertag>
<whatever>yada</whatever>
<id>32444</id>
<yetmore>yada yada</yetmore>
</tag>'''

soup = BeautifulStoneSoup(xml)
tag = soup.findAll('id')
print tag
#--> [<id>32444</id>, <id>32344</id>, <id>32444</id>]
snippsat 661 Master Poster

You have a post with same question.
http://www.daniweb.com/software-development/python/threads/416862

In this post you give more info about html file.
What you post now is just a mess,read about function.
Is this a school task? can you use regex in this task?

import re

info = '''<table>
    <tr align = "center">
        <h1> Lachlan Osborn </h1>
        <p> Address: 5 Smith Street, Manly <br>
        Date of Birth: 26th April 1993 </p>

        <a href="semester.html"><b>My Semester Units</b></a>
        <p><b>Check out my <a href="hobbies.html">hobbies.</a></b></p>
    </tr>
</center>'''

def remove_html(info):
    text = re.sub(r'<.*?>', '', info)
    text = text.strip()
    text = text.replace('\n\n', '\n')
    for line in text.split('\n'):
        print line.strip()

remove_html(info)
"""Output-->
Lachlan Osborn
Address: 5 Smith Street, Manly
Date of Birth: 26th April 1993
My Semester Units
Check out my hobbies
"""
snippsat 661 Master Poster

For example, a text file that shows: <title>Lachlan Osborn</title>
and the output should be like that: Lachlan Osborn

It can dependent how that text file look.
Can cange regex to something like this.

import re

data = '''\
<title>Lachlan Osborn</title>
<head>hello world</head>
'''

text = re.sub(r'<.*?>', '', data)
print text.strip()
"""Output-->
Lachlan Osborn
hello world
"""