880 Posted Topics

Member Avatar for otengkwaku

Ok project,some advice or tips. I would have have used datetime module and not wirte getMom function,because there are many dark spots when trying to date stuff yourself. >>> from datetime import date >>> d = date.today() >>> d.strftime("%B") 'April' >>> d.strftime("%A, %d. %B %Y %I:%M%p") 'Sunday, 28. April 2013 …

Member Avatar for snippsat
2
385
Member Avatar for rahulinfy

As a addition to slate explanation,do a test in interactive interpreter. > The 'is' operator is not another way to type '=='. In most cases the use of **==** or **!=** is what you want. Normal way to use `is` are to test if something is identical to `None` like …

Member Avatar for snippsat
0
216
Member Avatar for tony75

hmm you have ask similar question before and got good answers. So two word in s1. >>> s1 = "Hello World" >>> len(s1.split()) 2 Some really basic mistake. What happends if you iterate before you split() like you do? s1 = "Hello World" for word in s1: print word #? …

Member Avatar for tony75
0
175
Member Avatar for nouth

> so maybe newFile can be temporary and then it can be used with to reoverwrite the oldFile? Yes this is normal way,you iterate over contend and do what you need,then save contend in a new file. If you need `newtext` to be `oldtext` you rename the files. `os.rename(oldtext','newtext')` or …

Member Avatar for TrustyTony
0
362
Member Avatar for otengkwaku

A little more about `*args` and `**kwargs` First `vehicle` take only `'car'` as agument. Next `*args` take `'hello', 'world'` and make it a tuple. Next `**kwargs` take `key_a='value 1', key_b='value 2'` and make it a dictionary. def func(vehicle, *args, **kwargs): #argument vehicle print(vehicle) #--> car #argument *args print(args) #--> ('hello', …

Member Avatar for dashing.adamhughes
0
692
Member Avatar for mkweska

Some hint,it's ok to use `total += number` as practice. Here i do the same with build in `sum()`. """ randomnumbers.txt--> 1 4 5 2 4 8 """ with open('randomnumbers.txt') as f: print sum(float(i) for i in f.read().split()) #24.0 So this sum up all numbers in one go. Split it …

Member Avatar for snippsat
0
176
Member Avatar for mkweska

A more pythonic/better solution is to use `enumerate()` `enumerate()` can take argument,so counting start at 1. with open('names.txt') as fin: for index, name in enumerate(fin, 1): print("{}: {}".format(index, name.strip())) """Output--> 1: Fred 2: Mary 3: Lisa 4: Amy """

Member Avatar for snippsat
0
479
Member Avatar for nouth

> textfileB: "word","word","word" So dos your text file look like this when you read it? with open("textfileB.txt") as f: your_file = f.read() print your_file Can you post the output? The reason why i ask is because it not normal to have quotes in file. If it's quotes you have to …

Member Avatar for nouth
0
328
Member Avatar for tony75

> How can I read from data.txt? This is in every tutotial/book out there,so it should not be a problem. I try to always use `with open()`,this is the prefered way(`with statement` has been in Python since 2006) One short way. import re from collections import Counter with open('your.txt') as …

Member Avatar for tony75
0
494
Member Avatar for cobaltbravo

> but I am rather confused Yes that's normal when you new to programming. Some help,you are writing more code than you need for this and it's a little messy. Forget errohandling(try,except),function this can you do later. Her is the basic of the game,look at code and see if it …

Member Avatar for cobaltbravo
0
303
Member Avatar for krystosan
Member Avatar for dirtydit27

> The question I have now is how can I make a dictionary out of the list d with the car manufacturer as the key and a tuple containing the year and the model should be the key's value. Something like this. >>> lst = ['1899 Horsey Horseless', '1909 Ford …

Member Avatar for snippsat
0
380
Member Avatar for Siberian

In environment variable `Path`,you should add root folder and scripts folder of python26. http://www.windows7hacker.com/index.php/2010/05/how-to-addedit-environment-variables-in-windows-7/ This is what you add to `Path` `;C:\python26\;C:\python26\scripts\;` Restart. Test it out in cmd(command line) type `python`. Now running program `pythnon somecode.py` will use python26 and install modules with setuptools,pip will find and install to python26. …

Member Avatar for Siberian
0
1K
Member Avatar for clouds_n_things

`IndexError: list index out of range` >>> l = [1,2] >>> l[1] 2 >>> l[2] Traceback (most recent call last): File "<interactive input>", line 1, in <module> IndexError: list index out of range A simple print should tell you what is wrong `print passWord`. If it split at at `:`,you …

