snippsat 661 Master Poster

Parser should skip the comments.
I did a test in BeautifulSoup(3.08) dont use newer version.

xml = """
<Label> Hello!</Label>
<!-- The above label says Hello.
  -- It is clear, no?  Let's try spicing it up a bit.
  -- Add some color to it.
-->
<Label color="#FF0000">HI I'M RED-Y.</Label>
"""

from BeautifulSoup import BeautifulSoup

soup = BeautifulSoup(xml)
matches = soup.findAll('label')
for i,match in enumerate(matches):
    print i, match.text


'''Out-->
0 Hello!
1 HI I'M RED-Y.
'''
PythonNewbie2 commented: Very helpful person! +1
snippsat 661 Master Poster

Thanks everyone. Snippsat, what if you want them with a different number or arguments?

Use the power off python list,dict,set as default argument.
The link tony show the use off *arg(tuple) **arg(dictionary)
Python has much power up it`s sleeves.
Maybe simpler to understand it like this.

def foo(*arg):
    '''Return a tuple'''
    print arg
    
foo(1,2,3,4,5,'test')
foo()


def foo1(**arg):
    '''Return a dictionary'''
    print arg

foo1(a='1', b='2')
foo1()

'''Out-->
(1, 2, 3, 4, 5, 'test')
()
{'a': '1', 'b': '2'}
{}
'''
class Car:
    def __init__(self, carName=['Bmw'], Color=['red'] , Speed=[250]):
        self.name = carName
        self.color = Color
        self.speed = Speed

        self.printStats()

    def printStats(self):
        print 'Car Statistics:'
        print "Name      : %s" % self.name
        print "Color     : %s" % self.color
        print "Speed:    : %s" % self.speed
        print "----------------------------"

car_1 = Car()
car_2 = Car(['fiat','opel','ferrari'], ['black','Blue','Yellow'], [200,220,300])

'''Out-->
Car Statistics:
Name      : ['Bmw']
Color     : ['red']
Speed:    : [250]
----------------------------
Car Statistics:
Name      : ['fiat', 'opel', 'ferrari']
Color     : ['black', 'Blue', 'Yellow']
Speed:    : [200, 220, 300]
----------------------------
'''
snippsat 661 Master Poster

In the above code, why are the three lines following the second for loop encased in parentheses? And what is the last of those three lines.(639-randint? How did they just slap a number and a dash right in front of a function. Thanks for any and all replies.

Why dont you test it out?

>>> from random import * #bad way to import
>>> from random import randint
>>> random_color = (randint(0, 255), randint(0, 255), randint(0, 255))
>>> random_color
(164, 184, 42)
>>> repr(random_color)
'(164, 184, 42)'
>>> random_color = randint(0, 255), randint(0, 255), randint(0, 255)
>>> random_color
(130, 206, 142)
>>> repr(random_color)
'(130, 206, 142)'
>>> #As you see the same

On a side note, why doesn't python support function, method, and constructor overloading? And what does it do to compensate?

Python does not support function overloading but compensate well by use off default arguments and keyword arguments.
There are also rather ugly global statement,that we dont talk about.

def foo(n=None):
    if n is None: n = 10
    return n + 20

print foo()
#-->30

If we talk about a class.
The constructor for a Python class is def __init__(self, ...): and you cannot overload it.
What you can do is use defaults for the arguments.

class Car:
    def __init__(self, carName="Bmw", Color='red', Speed=250):
        self.name = carName
        self.color = Color
        self.speed = Speed

        self.printStats()      

    def printStats(self):
        print 'Car Statistics:'
        print "Name      : %s" % self.name
        print "Color     : %s" % self.color
        print "Speed:    : …
snippsat 661 Master Poster

print list(word_pattern.findall(abstract))

Just a tips.
re.findall is returning a list,so there is not necessary to use list().

import re

text = '''\
hello, my name is george. How are you? Today
i am not feeling very well. I consider myself to be
sick.
'''

word_pattern = re.findall(r'\w+', text)
print word_pattern

""" Out-->
['hello', 'my', 'name', 'is', 'george', 'How', 'are', 'you', 'Today', 'i', 'am', 'not', 'feeling', 'very', 'well', 'I', 'consider', 'myself', 'to', 'be', 'sick']
"""
Gribouillis commented: indeed ! +4
snippsat 661 Master Poster

Like this,i have put function call in variable name and age.

def main():    
    name = makename()
    age = makeage()    
    print "You are" ,age ,"years old", name
def makename():
    name = raw_input("Please enter your name ")
    return name
def makeage():
    year = input("What is the year current year? ")
    byear = input("What year were you born in? ")
    age = year - byear
    return age
main()
snippsat 661 Master Poster
'''-->my_file.txt
x
a
b
'''

text_label = [f.strip() for f in open('my_file.txt')][0]
self.button = wx.Button(panel, label = '%s' % text_label)

Take x from my_file.txt and place it as label text for button.

snippsat 661 Master Poster
snippsat 661 Master Poster

Using global is not a good soultion at all,learn to give argument at return value out functions.
A simple example.

def newUser():    
    Username = raw_input('Choose a username? ')
    return Username


def reg_user(newUser):
    '''Make 3 users an save to a list'''
    l = []
    for i in range(3):
        l.append(newUser())        
    return l   
    
if __name__ == '__main__':     
    print reg_user(newUser)

'''-->Out
Choose a username? Tom
Choose a username? Paul
Choose a username? Hans
['Tom', 'Paul', 'Hans']
'''
snippsat 661 Master Poster

Something like this,look into findall off re module.
Dont use str as variable,it`s a builtin key word.

