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

Use code tag so indentation works.
You are doing some unnecessary stuff.
The answer is not so long,so i dont break it up.

with open('age.txt') as f:
    for item in f:
        sorted_list = sorted(item.split(','), key=int)

with open('age_out.txt', 'w') as f_out:
    f_out.write(','.join(sorted_list))
    #--> 12, 13, 14, 15, 16, 17, 18, 19, 20

Some point is best to always use with open(),then you dont need to close fileobject.
And with open() is doing some error handling to.
When you read from file and write to file it is string that is used.
Here i dont convert the list to integer and sort,but use key=int to sort the list of string.
Then join that list to a string and write to file.

TrustyTony commented: Elegant one! +12
snippsat 661 Master Poster

You need to post your code with Traceback error.
We can not help by guessing how code look.

spyder 2.1.9 Setup

Python 2.7 is not installed on your computer

OK

Install 2.7.
http://packages.ubuntu.com/oneiric/python-spyderlib

snippsat 661 Master Poster

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

snippsat 661 Master Poster

Code are sending shellcode through a socket with python code.

Shellcode is a piece of machine-readable code, or script code that has just one mission; to
open up a command interpreter (shell) on the target system so that an “attacker” can type in
commands in the same fashion as a regular authorized user or system administrator of that
system can do (with a few not-so-important exceptions of course).

Shellcode is primarily used to exploit buffer overflows (including heap overflows) or format
string bugs in binary, machine-readable software.

snippsat 661 Master Poster

A little more about this. is is the identity comparison. == is the equality comparison.

With id() we can se memory loaction.
So here a and b point to same place in memory.

>>> a = 5
>>> b = 5
>>> a is b
True
>>> id(a)
4062136
>>> id(b)
4062136

Let`s try with list.

>>> a = []
>>> b = []
>>> a is b
False
>>> a == b
True
>>> id(a)
41004848
>>> id(b)
41004968

People often think that is is part of the comparison operator set.
The is statement does not compare two objects.

So a good rule is to not use is unless you want to check if something is None or something is not None.
The reason is works for things like "a is None" is because there is
only one None builtin in memory ever.

HiHe commented: good explanation +5
snippsat 661 Master Poster

You have to convert to int() or float().
If you concatenate two string then is just strings not numbers.

>>> '5' + '2'
'52'
a = raw_input("enter 2 numbers separated by a /: ") #5/2 entered
b = a.split("/")
c = int(b[0]) + int(b[1])
print c

You can also do it like this if you have a list with string.

>>> l = ['5', '2']
>>> [float(i) for i in l]
[5.0, 2.0]
>>> l = ['5', '2']
>>> map(int, l)
[5, 2]
>>> sum(float(i) for i in l)
7.0
snippsat 661 Master Poster

sort() dos a in place sort of orginal list and it dont return anything.

>>> mystring = 'blue, pink, red, red, red, white, long, short, blonde, blonde'
>>> s = mystring.split(', ')
>>> s
['blue', 'pink', 'red', 'red', 'red', 'white', 'long', 'short', 'blonde', 'blonde']
>>> s.sort()
>>> s
['blonde', 'blonde', 'blue', 'long', 'pink', 'red', 'red', 'red', 'short', 'white']

>>> help(s.sort)
Help on built-in function sort:

sort(...)
    L.sort(key=None, reverse=False) -- stable sort *IN PLACE*

Use sorted() for store result in variable.

>>> s_sort = sorted(set(mystring.split(', ')))
>>> s_sort
['blonde', 'blue', 'long', 'pink', 'red', 'short', 'white']
snippsat 661 Master Poster

Dont use file as variable/argument is a built-in functions.

>>> f = open(file, 'a')
Traceback (most recent call last):
  File "<interactive input>", line 1, in <module>
TypeError: coercing to Unicode: need string or buffer, type found
>>> file
<type 'file'>
>>>
snippsat 661 Master Poster

I'm working on the py2exe convertor, which will convert files from .py to .exe

It seems like you are making this to diffcult and you are missing stuff like setup option.
Look at this,will convert py file to exe.

from distutils.core import setup
import py2exe
import sys

def py2_exe(file_in=None):
    if len(sys.argv) == 1:
        sys.argv.append('py2exe')

    setup(options = {'py2exe': {'compressed': 1, 'optimize': 2, 'ascii': 1, 'bundle_files': 3}},
           zipfile = None,

           ## Can use console or window
           ## Filpath to '....py' run this script in same folder as file_in
          console = [{'script': file_in}])

if __name__ == '__main__':
    #Use raw string then you dont need \\ or /
    file_in = r'c:\test\singel_digits.py'
    py2_exe(file_in)

There is also Gui2exe you can look at.

snippsat 661 Master Poster

See if this help,it seems to work for me in this test
This script dos delete the file and create a new file in one go.

import os

ofile = r'c:\test4\t.txt'
if os.path.exists(ofile):
    print 'ofile exists'
    os.unlink(ofile)

print "It didn't exist so I'm creating it"
f = open('t.txt', 'w+')
f.close()

Here it will delete file at first run and stop.
Second run the file dont exist,so then else block will run and create the file.

import os

ofile = r'c:\test4\t.txt'
if os.path.exists(ofile):
    print 'ofile exists'
    os.unlink(ofile)
else:
    print "It didn't exist so I'm creating it"
    f = open('t.txt', 'w+')
    f.close()
snippsat 661 Master Poster

Here we go again:ooh:

>>> a = 1
>>> globals()
{'__builtins__': <module '__builtin__' (built-in)>, '__name__': '__main__', '__doc__': None, 'a': 1, '__package__': None}

What`s happen here is that we take a look into the global namespace.
We see that global namespace store 'a': 1 as a dictionary.
Let create a visible dictionary.