Member Avatar for clouds_n_things
0
242
Member Avatar for nytman

Hmm PEP-8 is gone fall in our head. def __str__(self): return 'Name: '+self.name+', Salary: '+str(self.salary)+', Description: '+self.desc And not to happy with all that + def __str__(self): return 'Name: {} Salary: {} Description: {}'.format(self.name, self.salary, self.desc)

Member Avatar for nytman
0
1K
Member Avatar for jeremywduncan

> It returns, 'zip' is not recognized as an internal or external command zip command works only on linux. You can get it in windows by install GnuWin32 project,and to **PATH** in environment variables, you need to add `;C:\%PROGRAMFILES%\GnuWin32\bin` But you shold really use module zipfile as suggsest by Grib. …

Member Avatar for jeremywduncan
0
431
Member Avatar for tony75

> I was welcomed with a lot of negative feedback, due to "Hmm PEP-8 falling on my head", thus my next move would be to offering you some exemplified links to help you figure that out. So here it is: Sorry it's was more about how your code was indented,your …

Member Avatar for tony75
0
345
Member Avatar for bdheeraj

Use [cx_Freeze](http://cx-freeze.sourceforge.net/) You should also set up `Environment Variables` to point to Python32. http://www.daniweb.com/software-development/python/threads/359605/python-not-recognized This mean that you can type `python` in any path in cmd(windows command line) and Python will start. ''' my_cx_freeze.py To run code from cmd python my_cx_freeze.py build Eksp from cmd: C:\Python32\Scripts>python my_cx_freeze.py build ''' from …

Member Avatar for vegaseat
0
5K
Member Avatar for clouds_n_things

urlopen() take string as argument. So no need to use input() that return integer,use raw_input(). You should by the way never use input() in python 2.x,use int(raw_input()) for integer return. input() in python 2.x has some safty issues,this has been fixed in python 3. String formatting is natural way to …

Member Avatar for clouds_n_things
0
182
Member Avatar for krystosan

>>> #Python2.x >>> key = 5 >>> print "module {0}".format(key) module 5 >>> #Python 3.x >>> print("module {0}".format(key)) module 5

Member Avatar for vegaseat
0
345
Member Avatar for aVar++

You can use `itertools permutations` for this. If this is a school task,follow woooee explanation. And try to figure a way to get permutation without using build in tools like itertools. Can simplify class to you dont need a method(printNum),class already has that info as you see a take out …

Member Avatar for Ene Uran
0
289
Member Avatar for scubastevie

Some more ways,i use `numbers.txt` as shown by Lucaci. with open('numbers.txt') as f: print [i.strip() for i in f] #['1', '2', '3', '4', '5', '6', '7', '8'] So we get a list of numbers that are strings. To get a list with integer or float,use `int()` or `float()` with open('numbers.txt') …

Member Avatar for Lucaci Andrew
0
228
Member Avatar for jeremywduncan

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.

Member Avatar for TrustyTony
-1
784
Member Avatar for SteveA

All `txt` files in blah. import glob for files in glob.glob(r'C:\blah\blah\*.txt'): print files Run all files through [os.stat](http://docs.python.org/2/library/os.html?highlight=os.stat#os.stat) What you need is `st_mtime`,nr 8. Now you can use time(`import time`),make a time object for `14_days` back. Make a time object from `os.stat(files)[8]`call it `lastmod_date`. Compare `14_days > lastmod_date` use `os.remove(files)` …

Member Avatar for Ene Uran
0
309
Member Avatar for Octet

Some repating code like Val1,Val2 is not so god. You should make a funcion for this and send function/operator in as argument. Maybe this help,here is how i would write this. I use a dictionary with lambda for operators to shorten the need for 4 function,Addition(),Multiplication().... def showoptions(): print("1. Addition") …

Member Avatar for Octet
0
210
Member Avatar for krystosan

>>> names = ['Google', 'Apple', 'Microsoft'] >>> for index,item in enumerate(names): print index,item 0 Google 1 Apple 2 Microsoft

Member Avatar for vegaseat
0
201
Member Avatar for Greyhelm

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

Member Avatar for Greyhelm
0
419
Member Avatar for longtomjr

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 …

Member Avatar for woooee
0
225
Member Avatar for clouds_n_things

> If the data endered ends with one of the 3 extensions, I would like it to be returned and the snes emulator to be opened. Your logic dos not make sense to me. If user input `game.smc`,should all files that has a smc extensions be found? Explain your self …

Member Avatar for clouds_n_things
0
169
Member Avatar for wrathofmobius

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']` …

Member Avatar for wrathofmobius
0
8K
Member Avatar for romes87

For fun one with regex,but i guess this is a school task? import re string = 'alpha 111 bravo 222 alpha somethingA end, 333 bravo somethingB end 444 alpha 555 bravo' pattern = re.compile(r'(alpha|bravo)(\s\w+\s)(end)') for match in pattern.finditer(string): print match.group(2).strip() """Output--> somethingA somethingB """

Member Avatar for TrustyTony
0
251
Member Avatar for mkweska

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

Member Avatar for mkweska
0
226
Member Avatar for inuasha
Member Avatar for padton

You can try this,glob will iterate over all your `file..txt` I use `fileinput` module to open all files. Then calulate two sum based on `enumerate` even/odd. import fileinput from glob import glob sum_file = open("SumFile.csv", "w") total = 0.0 total_1 = 0.0 fnames = glob('file*.txt') for numb,line in enumerate(fileinput.input(fnames)): if …

Member Avatar for snippsat
0
225
Member Avatar for biscayne

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'

Member Avatar for vegaseat
0
239
Member Avatar for flebber

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 …

Member Avatar for flebber
0
149
Member Avatar for shanew21

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

Member Avatar for snippsat
0
195
Member Avatar for UnchainedDjango

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 …

Member Avatar for UnchainedDjango
0
647
Member Avatar for krystosan

I think doc explain it ok [os.getenv()](http://docs.python.org/2/library/os.html?highlight=os.getenv#os.getenv) and [sys.path](http://docs.python.org/2/library/sys.html?highlight=sys.path#sys.path) A simplified explation of some use of those could be. If i want to import a Python module made by me or other,i have to make sure it is in `sys.path` so Python can find it. In my windows environment variables …

Member Avatar for krystosan
0
1K
Member Avatar for felix001

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 …

Member Avatar for vegaseat
0
124
Member Avatar for krystosan

> but i wanted to learn re module.. Start with something simpler. An example could be something like this. Match phonenumber with +. >>> import re >>> s = '"taruna"," 09015561619"," +918968391049",,"tarunthegreat43@gmail.com",,,' >>> re.findall(r'\+\d+', s) ['+918968391049'] So `\+` macth `+`. `+` alone has a spesiell mening(Matches 1 or more of …

Member Avatar for snippsat
0
406
Member Avatar for Cravver

A space in in gdata youtube search is `%20` So if you search for `car bmw`,then it should look like this `car%20bmw` Here is one way of do it. >>> word = 'car bmw' >>> word = word.split() >>> word ['car', 'bmw'] >>> space = '%20' >>> word = space.join(word) …

Member Avatar for Cravver
0
280
Member Avatar for padton

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 …

Member Avatar for vegaseat
0
444
Member Avatar for efwon

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

Member Avatar for snippsat
0
234
Member Avatar for biscayne

Use "else" block. if andexfield == elem: do bladibla else: print "Error, no andexfield in fname" Error would be more normal to occur before you compare with ==. Like open file or get index/iterate list `lstData[0]` `lstLine[1:]`

Member Avatar for Gribouillis
0
278
Member Avatar for slasel

> thanks but why doesn't the sleep work...? If you look at the documentation for [time.sleep()](http://docs.python.org/2/library/time.html#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 …

Member Avatar for Ene Uran
0
437
Member Avatar for ailen.samson

> > a = [0,1,2,3,4,5,6,7,8,9] > > a[0]=input() > a[1]=input() > a[2]=input() > a[3]=input() > a[4]=input() > a[5]=input() > a[6]=input() > a[7]=input() > a[8]=input() > a[9]=input() In Python we dont like long code that dos repating stuff. >>> [int(raw_input('Enter numbers: ')) for i in range(10)] [90, 5, 27, 63, 12, …

Member Avatar for woooee
0
904
Member Avatar for darealsavage

> also i still have no idea how to just import the excell spreadsheet into python to use, You most use using something like [xldr](http://www.python-excel.org/) A example of use [here](http://www.daniweb.com/software-development/python/threads/379289/using-an-excel-spreadsheet-as-an-argument-for-a-python-script) by Gribouillis. > ive also tryed just using the numbers in a .txt file.. like so. An example of how …

Member Avatar for snippsat
0
265
Member Avatar for redcar2228

As posted over the full Traceback tell you where in code you get the error. > Im getting an index out of range error? Please help! So to make a `index out of range error`. >>> l = [1,2,3,4] >>> l[3] 4 >>> l[4] Traceback (most recent call last): File …

Member Avatar for snippsat
0
394
Member Avatar for crashhold
Member Avatar for crashhold
0
323

The End.