>>> str
<type 'str'>
>>> help(str)
Help on class str in module __builtin__:
>>> import re
>>> help(re.findall)
Help on function findall in module re:

findall(pattern, string, flags=0)
    Return a list of all non-overlapping matches in the string.
    
    If one or more groups are present in the pattern, return a
    list of groups; this will be a list of tuples if the pattern
    has more than one group.
    
    Empty matches are included in the result.
import re

text = '''\
Subs cars are test driving in space,and many pigs are flying.
'''

test_match = re.findall(r'\w+[s]\b', text)
print test_match
#->['Subs', 'cars', 'pigs']
snippsat 661 Master Poster
def wordPop(text, n):
    nwords = []
    words = text.split()
    for word in words:
        if (len(word) >= n):
             nwords.append(word)
    return sorted(nwords)

w = 'This is a test off word lenght'
print wordPop(w.lower(), 4)
#->['lenght', 'test', 'this', 'word']

So i removed you length_compare function.
sorted(nwords,cmp=length_compare)
So this get wrong,first off cmp is a python key word.
And your "length_compare" function is not comparing anything.

>>> cmp
<function length_compare at 0x0265EF30>
>>> help(cmp)
Help on function cmp=length_compare in module __main__:

length_compare(x, y)
def length_compare(x, y):
    return len(x) - len(y)

x = 'hi'
x = 'test'
print length_compare(x, y)  #->2
#If you call function you have to use 2 argument
#And it`s not comparing anything,just extract test(4) from hi(2)
snippsat 661 Master Poster

<open file 'MyText1.txt', mode 'r' at 0x15a69b0>
Can someone explain? I'm on a Mac.

You dont make any action for the file object.
text = open(fname, "r").read()
Now it will read file into memory and you can print it out.

So if you call "printWordFrequencies" like this it will work.
printWordFrequencies(text)
doctest.testmod(verbose=True)

Dont ask question in Code Snippet,make a new post next time.

snippsat 661 Master Poster
>>> x = 'car'
>>> x.close()
Traceback (most recent call last):
  File "<interactive input>", line 1, in <module>
AttributeError: 'str' object has no attribute 'close'

As tony mention str has no close() method as a file object.

cStringIO module has close(),or maybe you are trying to use close on what you think is a file object.
You can check type like this.

>>> x = 'car'
>>> type(x)
<type 'str'>
>>>
#cStringIO demo
>>> from cStringIO import StringIO
>>> output = StringIO()
>>> output.write('This goes into the buffer.\n')
>>> output.write('car')
>>> print output.getvalue()
This goes into the buffer.
car
>>> output.close() # discard buffer memory
snippsat 661 Master Poster

This should help you.

>>> import time
>>> date_old = '05/26/1999'
>>> time_tuple = time.strptime(date_old, "%m/%d/%Y")
>>> date_new = time.strftime("%b-%d", time_tuple)
>>> date_new
'May-26'
>>>
try:
    # use strptime(time_str, format_str) to form a time tuple
    time_tuple = time.strptime(date_old, fmt)
except: #Dont use bare except try to catch specific error that are comming
        #Example except ValueError or something else.
    pass
snippsat 661 Master Poster

