880 Posted Topics
>I, and many others, desired a "switch" keyword in Python. Do not speak for "others". The swith/Case statement was finally rejected in 2006 [PEP 3103](https://www.python.org/dev/peps/pep-3103/) >For me it was to a desire to make some of my code more compact and readable The desired goal of readability don't show i …
>I installed Python v 3.4.3 pip comes pre-installed on Python 3.4.3,do **not** install pip. First set up [environment Variables Path](https://vimeo.com/70504477), Same as in video,but also point to script folder(pip placement),so for Python 3.4 you add `;C:\python34\;C:\python34\scripts` to Path. >What "terminal" am I using, and what's with the "$" symbol? I …
It's a little old way of doing this,but it work if fixing as Girb posted. You should not make a seperate line for count. Do it like this. my_dict = {} s = 'hello world hello' for word in s.split(): if word in my_dict: my_dict[word] += 1 else: my_dict[word] = …
Good effort,i give you a up vote:) But have to mention your code style again,it's not so pretty. I link to [PEP-8](https://www.python.org/dev/peps/pep-0008/) in your post, just to show a doc that can help you in the future regarding code style. Here a version i made, Look a little at how …
You have to install [wheel](http://pythonwheels.com/) with `pip`. On Python 2.7.9 is pip pre-installed. Put `PyQt4-4.11.3-cp27-none-win32.whl` in `C:\Python27\scripts` folder. Start *cmd* navigate to `C:\Python27\scripts` folder, then do: `pip install PyQt4-4.11.3-cp27-none-win32.whl`
Think about your design. One textbox user enter 3 number. Then operator / and then user enter new number and you get and average. Like a normal calculator. What if user want average of 5 number,should you create 5 textboks?
Also [here](http://www.python-forum.org/viewtopic.php?f=6&t=15584):)
You have been told before to before to watch your coding style. Stop using `global`. There is a also build module that solve this in Python 3. from functools import lru_cache @lru_cache(maxsize=None) def fib(n): if n < 2: return n return fib(n-1) + fib(n-2) Test all computation are instantly. >>> …
Or a more modern [click here](http://docs.python-requests.org/en/latest/) :)
It's started (: Find some videos that are interesting,feel free to post link or discuses it here. I was looking most forward to David Beazley talks. Live coding with Concurrency as topic,doesn't get much better than this. [David Beazley - Python Concurrency From the Ground](https://www.youtube.com/watch?v=MCs5OvhV9S4) The main talk David Beazley …
You use [subprocess](https://docs.python.org/3/library/subprocess.html) module. import subprocess calc_program = "path_to_program" subprocess.call([clac_program])
Use [string formatting](https://mkaz.com/2012/10/10/python-string-format/) >>> value = 1000000000000 >>> n = "{:,}".format(value) >>> print(n) 1,000,000,000,000 >>> #Back to float >>> float(n.translate(None, ',')) 1000000000000.0
>because my anaconda distribution doesn't seem to have linprog (?) You can use `pip install` or `conda install`(Scripts folder) to get new stuff into Anaconda. For this is best to use `conda install scikit-learn`,then you get all new packages that scikit-learn need. Look like this when run `conda install scikit-learn`. …
Hello world on the wall? This is a rewite of some code i did for a "99 bottles of beer" challenge. Use Google image API and take out some random images. Use IPython Notebook to show result. Here some result. [Hello world](http://nbviewer.ipython.org/gist/snippsat/684d842813fc4b401423) [Hello World Python](http://nbviewer.ipython.org/gist/snippsat/940a13a3fa0acf9a4ee0) [Hello World Linux](http://nbviewer.ipython.org/gist/snippsat/d1c196e3c601a3029de8)
[psutil](https://pypi.python.org/pypi/psutil/#downloads) is good. Here a run on my windows and Mint(VirtualBox) >>> import psutil >>> psutil.disk_partitions() [sdiskpart(device='C:\', mountpoint='C:\', fstype='NTFS', opts='rw,fixed'), sdiskpart(device='D:\', mountpoint='D:\', fstype='', opts='cdrom'), sdiskpart(device='E:\', mountpoint='E:\', fstype='NTFS', opts='rw,fixed'), sdiskpart(device='F:\', mountpoint='F:\', fstype='UDF', opts='ro,cdrom'), sdiskpart(device='G:\', mountpoint='G:\', fstype='NTFS', opts='rw,fixed')] >>> psutil.disk_usage('C:\') sdiskusage(total=255953203200L, used=177126027264L, free=78827175936L, percent=69.2) Mint: >>> import psutil >>> psutil.disk_partitions() [partition(device='/dev/sda1', mountpoint='/', …
Here are the diffrent ways, and also what i would call the prefered way these day with [Requests](http://docs.python-requests.org/en/latest/#). Python 2: from urllib2 import urlopen page_source = urlopen("http://python.org").read() print page_source Python 3: from urllib.request import urlopen page_source = urlopen('http://python.org').read().decode('utf_8') print(page_source) For Python 3 to get `str` output and not `byte` we …
>so why it didn't print the url of each website into output?! Because this is a dynamic site using JavaScript,jQuery.... The problem is that JavaScript get evaluatet by DOM in browser. To get links we need something that automates browsers like [Selenium](https://pypi.python.org/pypi/selenium). Can show you one way,here i also use …
>So now i want my script to find every word that start with "A" in that url page >and print it for me. Then i should find a way to ask my crawle just save those >words starting with "A" that are singers names. >Very difficult!!! That would be nightmare,and …
David W it's about time to learn string formatting :) Splitting up with `,` and `+ something +` is not so nice. print('"{}".istitle() is {}'.format(item, item.istitle())) [Python String Format Cookbook](https://mkaz.com/2012/10/10/python-string-format/) [string formatting specifications(Gribouillis)](https://www.daniweb.com/software-development/python/code/232375/string-formatting-specifications)
>Use regular expressions Click Here No no no just to make it clear :) Have to post this [link](http://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags) again. Use a parser Beautifulsoup or lxml. from bs4 import BeautifulSoup html = '''\ <head> <title>Page Title</title> </head> <body> <li>Text in li 1</li> <li>Text in li 2</li> </body> </html>''' soup = …
Change last part to this. lst = [] for k in d: high = int(max(d[k])) lst.append((k, high)) score_lst = sorted(lst, key=lambda tup: tup[1], reverse=True) for name,score in score_lst: print('{} {}'.format(name, score)) It's ok to throw away lambda,and use itemgetter as shown by slavi.
Use the new [bs4](http://www.crummy.com/software/BeautifulSoup/bs4/doc/),do not call old BeautifulSoup. Do not use `read()`,BeautifulSoup detect encoding and convert to Unicode. As mention you need take out `href attributes`, and you most learn to study webpage with [Firebug](http://getfirebug.com/) or [Chrome DevTools](https://developer.chrome.com/devtools). So then you see that you only need adresses that start with …
As Andrae posted,but need to close file object. f = open('url.txt', 'w') #Opens the file to write text f.write(url) #Writes the file to the opened text file f.close() Or the best approch is to use `with open()`,no need to close file object. import urllib url = 'http://www.python.org' text = urllib.urlopen(url).read() …
Yes is called default argument. def say(msg, arg='something'): print 'first argument <{}> default argument <{}>'.format(msg, arg) >>> say('hello') first argument <hello> default argument <something> >>> say('hello', 'world') first argument <hello> default argument <world> Many arguments. def foo(*arg): return sum(arg) >>> foo(1,2,3,4,5,6,7,8,9,10) 55 Keyword arguments. def bar(**kwargs): for key, value in …
>>> answer = ('7', 'Q', '5', 'H', '9', '4', '3', '8', 'L') >>> print(' '.join(answer)) 7 Q 5 H 9 4 3 8 L >>> help(''.join) Help on built-in function join: join(...) method of builtins.str instance S.join(iterable) -> str Return a string which is the concatenation of the strings in …
Don't call both function main,use name that make sense. import random def generate_numbers(): one = 1 thirteen = 13 subtract = 1 number_gen = open('numbers.txt', 'w') for number in range(one,thirteen,subtract): numbers = random.randint(1,100) number_gen.write(str(numbers) + ' ') number_gen.close() def read_numers(numb): numbers_read = open(numb) numbers = [float(n) for n in numbers_read.read().split()] …
Look's like you need [Avbin](http://avbin.github.io/AVbin/Home/Home.html) An other option is to use your favorite player. import subprocess # pick an external mp3 player you have sound_program = "path to player" # pick a sound file you have sound_file = "path to mp3" subprocess.call([sound_program, sound_file])
Here is a big hint. >>> import random >>> s = 'i am a programmer' >>> ''.join(random.sample(s, len(s))) 'm mraep mriago ra' >>> #no whitespace >>> s_1 = ''.join(s.split()) >>> ''.join(random.sample(s_1, len(s_1))) 'omagripramamer'
A test with [dataset](http://dataset.readthedocs.org/en/latest/index.html),database as simple as it get. So here i have a player list that i store in a Sqlite(comes with Python) database. import dataset player_lst = [ {'name': 'Tom', 'score': 250}, {'name': 'Kent', 'score': 150}, {'name': 'Paul', 'score': 500} ] db = dataset.connect('sqlite:///mydatabase.db') table = db['Score_table'] for …
A look at [Dataset](http://dataset.readthedocs.org/en/latest/) and easy and Pythonic way to create a database. Other candidates in this categorie,i will mention [pyDAL](https://github.com/web2py/pydal) and [Peewee](https://peewee.readthedocs.org/en/latest/). I did some test of Dataset in this [post](https://www.daniweb.com/software-development/python/threads/490219/how-can-i-creat-e-text-file-to-use-as-a-database-in-python) to look at. So here a common task some web-scraping of food recipes(just a task i did help …
>>> text = "trans panamanian bananas" >>> text.count('an') 6 -- >>> import re >>> len(re.findall(r'an', text)) 6
Pillow fork dos more than just bugfix of orginal PIL. It now comes with [new stuff and serval improvements](http://blog.uploadcare.com/post/106828637418/pillow-2-7-extended-release-notes). So it can be smart to get Pillow instead of PIL.
You have module like py2exe,cxfreeze,gui2exe that will give you(exe) to run without python installed. If that what you mean.
Cant find what you search in respData. Do post also post your import. import urllib.request, urllib.parse This is the adress,you get data from. >>> resp.geturl() 'https://ca.finance.yahoo.com/lookup?s=basics' Do you find `Price Book or class="yfnc_tabledata1` in url or in return respData? Some notes this use JavaScript heavy,and are not a easy site …
You should use [after](http://infohost.nmt.edu/tcc/help/pubs/tkinter/web/universal.html) Tkinter is running an infinite loop(the event loop). When you use a while loop and time sleep,then this can lock up(block GUI). That's why all GUI toolkit has some kind of timer/schedule/thread task, that dont interfer with the running event loop. In Wxpython that i have …
You can not open 2 exe in binary mode,and try to merge these into 1 file. `exe` are standalone programs,that has to be open separately. Here a demo of what i mean,with subprocess and threads to open 2 files. #2_exe_start.py import subprocess import threading def file_1(): subprocess.call([r'C:\Windows\notepad.exe']) def file_2(): subprocess.call([r'C:\Windows\explorer.exe']) …
To fix your orginal code. def translate(): a = {"merry":"god", "christmas":"jul", "and":"och", "happy":"gott", "new":"nytt", "year":"Ã¥r"} return a for k, v in translate().iteritems(): print k, v You need to practice more on using functions. It make no sense to take a argument `a`,when all you have in function is a dicionary. …
A couple of ways. from __future__ import print_function def generate_n_chars(n, a): for i in range(n): print(a, end='') def generate_n_chars_1(n, a): result = '' for i in range(n): result += a return result Test: >>> generate_n_chars(7, 'j') jjjjjjj >>> print generate_n_chars_1(20, 'z') zzzzzzzzzzzzzzzzzzzz
Is this all of your code? There are missing several function definition here. You never use `return` without a function. Post all of you code and full `Traceback`. Or at least code we can run that give this Traceback. Traceback always give you linenumber where error occur. Here is a …
With enumerate(). >>> mylist1 = [1,2,3] >>> mylist2 = ['a','b','c'] >>> for index, item in enumerate(mylist2, 2): ... mylist1.insert(index, item) ... >>> mylist1 [1, 2, 'a', 'b', 'c', 3] Flatten list approach. def flatten(container): for i in container: if isinstance(i, list): for j in flatten(i): yield j else: yield i …
A distribution such as [Anaconda](https://store.continuum.io/cshop/anaconda/) make it easy to run iPython notebook without thinking of dependencies. I aslo have [Miniconda](http://conda.pydata.org/miniconda.html) wish i run iPython notebook/Spyder for python 3.4 from. Anaconda is closed enviroment so it would not affect orginal installed Python. My main version that i use most is still …
A little look at [concurrent.futures](https://docs.python.org/dev/library/concurrent.futures.html) concurrent.futures has a minimalistic API for threading and multiprocessing. Only change one word to switch `ThreadPoolExecutor(threading)` and `ProcessPoolExecutor(multiprocessing)`. [concurrent.futures](https://pypi.python.org/pypi/futures) is backportet to Python 2.7 A look at `ProcessPoolExecutor(multiprocessing)` from __future__ import print_function from time_code import timeit import concurrent.futures import time def counter(n): """show the count …
Some hint that should help you. >>> lst = [1,2,3,4,5,6] >>> lst[:3] [1, 2, 3] #Assign to list thorny >>> help(lst.append) Help on built-in function append: append(...) L.append(object) -- append object to end #Or >>> help(lst.extend) Help on built-in function extend: extend(...) L.extend(iterable) -- extend list by appending elements from …
wooee show that `range()` work fine,another good and pythonic way is to use a generator. If also use [itertools.islice()](https://docs.python.org/2/library/itertools.html#itertools.islice) can make it even more versatile. from itertools import islice def fib(a=7, b=18): yield a while True: yield b a, b = b, a + b fib_numb_1 = list(islice(fib(),15)) # Slice …
Look at this [post](https://www.daniweb.com/software-development/python/threads/481966/optional-funtions#post2107767)
As mention bye chriswelborn use [Flask](http://flask.pocoo.org/) or [Bottle](http://bottlepy.org/docs/dev/index.html). CGI is dead in Python after [PEP 3333](http://legacy.python.org/dev/peps/pep-3333/)(WSGI). Flask,Bottle is a layer above WSGI and 100% WSGI compliant. > You need some JavaScript to get the value from your input box. JavaScript is not needed for this Flask has of course stuff …
>>> zip(*[iter(mylist)]*3) [(0, 1, 2), (3, 4, 5), (6, 7, 8), (9, 10, 11)]
> either I guess ungalcrys has left Python a long time ago. This is his only post over 4 year ago,look at dates.
> If you really wanted it in list format you could do this to it: Yes i agree if that's really what BingityBongity want, but a plain list with no connetion between vaules seems not right. Just use `dict.items()` then key and value from dict are together in tuple. >>> …
Use [PyUserInput](https://github.com/SavinaRoja/PyUserInput) Install [Pywin32](http://www.lfd.uci.edu/~gohlke/pythonlibs/#pywin32) and [Pyhook](http://www.lfd.uci.edu/~gohlke/pythonlibs/#pyhook) Install [pip](http://www.lfd.uci.edu/~gohlke/pythonlibs/#pip) Then do `pip install PyUserInput` from pykeyboard import PyKeyboard k = PyKeyboard() # pressing a key k.press_key('H') # which you then follow with a release of the key k.release_key('H')
The End.