880 Posted Topics
Re: 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 … | |
Re: 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 … | |
Re: 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 #? … | |
Re: > 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 … | |
Re: 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', … | |
Re: 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 … | |
Re: 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 """ | |
Re: > 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 … | |
Re: > 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 … | |
Re: > 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 … | |
Re: All versions are [here](http://www.lfd.uci.edu/~gohlke/pythonlibs/#pywin32) | |
Re: > 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 … | |
Re: 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. … | |
Re: `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 … | |
Re: 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) | |
Re: > 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. … | |
Re: > 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 … | |
Re: 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 … | |
Re: 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 … | |
Re: >>> #Python2.x >>> key = 5 >>> print "module {0}".format(key) module 5 >>> #Python 3.x >>> print("module {0}".format(key)) module 5 | |
Re: 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 … | |
Re: 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') … | |
Re: 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. | |
Re: 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)` … | |
Re: 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") … | |
Re: >>> names = ['Google', 'Apple', 'Microsoft'] >>> for index,item in enumerate(names): print index,item 0 Google 1 Apple 2 Microsoft | |
Re: 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. … | |
Re: 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 … | |
Re: > 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 … | |
Re: 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']` … | |
Re: 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 """ | |
Re: 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, … | |
Re: `test.txt` is a file,so you have to open it for read `open('test.txt'):` | |
Re: 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 … | |
Re: 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' | |
Re: 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 … | |
Re: > 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, … | |
Re: 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 … | |
Re: 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 … | |
Re: 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 … | |
Re: > 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 … | |
Re: 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) … | |
Re: 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 … | |
Re: 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 | |
Re: 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:]` | |
Re: > 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 … | |
Re: > > 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, … | |
Re: > 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 … | |
Re: 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 … | |
Re: Hi rrashkin nice to see you here,do you know status of "python-forum.org"? |
The End.