>>> d = {'a': 1}

Now we shall use both.

>>> globals()['a']
1
>>> d['a']
1
>>>

So a advice dont use python internal working like global namespace as a dictionary.
The code get much clearer if you make a ordinary dictionary.

snippsat 661 Master Poster
with open('numb.txt') as f:
    print [i.split() for i in f]
    #[['1', 'string1'], ['2', 'string2'], ['10', 'string3']]

A little mistake like this for 1 list.

with open('numb.txt') as f:
    print f.read().split()
    #['1', 'string1', '2', 'string2', '10', 'string3']
snippsat 661 Master Poster

You cannot just open an ordinary txt file with pickle.
You have to dump something to it first.

# Save a dictionary into a pickle file.
import pickle

favorite_color = {"lion": "yellow", "kitty": "red"}
pickle.dump(favorite_color, open("Ex.txt", "wb"))

favorite_color = pickle.load(open("Ex.txt", "rb" ))
print(favorite_color) #{'lion': 'yellow', 'kitty': 'red'}
snippsat 661 Master Poster

Best way to create one is to not to.

Pseudo-random number generators are a very complex subject, so it's better off to use the implementations produced by the people that have a good understanding of the subject.

Python uses the Mersenne twister as the core generator. It produces 53-bit precision floats and has a period of 2**19937-1.
The underlying implementation in C is both fast and threadsafe.

You can of course look at all code for python.
http://svn.python.org/projects/python/trunk/Modules/_randommodule.c
http://svn.python.org/projects/python/trunk/Lib/random.py

Pitfalls in Random Number Generation

def get_random_number():
    '''Chosen bye a fair dice roll,guaranteed to be random'''
    return 4
Gribouillis commented: nice post +13
snippsat 661 Master Poster

Almost always nothing after else: .
You have some cases like a ternary operator,list comprehension where else is not bare.
You can you use if or elif in this case.

It is almost always best to try avoiding global statement.
Pass variable in as an argument and in most cases return result out(insted of print in function)
So these 3 function do the same.

def room_4b(medical_kit):
    if medical_kit >= 1:
        print "You have a medical kit."
    elif medical_kit <= 0:
        print "If only you could revive him somehow."
    else:
        print 'Someting else'

medical_kit = 0
room_4b(medical_kit)
def room_4b(medical_kit):
    if medical_kit >= 1:
        print "You have a medical kit."
    else:
        print "If only you could revive him somehow."

medical_kit = 0
room_4b(medical_kit)
def room_4b(medical_kit):
    if medical_kit >= 1:
        return "You have a medical kit."
    return  "If only you could revive him somehow."

medical_kit = 0
print room_4b(medical_kit)
snippsat 661 Master Poster

Like this with correct indentations.

I double checked my indentation and this still doesn't work for me,