Try this and it should work.

import shutil

shutil.copy('c:\\test\my_file.txt', 'c:\\temp')

You most copy files with shutil.copy.

This will give you and Permission denied.
You can not copy folder to folder with shutil.copy.

import shutil

shutil.copy('c:\\test', 'c:\\temp')

Use copytree.

import shutil

shutil.copytree('c:\\test', 'c:\\new')

This will copy from c:\test and make a new folder c:\new.
It will give and error if c:\new excited

Look also at this for coping folders.
http://docs.python.org/distutils/apiref.html#distutils.dir_util.copy_tree

import os
import distutils.dir_util

distutils.dir_util.copy_tree('c:/test', 'c:/testbak')

Alwas use \\ or /

c:\test  #No \ can be looked at as an escape character
c:\\test #Ok
c:/test  #Ok
snippsat 661 Master Poster

Another way you can look at.

text = 'ARARAKHTLROGKFMBLFKKGOHMFDGRKLRNGROGINFBLMNFBAEKJGFGOQEITHRGLFDKBN'
abc = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'

textletters = list(text)
abcletters = list(abc)

my_list = []
for letter in abcletters:
      letter = textletters.count(letter)
      my_list.append(letter)

#Now we have a list,but not easy to understand
print my_list

'''zip demo-->
>>> l = ['a','b','c']
>>> n = [1,2,3]
>>> zip(l,n)
[('a', 1), ('b', 2), ('c', 3)]
'''

#We can use zip in a for loop to par it up
for item, letters in zip(my_list, abcletters):
    print item,letters

'''Out-->
[4, 4, 0, 2, 2, 7, 8, 3, 2, 1, 7, 5, 3, 4, 4, 0, 1, 7, 0, 2, 0, 0, 0, 0, 0, 0]
4 A
4 B
0 C
2 D
2 E
7 F
8 G
3 H
2 I
1 J
7 K
5 L
3 M
4 N
4 O
0 P
1 Q
7 R
0 S
2 T
0 U
0 V
0 W
0 X
0 Y
0 Z
'''
snippsat 661 Master Poster

inputChoice = input("Choose an option: ") #Do not need int() as input defaults to int

tbone2sk this code is for python 3.x,so he need int(input()).
Garrett85 make a note that you use python 3.x,most pepole use python 2.x so there is no confusion.

Last but not least, what is prices[choice -1] & items[choice - 1]?

>>> prices = [1.50, 2.0, 1.80, 1.20]
>>> prices[1]
2.0
>>> choice = 2
>>> prices[choice]
1.8
>>> #To get the second element -1(count not from 0 as almost all programming language)
>>> prices[choice -1]
2.0
>>>
snippsat 661 Master Poster

Python 3.x version after run through 2to3 module.

import pprint

info ="101;johnny 'wave-boy' Jones;USA;8.32;Fish;21"
stat = 'id,name,country,average,board,age'

info = info.split(';')
stat = stat.split(',')

my_Dict = {}

k = 0
for item in stat:
    my_Dict[item] = info[k]
    k += 1
    
pprint.pprint(my_Dict)
  
print('*'*35)    

#Sort by key
key_sort = sorted(list(my_Dict.items()), key=lambda v_k: (v_k[0],v_k[1]))
for info, stat in key_sort:
    print('%-10s  %10s' % (info, stat))
    
print('*'*35)

#Sort by value
value_sort = sorted(list(my_Dict.items()), key=lambda k_v: (k_v[1],k_v[0]))
for info, stat in value_sort:
    print('%-10s  %10s' % (info, stat))
snippsat 661 Master Poster