Do not post that code dont work,python always give you Traceback.
Next time post code and Traceback,then is`t much eaiser to help.
Understanding Traceback is very important part of programming in python.
1 line you get syntax error because of missing #

Also code from HiHe works,so now you have a couple working example with pyside.

#!/usr/bin/python 
# -*- coding: utf-8 -*-

import sys
from PySide.QtCore import *
from PySide.QtGui import *

class Form(QDialog):
    def __init__(self, parent=None):
        super(Form, self).__init__(parent)
        # Create widgets
        self.edit = QLineEdit("Write my name here")
        self.button = QPushButton("Show Greetings")
        # Create layout and add widgets
        layout = QVBoxLayout()
        layout.addWidget(self.edit)
        layout.addWidget(self.button)
        # Set dialog layout
        self.setLayout(layout)
        # Add button signal to greetings slot
        self.button.clicked.connect(self.greetings)
        # Add button signal to exit slot
        exit_button = QPushButton("Exit")
        exit_button.clicked.connect(sys.exit)

    # Greets the user
    def greetings(self):
        print ("Hello %s" % self.edit.text())

if __name__ == '__main__':
    # Create the Qt Application
    app = QApplication([])
    # Create and show the form
    form = Form()
    form.show()
    # Run the main Qt loop
    sys.exit(app.exec_())
vegaseat commented: good point +15
snippsat 661 Master Poster

For python 2 and 3,i think you use pyhon 3 because you get error on print.

#Python 2.7
>>> print r"pow(2,3) returns 2^3 pow(2,3,1) returns 2^3 modulo 1", pow(2,3), pow(2,3,1)
pow(2,3) returns 2^3 pow(2,3,1) returns 2^3 modulo 1 8 0
#Python 3
>>> print(r"pow(2,3) returns 2^3 pow(2,3,1) returns 2^3 modulo 1", pow(2,3), pow(2,3,1))
pow(2,3) returns 2^3 pow(2,3,1) returns 2^3 modulo 1 8 0
>>> help(pow)
Help on built-in function pow in module builtins:

pow(...)
    pow(x, y[, z]) -> number
    
    With two arguments, equivalent to x**y.  With three arguments,
    equivalent to (x**y) % z, but may be more efficient (e.g. for longs).

>>>
snippsat 661 Master Poster

Tk GUIs don't look and behave like a native application, which affects the "look & feel" in multiple small ways,
which make a complex app feel weird and clunky compared to native apps on given system.
So Tkinter will not look god on windows.

For more better looking GUI look into wxpython,PyQt(pyside),PyGTK.

snippsat 661 Master Poster

There are many postet how to use py2exe and cx_freeze on this site.
Just search.

snippsat 661 Master Poster

You can look at this and see if it helps.

>>> import socket 
>>> socket.gethostbyname_ex('python.org')
('python.org', [], ['82.94.164.162'])
>>> socket.gethostbyaddr('82.94.164.162')
('dinsdale.python.org', [], ['82.94.164.162'])
>>> socket.gethostbyaddr('111.111')
Traceback (most recent call last):
  File "<interactive input>", line 1, in <module>
gaierror: [Errno 11004] getaddrinfo failed
>>> socket.gethostbyaddr('11.111.111.111')
Traceback (most recent call last):
  File "<interactive input>", line 1, in <module>
herror: [Errno 11004] host not found
import socket

def foo(ip):
    try:
        name = socket.gethostbyaddr(ip)
        return name[0]
    except (socket.gaierror,socket.herror):
        return 'No DNS name found for this ip'

#ip = '82.94.164.162'
#dinsdale.python.org

ip = '11.111.111.111'
#No DNS name found for this ip

print foo(ip)
snippsat 661 Master Poster

An other way,nice use of itertools Gribouillis.

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

filename = 'numb.txt'
chunks = 4
print blocks(filename, chunks)

""" Out-->
[['56.71739\n', '56.67950\n', '56.65762\n', '56.63320\n'], ['56.61648\n', '56.60323\n', '56.63215\n', '56.74365\n'], ['56.98378\n', '57.34681\n', '57.78903\n', '58.27959\n']]"""
snippsat 661 Master Poster

So everytime if we have a function to define, and If i wanna write
to an output file, I always have to put it outside the function.

No of course not,we could have placed all in one function.
For better design it can be smarter to make a new function like code under.
A function should not do to many task,if a function do to many task code get harder to read.

def makeMagnitudeList():
        quakefile = open("in.txt","r")
        headers = quakefile.readline()
        maglist = []
        for aline in quakefile:
            vlist = aline.split()
            maglist.append(float(vlist[1]))
        quakefile.close()
        return maglist

def write_to_file(arg):
    outfile = open("out.csv", "w")
    outfile.write(', '.join(str(i) for i in arg))
    outfile.close()

magList = makeMagnitudeList()
write_to_file(magList)
Gribouillis commented: wise advice +13
snippsat 661 Master Poster

Some note.
For better look/style than just stuff all code in a main function,it can be better to make som more functions.
Then bring it all togeher in the main function.
Here you also see that i use docstring in function name_calc.

def name_input():
    name = raw_input("Please enter your first or last name (no spaces): ").lower()
    first,last = name.split()
    return first, last

def name_calc(first,last):
    '''Calculate numeric value from input names'''
    first_calc = sum([ord(c)-96 for c in first])
    last_calc = sum([ord(c)-96 for c in last])
    return first_calc, last_calc

def main():
    first,last = name_input()
    f, l = name_calc(first,last)
    print '%s(%d) %s(%d) total numeric value %s' %  (first,f, last,l, f+l)
    #williams(98) smith(69) total numeric value 167

if __name__ == '__main__':
    main()
snippsat 661 Master Poster

Some point to this.

>>> a = 2
>>> b = 1
>>> c = 4
>>> d = 3
>>> l = [a,b,c,d]
>>> l
[2, 1, 4, 3]
>>> sum(l)
10
>>>

So here i declare variables an put it in a list and sum() it up. ['a','b','c','d'] will always be list with strings.
So 'a' wil be a.
You can make a new list with numbers,and make it to dictionary so a point to 2.

>>> l = ['a','b','c','d']
>>> n = [2,1,4,3]
>>> d = dict(zip(l, n))
>>> d
{'a': 2, 'b': 1, 'c': 4, 'd': 3}
>>> d['a']
2
>>> [i for i in d.keys()]
['a', 'c', 'b', 'd']
>>> [i for i in d.values()]
[2, 4, 1, 3]
>>> sum([i for i in d.values()])
10
>>> for k,v in d.items():
...     print('%s has a value of %s' % (k, v))
...     
a has a value of 2
c has a value of 4
b has a value of 1
d has a value of 3
snippsat 661 Master Poster

If .py files are assigned to be opened by python on your system, then you only need to put a shortcut into your startup folder.
C:\Documents and Settings\All Users\Start Menu\Programs\Startup

More andvance solutions is.
- add it to the windows registry (HKCU\Software\Microsoft\Windows\CurrentVersion\Run)
- package it into a service, that should then be installed

snippsat 661 Master Poster

After your description this function dos what you want.
It`s more common to return out of function,than use print.
As you se it has no argument,because words comes from file.