It`s better if you can use a for loop for key:value in a dicitionary.
Than just 6 print statement.

Here some code you can look at,with som sorted output that i see you asked about in an other post.

import pprint

info ="101;johnny 'wave-boy' Jones;USA;8.32;Fish;21"
stat = 'id,name,country,average,board,age'

info = info.split(';')
stat = stat.split(',')

my_Dict = {}

k = 0
for item in stat:
    my_Dict[item] = info[k]
    k += 1
    
pprint.pprint(my_Dict)
  
print '*'*35    

#Sort by key
key_sort = sorted(my_Dict.items(), key=lambda (v,k): (v,k))
for info, stat in key_sort:
    print '%-10s  %10s' % (info, stat)
    
print '*'*35

#Sort by value
value_sort = sorted(my_Dict.items(), key=lambda (k,v): (v,k))
for info, stat in value_sort:
    print '%-10s  %10s' % (info, stat)


##Out
{'age': '21',
 'average': '8.32',
 'board': 'Fish',
 'country': 'USA',
 'id': '101',
 'name': "johnny 'wave-boy' Jones"}
***********************************
age                 21
average           8.32
board             Fish
country            USA
id                 101
name        johnny 'wave-boy' Jones
***********************************
id                 101
age                 21
average           8.32
board             Fish
country            USA
name        johnny 'wave-boy' Jones
snippsat 661 Master Poster

Do you have a question?
If this is a school task try to code something yourself.

What you have now is pseudocode,that maybe has some info to this task that we dont know.

snippsat 661 Master Poster

startswitch/endswith you can use tuple.

if not link.startswith(('javascript','mailto')) and not link.endswith(('pdf','ppt')):
#do something

Depends on how input text is,but a regex can bee used.
Just an untestet regex for this could look something like this. ^javascript|^mailto|pdf$|ppt$ .

Or make variables with tuple as jca0219 suggest.

snippsat 661 Master Poster

Try.
print "You played %s. The computer played %s and %s" % (player_card1, computer_card1, computer_card2)

You can not use a% b% c%
http://docs.python.org/library/stdtypes.html#string-formatting-operations

Most commen formatting expression.
%s == String (converts any Python object using str()).
%d == Signed integer decimal
%f == Floating point decimal format.

snippsat 661 Master Poster

This issue just came up in GUI calculator thread, where I prepared a calculator in Tkinter for comparision

Just make it a float,i have done that many time with wxpython for calculator stuff.
When push buttun i getvalue from this.

elif self.c == 'Divide':
    p = float(self.s1) / float(self.s2)
snippsat 661 Master Poster

How about this.

#Python 3
try:
    input_num = float(input('test: '))
except ValueError:
    print ('Not an integer')

print (input_num)
snippsat 661 Master Poster
#It is a good thing that pyton 3 only has input not raw_input and input as python 2
#Let look a little at it
#I do not use python 3,i wait for 3 party module to be portet to python 3

>>> choice = input('Choose your option: ')
Choose your option: 5
>>> choice
'5'
>>> type(choice)
<class 'str'>
>>> choice + choice
'55'
>>> int(choice) + int(choice)
10

>>> #We can make user input return a interger
>>> choice = int(input('Choose your option: '))
Choose your option: 5
>>> choice + choice
10
>>> type(choice)
<class 'int'>
>>>
snippsat 661 Master Poster

The code it is not tested, but should be worked

You should test it because it is not working:-/

Here you have one way off do it.
This is for python 3 that i think you use.
Homework?,they may spot that you havent wirte this code(some smart shortcut in this code)
You may work on the for loop you startet with(now your code is not working)

def makeList():
    num = input('Please enter the number of strings you want to input\n')
    alist = []
    for i in range(int(num)):
        x = input('Enter string please: ')
        alist.append(x)
    return sorted(alist)

def findShortest(alist):
    min_list = min(alist, key=len)
    return (min_list)

def findLongest(alist):
    max_list = max(alist, key=len)
    return max_list

def findAlpha(alist):
    alpha_list = [item for item in alist if str(item).isalpha()]
    return alpha_list

def main():
    alist = makeList()
    print ('Sorted list is:\n{0}'.format(alist))
    print ('Shortest element is:\n{0}'.format(findShortest(alist)))
    print ('Longest element is:\n{0}'.format(findLongest(alist)))
    print ('Only alphabetic characters is:\n{0}'.format(findAlpha(alist)))

if __name__ == "__main__":
    main()

'''Out-->
Sorted list is:
['car', 'taxi', 'train5']
Shortest element is:
car
Longest element is:
train5
Only alphabetic characters is:
['car', 'taxi']
'''
vegaseat commented: nice code +10
snippsat 661 Master Poster

I was wondering if there are any GUI toolkits in python that create native-looking windows in Windows 7

Wxpython-PyQt dont have the ugly and native-looking that Tkinter has on all windows version.
Tkinter look better on linux,mac.
I postet a wxpython picture here.
http://www.daniweb.com/forums/thread252780.html
Wxpython are a very good gui-toolkit and you have a lot more option than tkinter.

snippsat 661 Master Poster

if i want to delete red data of only key '172.14' all in from array

You can use vega code for this.

mylist = newlist
print(mylist)

So now mylist has removed item you want(garbage collection)old mylist do not exits.

Or an another soultion.

mylist = [
'192.168.255.1 00:01:02',
'172.14.0.1 00:0f:01',
'172.14.0.2 00:0f:01',
'172.14.0.3 00:0f:01'
'172.14.0.4 01:ff:dd:34',
'192.168.255.3 00:dd:01:ff'
]

for item in mylist[:]:
    if item.startswith('172'):        
        mylist.remove(item)   
        
print mylist
snippsat 661 Master Poster

Though there are advantages to using full IDEs such as netbeans

Vega is not talking about big editors like netbean that support many languages.
Pyscripter,SPE are small python editors that work out the box,just paste in code an run it.
And will give a god error message and where in code if somthing goes wrong.

snippsat 661 Master Poster

redyugi you code dos the same as set()

print len(set(["bread","cookies","cake","chocolate","bread"]))
4

That only remove duplicate in a list.
For count with set() this is a solution.

wordlist = ["bread", "cookies", "cake", "chocolate", "bread"]
for item in set(wordlist):
    print '%s %s' % (item,wordlist.count(item))

'''Out-->
cake 1
cookies 1
chocolate 1
bread 2
'''
snippsat 661 Master Poster

To check for a valid email adress regular expression is a god tool.

import re

mail_input = raw_input("Enter your email: ")

if re.match(r"\b[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}\b\Z", mail_input, re.IGNORECASE):
    print ("That is a valid email")
else:
    print ("That email is not valid")
snippsat 661 Master Poster

I'm an information security professional who's decided to teach myself python

Yes a good choice.
I put together something that may in direction you describe.

import re

text = '''\
A fast and friendly dog.
email1@dot.net
myetest@online.no
My car is red.
han445@net.com
'''

find_email = re.findall(r'\b[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}\b',text,re.IGNORECASE)
print 'Text has %d email adress' % (len(find_email))
print find_email
for item in enumerate(find_email):
    print 'Email #%s --> %s' % (item[0],item[1])

'''Out-->
Text has 3 email adress
['email1@dot.net', 'myetest@online.no', 'han445@net.com']
Email #0 --> email1@dot.net
Email #1 --> myetest@online.no
Email #2 --> han445@net.com
'''
#Python 3.x
find_email = re.findall(r'\b[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}\b',text,re.IGNORECASE)
print ('Text has %d email adresser' % (len(find_email)))
print (find_email)
for item in enumerate(find_email):
    print ('Email #%s --> %s' % (item[0],item[1]))
vegaseat commented: good thinking +10
snippsat 661 Master Poster

This was very bad,not worth anyone times.
The gui builder for wxpython could be better,but they are much better than this.

snippsat 661 Master Poster

It just gave a message at the bottom of the gray PythonWin frame right where it says,"running the code file..." or something similar to that

Get a better editor than PythonWin.
Pyscripter is good.
Paste your kode inn,and you se a red line mark under line 7 for your code.
It also give you and postion(25) if you try to run the code.
Because at postion(25) there should be a : as Gribouillis pointet out.

snippsat 661 Master Poster

How dos your money.txt look?

Change to this money = int(money) - Bet .

Type check print type(money) . print type(Bet) Your desgin could be better, a long funtion that only ends(no loop)
Try to make a main function that has meny and question then that function call the bet function.
Betting is done and it goes back to main.

snippsat 661 Master Poster

Many of us like wxpython,so is always fun with a new tool.:)
http://wxformbuilder.org/

Gribouillis commented: Nice info. +3
snippsat 661 Master Poster

In first post.

After you got the basics of Python under your belt, the best way to get a good knowledge of the language and improve your coding skills is to start on a project you are interested in.

That means that you have to know python good.
You can still be a beginner after 1-3 year it depends how much time you put in to learning programming.

Python is on the most easy language to learn,but it take time to be a good programmer where you can solve problem on your own(without hours on google for the most basic thing)

To day people are in a hurry to learn,this is a good read.
Teach Yourself Programming in Ten Years

snippsat 661 Master Poster

Read this.
http://www.daniweb.com/forums/announcement114-2.html

I didn't understand on what you trying to say, but I'm leaving this problem for "professionals people"

Yes leave your homework to "professionals people".
Do you see how stupid that look?

Nick Evan commented: No, apperantly he doesn't see that :) +12
snippsat 661 Master Poster

Use 4 space for indentations(and nothing else ever)

What is you data input?

Not sure what you are trying do do.
Here something you can look at.

>>> import sys
>>> help(sys.getsizeof)
Help on built-in function getsizeof in module sys:

getsizeof(...)
    getsizeof(object, default) -> int
    
    Return the size of object in bytes.

>>> a = 5
>>> sys.getsizeof(a)
12
>>> a = ['hi', 'test', '55']
>>> sys.getsizeof(a)
48
>>>
import sys

data = 55

if sys.getsizeof(data) < 512:
    print 'Data is %s bytes and less than 512 bytes' % (sys.getsizeof(data))
else:
    print 'Data is %s more than 512 bytes' % (sys.getsizeof(data))

'''Out-->
Data is 12 bytes and less than 512 bytes
'''
snippsat 661 Master Poster

For loop will only iterate one time over the list and not find duplicated words.

You can use text.find() method in a while loop.
This will iterate over all word in the text, when all search word are found text.find() will return -1.

Example.

text = """\
Hi,i have a nice car.
I drive to work every day in my car.
This text will find my car,....car.
"""

search_word = "car"
found = text.find(search_word)
while found > -1:
     print search_word, "found at index", found
     found = text.find(search_word, found + 1)

'''Out-->
car found at index 17
car found at index 54
car found at index 82
car found at index 90
'''
deonis commented: Very clear answer +1
snippsat 661 Master Poster

Dictionary has keys() and values()
You dont show all code.

Example.
>>> tanks = {'tiger': 'a55', 'trunk': 'f77'}
>>> for tank in tanks.values():
        print tank    

a55
f77

>>> for tank in tanks.keys():
        print tank
    
tiger
trunk

#--------
>>> dir(tanks)  #this show methods under dictionary
snippsat 661 Master Poster

A coulpe of class that show __str__ and __repr__ methods.

import datetime

class Time(object):
    def __init__(self,date):
        self.date = date
        
    def __str__(self):
        """Return a pleasant representation."""
        return 'Return a human-readable string: %s' % (self.date)    
    

t = Time(datetime.date.today())
print t  #The __str__ method of a class is called whenever Python needs a string representation of an object
'''
Return a human-readable string: 2009-12-27
'''
class Time(object):
    def __init__(self,date):
        self.date = date       
        
    def __repr__(self):
        '''We use __repr__ to produce a clear definition of how to recreate the given object'''
        return 'Return an expression: %r' % (self.date)    

t = Time(datetime.date.today())
print t
'''
Return an expression: datetime.date(2009, 12, 27)
'''

Navigate and getting help

>>> dir(datetime)
['MAXYEAR', 'MINYEAR', '__doc__', '__name__', '__package__', 'date', 'datetime', 'datetime_CAPI', 'time', 'timedelta', 'tzinfo']
>>> dir(datetime.date)
['__add__', '__class__', '__delattr__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__le__', '__lt__', '__ne__', '__new__', '__radd__', '__reduce__', '__reduce_ex__', '__repr__', '__rsub__', '__setattr__', '__sizeof__', '__str__', '__sub__', '__subclasshook__', 'ctime', 'day', 'fromordinal', 'fromtimestamp', 'isocalendar', 'isoformat', 'isoweekday', 'max', 'min', 'month', 'replace', 'resolution', 'strftime', 'timetuple', 'today', 'toordinal', 'weekday', 'year']
>>> dir(datetime.date.today)
['__call__', '__class__', '__cmp__', '__delattr__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__le__', '__lt__', '__module__', '__name__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__self__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__']
>>> #There are no more methods only special method that get called when you use the class

>>> #we look at __doc__
>>> print datetime.date.today.__doc__
Current date or datetime:  same as self.__class__.fromtimestamp(time.time()).
>>> #Or you can use help

>>> help(datetime.date.today)
Help on built-in function today:

today(...)
    Current date or datetime:  same …
snippsat 661 Master Poster

Dont use ; in python.

output = "The number is: "
num = 12

print '%s%d' % (output,num)
'''
The number is: 12
'''
output = "The number is: "
num = 12

output+=num
print output

Error message is pretty clear. TypeError: cannot concatenate 'str' and 'int' objects

>>> output = "The number is: "
>>> type(output)
<type 'str'>
>>> num = 12
>>> type(12)
<type 'int'>
>>> #As you see we have a string and integer
>>> output + num

Traceback (most recent call last):
  File "<pyshell#11>", line 1, in <module>
    output + num
TypeError: cannot concatenate 'str' and 'int' objects

>>> str(num)  #convert to string
'12'
>>> output + str(num) 
'The number is: 12'
>>>
snippsat 661 Master Poster

What Is an Exception?

Python uses exception objects.
When it encounters an error, it raises an exception.
If such an exception object is not handled (or caught), the program
terminates with a so-called traceback (an error message)

>>> b

Traceback (most recent call last):
  File "<pyshell#8>", line 1, in <module>
    b
NameError: name 'b' is not defined
>>>
import exceptions
>>> dir(exceptions)
<list method in exception class>

So let try it out. Version 1

x = input('Enter the first number: ')
y = input('Enter the second number: ')
print x/y 
'''
Enter the first number: 10
Enter the second number: 5
2
'''

Work just fine. Version 2

x = input('Enter the first number: ')
y = input('Enter the second number: ')
print x/y
'''
Enter the first number: 10
Enter the second number: 0
Traceback (most recent call last):
  File "E:\1py\Div\dffddd.py", line 3, in <module>
    print x/y
ZeroDivisionError: integer division or modulo by zero
'''

Here we got an problem,user did divided 10/0.
So what to do now?
We have to catch that exceptions.
You do this with the try/except statement. Version 3

try:
    x = input('Enter the first number: ')
    y = input('Enter the second number: ')
    print x/y
except ZeroDivisionError:
    print "Dont divid by zero!"
'''
Enter the first number: 10
Enter the second number: 0
Dont divid by zero!
'''

Look we used ZeroDivisionError from error message,and now we dont get …

snippsat 661 Master Poster

I have are hard time understand why instructors use outdatet module like graphics.

It has to be much better to learn student basic Tkinter(graphical user interface) or another GUI toolkit.
That is useful othert than education purpose.

And getting help with graphics is hard,because very few has the graphics module.

snippsat 661 Master Poster

You can use what ide editor you want, whish gui toolkit you use dos have little impact.

Pyscipter is good.
http://code.google.com/p/pyscripter/

I use komodo ide,and pyscripter for python 3.x
http://www.activestate.com/komodo/

Pydev plugin should work fine,have not testet it.

snippsat 661 Master Poster

As Mathhax0r take upp your code is really not god at all it`s a big mess.
I think helping you now is difficult because of your code design.