def no_e():
    with open('fox.txt') as f:
        for item in f:
            words = item.split()
    return [word for word in words if 'e' not in word]

print no_e()

If we spilt it up it can look like this.
Now functions only dos 1 jobb an return out,this also show use of docstring.
This can be a good practise when code grow larger.

def read_file():
    '''Read a file and return words'''
    with open('fox.txt') as f:
        for item in f:
            words = item.split()
    return words

def no_e(words):
    '''Return all words,but not words that has "e" in it'''
    return [word for word in words if 'e' not in word]

if __name__ == '__main__':
    words = read_file()
    print no_e(words)
    help(read_file)
snippsat 661 Master Poster

Here something you can look at.

>>> s = 'The quick brown fox jumps over the lazy dog'
>>> [i for i in s.split() if 'e' not in i]
['quick', 'brown', 'fox', 'jumps', 'lazy', 'dog']

Can break it up,code over is list comprehensions wish is much used in python.

>>> s = 'The quick brown fox jumps over the lazy dog'
>>> for item in s.split():
...     if 'e' not in item:
...         print item
...         
quick
brown
fox
jumps
lazy
dog
Lomholdt commented: Gave me a quick hint, and made me solve it in seconds! Excellent! +0
snippsat 661 Master Poster

You are making some mistake and it can be done much eaiser with some python power.
You are trying to count with dictionary 2 times 1 is enough.
.strip(',:.;')
You should take out more than this also ?!
An example.

>>> import string
>>> string.punctuation
'!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~'
>>> s = 'The quick:: brown! fox jumps? over+ the lazy?? dog.'
>>> ''.join(c for c in s if c not in string.punctuation)
'The quick brown fox jumps over the lazy dog'
>>>

So another way this time a complete script.

import re
from collections import Counter

with open('text.txt') as f:
    text = f.read().lower()
words = re.findall(r'\w+', text)

print(Counter(words).most_common(4))

This use regex \w+ that dos the same as i showed in code over remove special character.
And counting is done bye collections Counter new from 2.7-->
Counter also has a most_common function,that dos what name say.
This will show the 4 most common word in text.txt.

snippsat 661 Master Poster

P.S on what highest python version wxpython works?

2.7 wxpython Roadmap

Just a note dont use findall() in a loop.
findall() iterate through all text it`s given.

g = regex.findall(regex, failas.read())

If you shall iterate through to text,use finditer()

for line in failas:
    for match in regex.finditer(line):
        print (match.group())[:-1]

And print in GUI is most for troubelshoothing.
You wirte to a label text,texbox ...

snippsat 661 Master Poster

You gone struggle with this if your regex and python skill are not so good.
This file is a mix of javascript and html.
Regex and html is not and the best fit,that`s why it exist parser like lxml and BeautifulSoup.

So this time you want to find something completely diffrent than the first post.
I use with open() then you dont need to close fileobject.

import re

pattern = re.compile(r'pr(.+i)n')
with open('test.txt') as f:
    for match in pattern.finditer(f.read()):
        print(match.group(1)) #eload" /><i

And why do you want to only find a part of word and some tag delimiter?

snippsat 661 Master Poster

Can you post a sample of the file.
You are making some basic mistake,so what you do will not work.

snippsat 661 Master Poster

You may have to give more exact info,like post more of the file.
Here is a regex example with the string you posted,that may need some changes to be more greedy.

import re

s = '(a,b){var c=encodeURIComponent,d=["//www.google.com/gen_204?atyp=i&zx=",(new Da "'
r = re.findall(r'\gen_(\d.*)="', s)
print(r) #['204?atyp=i&zx']
snippsat 661 Master Poster

As Tony poster regex is not a god choice for html or xml.
This is why paser exist to do this job.

from BeautifulSoup import BeautifulSoup

html = '''\
<html>
...some code....
<B><FONT color="green">TEXT to BE EXTRACTED 1</FONT></B><br>
<P>
<B><FONT color="green">TEXT to BE EXTRACTED 2</FONT></B><br>
<P>
<B><FONT color="red">TEXT to BE EXTRACTED 3</FONT></B>
....some code....
</html>'''

soup = BeautifulSoup(html)
tag = soup.findAll('font')
for item in tag:
    print item.text

'''Output-->
TEXT to BE EXTRACTED 1
TEXT to BE EXTRACTED 2
TEXT to BE EXTRACTED 3
'''
snippsat 661 Master Poster

Its used to make web apps by people who think PERL is not verbose enough and ruby is a "toy" language.

Basically everyone has their own pet language and anything else is junk to them for any reason.

I use whatever language will get the job done, because in the end that's the whole point, accomplishing work of some sort.

He want to know how python is used in web development,that you use whatever language
do get the job done has nothing to with the question asked at all.

snippsat 661 Master Poster

The question, how can I (if possible) replace all "value" with numbers in a quicker way then above?

Yes you dont need to store data from file,just iterate over the file and do replace.
And use with open() ,then you dont need to close fileobject.
This create a new file,this is ofen the best way so you dont mess up orginal file.

with open('val.txt') as f:
    for line in f:
        with open('new.txt', 'a') as f_out:
            f_out.write(line.replace('value', '1111'))
snippsat 661 Master Poster

Enalicho has give some tip.
Here a couple more.
Always use r(raw_string) for regex expression.
If you want to count,just use len() because re.findall() is returning a list.
Here is a example run.

>>> import re
>>> user_input = 'aaaaBBBCC'
>>> re.findall(r'A-Z', user_input)
[]
>>> #Missing []
>>> re.findall(r'[A-Z]', user_input)
['B', 'B', 'B', 'C', 'C']
>>> #Count
>>> len(re.findall(r'[A-Z]', user_input))
5
>>>
Enalicho commented: Good call; I shouldn't have left out the r +1
snippsat 661 Master Poster

You dont need to convert code just write it in python.
I could of course convert it to look exactly like C++ over,but that had been stupid.
Because python dos most stuff a lot eaiser than C/C++.