Never use global variabels like this, or at all.
The are ugly an as code grow the will give a lot of problems.

Any name (variable) defined inside a function is local to that function,and should always stay that way.
If you need access to a function's local variables outside that function use argument and return variables out off function.
When you use global like this you are pollutioning the global namespace

snippsat 661 Master Poster

It`s not the best example of python class masterofpuppets.
You put in lot effort to help wish is fine.

Hope this makes it a bit clearer....I haven't actually worked a lot with classes in Python but I guess it is not that much different to Java. So I am sorry if I didn't explain something properly... still learning as well

Python is not java,it`s a lot better:cool:
http://dirtsimple.org/2004/12/python-is-not-java.html
Just to point it out that you could have dropped all that getters method.

Form article.

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.

Look at this and then think of how you code could have been shorter and better.
http://tomayko.com/writings/getters-setters-fuxors

jlm699 commented: Great articles. I like the authors' points of view on Python. Inspiring! +3
snippsat 661 Master Poster

One more,now start to think how to put this together.

>>> count = 0
>>> a = 55
>>> if a % 2 == 1:
	count += 1
	print 'odd', count

else:
	print 'even'

	
odd 1
>>>
snippsat 661 Master Poster

You should try to post some code yourself.

Can give you some tips.

>>> for i in range(0,7):
	a = random.randint(0,100)
	print a
	
79
21
69
60
28
68
0
>>>
>>> 
>>> 1 % 2
1
>>> 2 % 2
0
>>> 3 % 2
1
>>> 4 % 2
0
>>>
snippsat 661 Master Poster

But how could we test if the given string is pallindrome or not. I need a syntax that returns true if the string is pallindrome otherwise false.

>>> def is_palindrome(s): 
...     return s.lower() == s[::-1].lower()
... 
>>> is_palindrome('test')
False
>>> is_palindrome('racecar')
True
>>> is_palindrome('RACECAR')
True
mn_kthompson commented: Very elegant solution to palindrome problem +2