print 'Enter numers,use q to stop'
l = []
while True:
    user_input = raw_input('Enter numers: ')
    if user_input == 'q':
        break
    else:
        l.append(user_input)

num_list = (float(i) for i in l)
#Ascending order
print sorted(num_list)
#Descending order
#print sorted(num_list, reverse=True)
snippsat 661 Master Poster

Python has some extraordinarily intuitive features I'm noticing, it's almost...English.

List comprehensions as Gribouillis use is a common way to write with python.

>>> l = ['a', 'b', 'c']
>>> a = [x for x in l if not 'a' in x]
>>> a
['b', 'c']
>>> l
['a', 'b', 'c']
>>>

If we break up List comprehensions it look like this.

>>> lst = []
>>> for x in l:
...     if not 'a' in x:
...         lst.append(x)
...         
>>> lst
['b', 'c']
>>> l
['a', 'b', 'c']
>>>
snippsat 661 Master Poster

python --version not python--version
And as Gribouillis pointet out you can write python in any path(cmd) and it will work.
If environment variables(path) are ok.

You should stick with 2.7 for now,you can have both installed.
Most of stuff(tutorials/books/forum) out there is for python 2.x
The diffrence 2 to 3.
http://diveintopython3.org/porting-code-to-python-3-with-2to3.html

snippsat 661 Master Poster

Look at this post here i explain a little,and give a link to why regex is not the right tool for xml/html.
http://www.daniweb.com/software-development/python/threads/375186

from BeautifulSoup import BeautifulStoneSoup

xml = '''\
<text>
<p><s id="s1"><ng><w pws="yes" id="w1" p="CD">25</w> <w l="woman" pws="yes" id="w4" p="NNP"
common="true" headn="yes">Woman</w></ng> <vg tense="past" voice="act" asp="simple" modal="no"><w l="create"
pws="yes" id="w10" p="VBD" headv="yes">created</w></vg> <pg><w pws="yes" id="w18" p="IN">for</w></pg> <ng><w
vstem="succeed" l="success" pws="yes" id="w22" p="NN" headn="yes">success</w> <w l="barbie" pws="yes" id="w30"
p="NN" headn="yes">barbie</w></ng> <ng><enamex type="location"><w l="reynold" pws="yes" id="w37" p="NNP"
locname="single">Reynolds</w></enamex> <w l="sep" pws="yes" id="w46" p="NN" headn="yes">sep</w></ng>
<ng><timex type="date"><w pws="yes" id="w50" p="CD">1986</w></timex></ng> <ng><enamex type="organization"><w l="pari"
pws="yes" id="w55" p="NNP" locname="single">Paris</w> <w orgname="single" l="google" pws="yes" id="w61" p="NNP">Google</w>
<w l="limited" pws="yes" id="w68" p="NNP" common="true">Limited</w></enamex></ng></s></p>
</text>'''

soup = BeautifulStoneSoup(xml)
tag = soup.findAll('w', {'locname':'single' })
print tag[0].text #Reynolds

For fun one with regex.

import re

r = [match.group(1) for match in re.finditer(r'single">(\w+)', xml)]
print r[0]#Reynolds
Gribouillis commented: beautifulsoup pro +13
snippsat 661 Master Poster

Use code tag next time you post.

import wx
class duff(wx.Frame):

    def __init__(self,parent,id):
        wx.Frame.__init__(self,parent,wx.ID_ANY,'Duffan Formula', size=(400,300)) #wx.ID_ANY
        self.panel = wx.Panel(self) #self.panel

        #self.panel on all
        g=wx.StaticText(self.panel,-1,"________________________________________________________",pos=(10,65))
        z=wx.StaticText(self.panel,-1,"Welcome to Duffan Formula!!",pos=(10,10))
        r=wx.StaticText(self.panel,-1,"Here you can discover the score of any girl you are looking for.",pos=(10,30))
        q=wx.StaticText(self.panel,-1,"Use it, with Knowledge!",pos=(10,50))
        a=wx.StaticText(self.panel,-1,"What`s her name?",pos=(10,110))
        b=wx.StaticText(self.panel,-1,"What`s her beauty score?",pos=(10,150))
        c=wx.StaticText(self.panel,-1,"What`s her body score?",pos=(10,190))
        average=wx.StaticText(self.panel,-1,"Average: ", pos=(80,222.5)).SetForegroundColour('blue')

        self.one=wx.TextCtrl(self.panel,-1,'Enter name',pos=(110,108),size=(80,20))
        self.two=wx.SpinCtrl(self.panel,-1,'1',pos=(150,148),size=(60,20),min=0,max=100)
        self.three=wx.SpinCtrl(self.panel,-1,'1',pos=(130,188),size=(60,20),min=0,max=100)
        wx.StaticBox(self.panel,-1,'Personal Info', (5,90),size=(250,160))


        ae=wx.Button(self.panel,label="Done",pos=(10,220),size=(60,20))
        self.Bind(wx.EVT_BUTTON,self.clickbutton,ae)
        self.Centre()
        self.Show(True)

    def clickbutton(self,event):
        '''
        Now this method can use self.panel
        Without self method can not use panel
        '''
        s1=self.two.GetValue()
        s2=self.three.GetValue()
        media = s1
        if  0<=media<=100:
            wx.StaticText(self.panel,-1, str(media) ,pos=(135,222)) #str(media)

if __name__=='__main__':
    app=wx.PySimpleApp()
    frame=duff(parent=None,id=-1)
    frame.Show()
    app.MainLoop()
Ene Uran commented: sharp eye +13
snippsat 661 Master Poster

One way.

>>> ip = "192.168.157.128"
>>> ip = ip.split('.')
>>> ' '.join((hex(int(i))[2:] for i in ip))
'c0 a8 9d 80'
>>>
debasishgang7 commented: It helped me alot... +3
snippsat 661 Master Poster

how do I obtain inifo such as the name or the path of the folder,

Maybe i dont understand you,if you give the path to the folder.
Then you can store it in a variable and just print it out.

import os

aFolder = 'C:/test/'
print 'Top folder is %s' % aFolder
for root, dirs, files in os.walk(aFolder):
    for sub in dirs:
        print sub #Will print all subfolder in C:\test\

You have os.getcwd()
Return a string representing of the current working directory.

If unclear as @tony postet give more info.

snippsat 661 Master Poster

is 'globals()' a namespace? and does a namespace work like a dictionary in the sense that you can add a key to a dictionary just by:

Yes globals() are a namespace.
A namespace is it`s just like dictionary.

*** Python 2.7.2 (default, Jun 12 2011, 15:08:59) [MSC v.1500 32 bit (Intel)] on win32. ***
>>> a = 5
>>> globals()
{'__builtins__': <module '__builtin__' (built-in)>,
 '__doc__': None,
 '__name__': '__main__',
 '__package__': None,
 'a': 5,
 'pyscripter': <module 'pyscripter' (built-in)>}
>>> globals()['a']
5
>>> globals()['b'] = 6 #same as b = 6
>>> b
6
>>> globals()
{'__builtins__': <module '__builtin__' (built-in)>,
 '__doc__': None,
 '__name__': '__main__',
 '__package__': None,
 'a': 5,
 'b': 6,
 'pyscripter': <module 'pyscripter' (built-in)>}
>>>

Python has 3 namespaces global namespace, local namespace, built-in namespace .
We can take a look at local namespace.

>>> def foo():
...     x = 'i am local'
...     return x
... 
>>> foo()
'i am local'
>>> globals()
{'__builtins__': <module '__builtin__' (built-in)>,
 '__doc__': None,
 '__name__': '__main__',
 '__package__': None,
 'foo': <function foo at 0x01EE5AF0>,
 'pyscripter': <module 'pyscripter' (built-in)>}

>>> x #if we try to access x
Traceback (most recent call last):
  File "<interactive input>", line 1, in <module>
NameError: name 'x' is not defined

>>> #x are local to fuction foo
>>> locals()
{'__builtins__': <module '__builtin__' (built-in)>,
 '__doc__': None,
 '__name__': '__main__',
 '__package__': None,
 'foo': <function foo at 0x01EE5AF0>,
 'pyscripter': <module 'pyscripter' (built-in)>}

>>> def foo():
...     global x #make x global
...     x = 'i am no longer only local'
...     return x
... …
snippsat 661 Master Poster

There is no problem all python 2.x books/tutorials will works for python 2.7.
It dos not mattter if it`s python 2.4 - 2.5 - 2.6,code will run fine in python 2.7.
New features for python 2.7
http://docs.python.org/dev/whatsnew/2.7.html
Only python 3 break backwardcompatibility.
This post is a good start.
http://www.daniweb.com/software-development/python/threads/20774