0

The Python Image Library (PIL) lets you handle images. Here is an example that loads a small image and a large image, and pastes the smaller image on top of the larger one ...

# paste a smaller image on top of another image
# using the Python Image Library (PIL) from ...
# http://www.pythonware.com/products/pil/index.htm
# tested with Python 2.6.5

from PIL import Image

fname1 = "Duck.jpg"
fname2 = "french_flag.jpg"

img1 = Image.open(fname1)
img2 = Image.open(fname2)

# test
print(img1.size)
print(img2.size)

# paste img2 onto img1 at coordinates x=130  y=50
# the upper left corner(ULC) of img2 will at (x, y)
img1.paste(img2, (130, 50))

# save the modified picture
img1.save("french_duck.jpg")
# use module webbrowser to show image file
import webbrowser
webbrowser.open("french_duck.jpg")
Attachments Duck.jpg 4.5 KB french_flag.jpg 0.64 KB
1

If you use the Python write() function to write to a text file, Windows normally puts in a '\r\n' line separator. This is somewhat annoying for Linux users that expect only a '\n' newline character. Python3 has solved this with the newline keyword when you open a file for writing ...

# write text file Unix style with only '\n' as line separator

text = """\
This broom does not actually fly.
For indoor or outdoor use only.
Product will be hot after heating.
Do not use while sleeping.
Open bottle before drinking.
Keep away from children.
Some assembly required.
"""

fname = "atest7.txt"

# Windows would normally use '\r\n'
# specify Unix style '\n' this way, needs Python3
fout = open(fname, "w", newline='\n')
fout.write(text)
fout.close()
0

This short code will create a list of the starting dates of the weeks in a given year ...

# create a list of all starting dates of the weeks in a given year

import calendar

def get_week_list(year, start_week=calendar.MONDAY):
    """
    create a list of starting dates for all the weeks in a given year
    start_week=calendar.MONDAY is actually the default
    """
    # set the first day of week
    calendar.setfirstweekday(start_week)    
    week_list = []
    for month in range(1, 13):
        for day in range(1, 32):
            try:
                weekday = calendar.weekday( year, month, day)
            except ValueError:
                continue
            if weekday == start_week:
                # format the result
                week_start = "%02d/%02d/%d" % (month, day, year)
                week_list.append(week_start)
    return week_list


year = 2010
monday_list = get_week_list(year)

# pretty print the list
import pprint
pprint.pprint(monday_list, indent=0)

""" result >>>
['01/04/2010',
'01/11/2010',
'01/18/2010',
'01/25/2010',
'02/01/2010',
'02/08/2010',
'02/15/2010',
'02/22/2010',
'03/01/2010',
'03/08/2010',
'03/15/2010',
'03/22/2010',
'03/29/2010',
'04/05/2010',
'04/12/2010',
'04/19/2010',
'04/26/2010',
'05/03/2010',
'05/10/2010',
'05/17/2010',
'05/24/2010',
'05/31/2010',
'06/07/2010',
'06/14/2010',
'06/21/2010',
'06/28/2010',
'07/05/2010',
'07/12/2010',
'07/19/2010',
'07/26/2010',
'08/02/2010',
'08/09/2010',
'08/16/2010',
'08/23/2010',
'08/30/2010',
'09/06/2010',
'09/13/2010',
'09/20/2010',
'09/27/2010',
'10/04/2010',
'10/11/2010',
'10/18/2010',
'10/25/2010',
'11/01/2010',
'11/08/2010',
'11/15/2010',
'11/22/2010',
'11/29/2010',
'12/06/2010',
'12/13/2010',
'12/20/2010',
'12/27/2010']
"""

Edited by vegaseat: a

0

This short code will create a list of the starting dates of the weeks in a given year ...

My alternative (little generalized):

# find next given weekday by generator, use tuple or list to save for random access

import datetime as dt 

def get_week_start(year, month=1, day=1, start_week=0):
    """ find start_week weekdays starting from year, month, day, start_week (default 0 = Monday) """
    # set the first day of week
    thisday = dt.date(year,month,day)
    ## return first day which has weekday start_week, possibly the year, month, day (modulo 0)
    thisstart = thisday + dt.timedelta((7 - start_week - dt.date.weekday(thisday)) % 7)
    yr = thisstart.year
    # format the result
    while year == thisstart.year:
        yield thisstart.strftime('%m/%d/%Y')
        thisstart += dt.timedelta(7)
        
# the years dates from generator, columnar print of tab-joined dates
today = dt.date.today()
print('\t'.join(get_week_start(today.year)))

yearmondays=tuple(get_week_start(today.year)) # saving as tuple
mondays = get_week_start(today.year, today.month, today.day)

print "Next Monday is %s" % next(mondays)
print "and next after that is %s." % next(mondays)

Edited by pyTony

1

"How to think like a computer scientist" is a great read, and source for coding basics

0

Here small assignment to practice processing of input by using method of starting small and adding and testing the code step by step

for number in ('a','b','1','','234234', '-234','4','-1'):
     if check(number):
         if in_correct_range(int(number), low, high):
             print('Good! You gave right size of number')
         else:
             print('The number you gave was outside the limits')
     else:
          print('That was not number')

Here is missing two functions you should define and the fixed values for range check. Write those. After that change this loop to while, which only exits the loop when correct input is given. Then put everything in function that returns that correct value out from function as integer.

3

Want to do some spell checking using Python?
Here is one way:

# download pyenchant-1.6.5.win32.exe from
# http://pypi.python.org/packages/any/p/pyenchant/
# then install for Python31 (my case) or Python27
# see http://www.rfk.id.au/software/pyenchant/tutorial.html
# check a text against 2 different enchant dictionaries

from enchant.checker import SpellChecker

# use the US/English dictionary
chkr = SpellChecker("en_US")
text = "This is sme sample txt with erors."
chkr.set_text(text)
for err in chkr:
    print( "ERROR: %s" % err.word )

'''
ERROR: sme
ERROR: txt
ERROR: erors
'''

# try the German dictionary
chkr = SpellChecker("de_DE")
text = "Ein Deutscher Satz mid einigen fehlern."
chkr.set_text(text)
for err in chkr:
    print( "Error (German): %s" % err.word )

'''
Error (German): mid
Error (German): fehlern
'''

This gives you the available dictionary languages:

import enchant

# check default dictionary
d = enchant.Dict()
print(d.tag)  # en_US

# show available languages
print(enchant.list_languages())
'''
['de_DE', 'en_AU', 'en_GB', 'en_US', 'fr_FR']
'''
Votes + Comments
great stuff
Nice links
0

An interesting play with iterators and generators:

it = iter(range(9))

# note iterator it depletes within zip()
mylist = list(zip(it, it, it))

print(mylist)

'''my output -->
[(0, 1, 2), (3, 4, 5), (6, 7, 8)]
'''

I tested this with Python26.

1

Applying deque to a Caesar Cipher. Wordy enough so you can figure it out:

# Caesar Cipher encryption/decryption
# using Python's double-ended queue

from collections import deque

def doCaesarCipher(text, shift):
    alpha = 'abcdefghijklmnopqrstuvwxyz'
    dq = deque(alpha)
    # shift/rotate the alphabet (dq in place)
    dq.rotate(shift)
    encrypted = ""
    for c in text.lower():
        if c in alpha:
            index_alpha = alpha.index(c)
            encrypted += dq[index_alpha]
        else:
            encrypted += c
    return encrypted


text = 'pumpkin'
# positive value shifts to the right
# negative value shifts to the left
shift = -5
encrypted = doCaesarCipher(text, shift)

print(text)       # pumpkin
print(encrypted)  # uzrupns

# shift to the right to get original text back
print(doCaesarCipher('uzrupns', 5))  # pumpkin
Votes + Comments
Clever use of deque.
1

Simple, but very interesting permutations:

# permutations using Python's itertool module
# needs Python26 or higher
# itertools.permutations(iterable[, r]) is a generator/iterator

# needs Python26+
import itertools as it

word = "rats"
# default is len(word)
for p in it.permutations(word):
    # join tuple p to form a string
    print( ''.join(p) )

""" my output (find existing words and possibly new words) --->
rats
rast
rtas
rtsa
rsat
rsta
arts
arst
atrs
atsr
asrt
astr
tras
trsa
tars
tasr
tsra
tsar
srat
srta
sart
satr
stra
star
"""

Can be used to find new words. How about:

My rast has caused nothing but stra!

1

Lardmeister, that is a good use of itertools.permutations to find string permutations.

I just want to explicitly caution others that when working with permutations you should use generators like Lardmeister is. The number of permutations of a string is the factorial of its length. Don't attempt to store all of the permutations in a collection. You can quickly run out of memory.

Votes + Comments
good point here
0

The Caesar cipher is also good, but I'd like to mention a couple of things.

The string module has constants for ascii_letters, ascii_uppercase, and ascii_lowercase.

A constant can be safely created outside of a function and still be used within it.
This is preferred when calculation is involved in creating the constant because it will only occur once instead of each time the function is called.

We should generally use str.join for string concatenation. In certain situations adding strings is faster than str.join, but in other situations adding strings occurs in quadratic time. O(n**2)

It's also possible to use a bytes translation to perform a Caesar shift, but you have to create the translation table for each shift. I think it would be less efficient than Lardmeister's implementation. However, if your program only ever needs shifts by one value, say 5, it might be better.

Edited by lrh9: n/a

1

This will give you the size of the display screen area usable by your program ...

# get the size of your usable display screen area
# root will not show up

try:
    # Python2
    import Tkinter as tk
except ImportError:
    # Python3
    import tkinter as tk

root = tk.Tk()
# make window full displayable size:
root.state('zoomed')
root.update()

width = root.winfo_width()
height = root.winfo_height()
print("The usable screen size (w x h) is: %s x %s" % (width, height))
0

Explain what this program does and write doc string for the function so that hint in IDLE is helpful when writing code using the function.

Explain for every line how and why they work in separate explanation or bid docstring in beginning of the file (module).

from collections import deque

def tail(n = 10, fn = 'alice.txt'):
    lines = deque(open(fn), maxlen=n)
    print((' %s (%i)' % (fn, n)).center(60, '*'))
    print(''.join(lines))

if __name__ == '__main__':
    tail()

EDIT: Maybe I should have put this to project for beginner as I wrote it in task form?

Edited by pyTony: n/a

0

The idea of this thread is to help the beginning Python programmer with hints and helpful code. Please feel free to contribute! If you have any questions start your own thread!


The creators of Python are very active, improving the language all the time. Here is a little of the version history:
Python24 March 2005
Python25 Sept 2006
Python26 Sept 2008
Python27 July 2010 (final version of the Python2 series)
Python31 July2009
Python32 February 2011
You can download the version you like free from: www.python.org
Selfextracting MS Installer files have a .msi extension and contain the version number, for instance python-3.1.msi.
Editors note:


Linux users can install Python installers from:
http://www.activestate.com/activepython/python3/
For the folks who like to do the unusual, Python is equally at home on the Apple computers. It is my understanding that Linux and Apple OS X have Python already installed. Apple users should check http://undefined.org/python/

I installed my Python on the D: drive, so I ended up with a D:\Python31 folder after the installation. The first step is to create a subfolder (subdirectory) for all your test programs, like D:\Python31\Atest31.

There is a Python editor included with the Python installation. The program is called IDLE, a small, but capable Integrated Development Environment (IDE), that you can use to write, edit, run and debug your code from. The problem is that it is hidden in subfolders. I found it in
D:\Python31\Lib\idlelib\idle.pyw

The .py or .pyw extension is used for Python code files. With Windows, all you need to do is to double click on idle.pyw and after a fraction of a second the compiled program appears on your screen.

If your version of IDLE starts up in the Shell Window, the one with the >>> prompts, go to 'Options' on the top line and then click on 'Configure IDLE'. In the configure menu go to the 'General' page and set the 'Open Edit Window' at startup option, then click on 'Apply'.

I think that coding in the interactive shell, also called the command line option, is limited to one liners, simple calculations and calls for help. Anything else is just major confusion, and has turned off a lot of fine folks from using Python! Lamentably, much of the Python docs are littered with command line examples with its many >>> prompts and ... line indent markers. Do not use those >>> prompts and markers in your code editor.

Once you are in the Edit Window with its simple flashing cursor, type in your first Python program (no, the line number is not part of the code). Press (Toggle Plain Text), if you want to copy and paste into your editor.

print( "Hello Monty Python!" )

On the top menu bar click on File and save the short program in the Atest folder as HelloMP1.py now press the F5 key (or click on Run then on Run Module). The Python interactive Shell appears telling what version of Python you are running, and wedged between >>> prompts is Hello Monty Python!

Not much, but it worked, your first Python program. After you admired this for a while, press the Alt and F4 keys at the same time (or File then Close) to leave the Shell and get back to the Editor.

Let's create a second version of the simple program. Replace 'print' with 'str1 =' and add a few more lines ...

str1 = "Hello Monty Python!"
# this is a comment
# notice you don't have to declare the variable type
print( str1 )
..... 

Editor's note:
I have started to update some of the posts to reflect changes in Python3.  Also changed some of the code to make it work with Python2 and Python3 versions.  This is work in progress, tough for my old tired eyes.[/QUOTE] 
Good for you to edit this valuable resource, but maybe same time you could collect some tutorial topics to double post as tutorials (which never seem to be published, but they come to main page if I open Daniweb adapted home page showing the favorite forums).

I would be happier also if you would go along with PEP8 in your print statements/functions, no

[code]
print( str1 )

but

print(str1)

str1 is maybe also not ideal name for variable, but it is difficult to come up with better in this specific example use.

Edited by pyTony: n/a

0

There are times when you want to process a string ...

# experiments with string processing
# change string to lower case and remove punctuation marks

from string import punctuation

text = """\
It is said, that if you line up all the cars in the world end to end, 
someone would be stupid enough and try to pass all of them!
Dr. Seuss pronounced "Seuss" such that it rhymed with "rejoice."
Al Capone's business card said he was a 'used furniture dealer'.
""" 

# since Capone's would turn into capones, optionally remove 's
text2 = text.replace("'s", "")

# remove punctuation marks and change to lower case    
text3 = ''.join(c for c in text2.lower() if c not in punctuation)

print(text)
print('-'*68)
print(text3)

''' result ...
It is said, that if you line up all the cars in the world end to end, 
someone would be stupid enough and try to pass all of them!
Dr. Seuss pronounced "Seuss" such that it rhymed with "rejoice."
Al Capone's business card said he was a 'used furniture dealer'.

--------------------------------------------------------------------
it is said that if you line up all the cars in the world end to end 
someone would be stupid enough and try to pass all of them
dr seuss pronounced seuss such that it rhymed with rejoice
al capone business card said he was a used furniture dealer
'''

... and here would be a typical use ...

# experiments with string processing
# preprocess the string and do a word frequency count

from string import punctuation
from collections import Counter

# sample text for testing (could come from a text file)
text = """\
A giraffe can clean its ears with its tongue.
A giraffe's heart beats 50 times a minute.
A dog's heart beats 100 times a minute.
A hedgehog's heart beats 300 times a minute.
""" 

# since giraffe's would turn into giraffes, optionally remove 's
text2 = text.replace("'s", "")

# remove punctuation marks and change to lower case    
text3 = ''.join(c for c in text2.lower() if c not in punctuation)

# get word and frequency of the words in text3
# text3.split() splits text3 at white spaces
# most_common() gives a list of all (word, freq) tuples sorted by count
# most_common(10) will return a list of the 10 most common words
mc_cnt = Counter(text3.split()).most_common(10)

for word, freq in mc_cnt:
    print("%3d  %s" % (freq, word))

''' result (10 most common words) ...
  7  a
  3  heart
  3  times
  3  beats
  3  minute
  2  giraffe
  2  its
  1  300
  1  dog
  1  50
'''

The word frequency count came up on the forum.

0

In Python defined functions are objects, so you can combine them ...

def combine_two(f1, f2):
    """combines two functions f1 and f2"""
    return lambda *a: f1(f2(*a))

def reverse(str1):
    """reverse string str1"""
    return str1[::-1]

def uppercase(str1):
    """convert string str1 to all upper case"""
    return str1.upper()

# combine functions reverse, uppercase
rev_up = combine_two(reverse, uppercase)

print(rev_up('!dlrow olleh'))  # HELLO WORLD!

You can nest functions within functions without the use of lambda ...

# similar to the addition function used in Haskell
# this function returns a function local to it

def add(x):
    def inc(y):
        return x + y
    return inc

# create a new function on the fly ...
increment_by_one = add(1)
print(increment_by_one)     # <function inc at 0x009D6770>
print(increment_by_one(7))  # 8
print(increment_by_one(9))  # 10

# add can be used to generally add 2 numbers
print(add(11)(77))  # 88

# a little more Lisp-looking
print(add(add(11)(77))(12))  # 100

# readability does suffer if you keep going
print(add(add(add(11)(77))(12))(55))  # 155

Edited by vegaseat: nest

1

Python comes with a lot of highly tested and optimized modules. Knowing what they can do will help greatly to simplify code ...

# a simple character count using collections.defaultdict() 

from collections import defaultdict

s = 'mississippi'
dd = defaultdict(int)
for k in s:
    dd[k] += 1

print(dd)
print(dd.items())
print('-'*40)

# sorted by character alphabetically
for c, freq in sorted(dd.items()):
    #print("%s  %d" % (c, freq))
    # Python27 or Python3
    print("{}  {}".format(c, freq))

''' result ...
defaultdict(<type 'int'>, {'i': 4, 'p': 2, 's': 4, 'm': 1})
[('i', 4), ('p', 2), ('s', 4), ('m', 1)]
----------------------------------------
i  4
m  1
p  2
s  4
'''

print('-'*40)

# same thing but sorted by frequency
for c, freq in sorted(dd.items(), key=lambda q: q[1]):
    #print("%s  %d" % (c, freq))
    # Python27 or Python3
    print("{}  {}".format(c, freq))

''' result ...
m  1
p  2
i  4
s  4
'''

Another approach ...

# a simple character count using collections.Counter()
# needs Python27 or Python3 

from collections import Counter

s = 'mississippi'
cnt = Counter(s)

print(cnt)
print(cnt.items())
print('-'*40)

for c, freq in sorted(cnt.items()):
    #print("%s  %d" % (c, freq))   # older C style
    print("{}  {}".format(c, freq))

''' result ...
Counter({'i': 4, 's': 4, 'p': 2, 'm': 1})
[('i', 4), ('p', 2), ('s', 4), ('m', 1)]
----------------------------------------
i  4
m  1
p  2
s  4
'''

Edited by vegaseat: sort

Votes + Comments
helpful
2

A hint on how to access information from a nested Python dictionary ...

# accessing information from a nested dictionary

# example of a nested dictionary
friends = {
'Fred' : {'city' : 'Pasadena', 'age' : 45},
'Adam' : {'city' : 'Dallas', 'age' : 27},
'Lisa' : {'city' : 'Chicago', 'age' : 31},
'Ulla' : {'city' : 'Las Vegas', 'age' : 19},
'Mark' : {'city' : 'New York', 'age' : 24}
}

# dictionaries consist of key:value pairs
# and are indexed by the keys
# so if you want to know where Ulla lives
# you use the keys 'Ulla' and 'city'
print(friends['Ulla']['city'])       # Las Vegas

# how old is Adam ...
print(friends['Adam']['age'])        # 27

# or loop through all your friends
for friend in friends:
    print("%s lives in %s" % (friend, friends[friend]['city']))

''' result ...
Lisa lives in Chicago
Ulla lives in Las Vegas
Mark lives in New York
Adam lives in Dallas
Fred lives in Pasadena
'''
0

Well how about getting each details out.
friends = {
'Fred' : {'city' : 'Pasadena', 'age' : 45},
'Adam' : {'city' : 'Dallas', 'age' : 27},
'Lisa' : {'city' : 'Chicago', 'age' : 31},
'Ulla' : {'city' : 'Las Vegas', 'age' : 19},
'Mark' : {'city' : 'New York', 'age' : 24}
}

print "Name %20s %5s"%("City","Age")  
print "="*38
for x in sorted(friends):
	print "%s  Details are %s "%(x, [ y for y in friends[x].values()])  

----output--------
Name                 City   Age
======================================
Adam  Details are ['Dallas', 27] 
Fred  Details are ['Pasadena', 45] 
Lisa  Details are ['Chicago', 31] 
Mark  Details are ['New York', 24] 
Ulla  Details are ['Las Vegas', 19]

from my htc phone

Edited by richieking: n/a

0

I would prefer this:

friends = {
'Fred' : {'city' : 'Pasadena', 'age' : 45},
'Adam' : {'city' : 'Dallas', 'age' : 27},
'Lisa' : {'city' : 'Chicago', 'age' : 31},
'Ulla' : {'city' : 'Las Vegas', 'age' : 19},
'Mark' : {'city' : 'New York', 'age' : 24}
}
for x in sorted(friends):
    print("Friend {name:>6}  is living in {friend[city]:>10} and is now {friend[age]:3} years old.".format(
                 friend=friends[x], name = x))

Output:

Friend   Adam  is living in     Dallas and is now  27 years old.
Friend   Fred  is living in   Pasadena and is now  45 years old.
Friend   Lisa  is living in    Chicago and is now  31 years old.
Friend   Mark  is living in   New York and is now  24 years old.
Friend   Ulla  is living in  Las Vegas and is now  19 years old.

Works even with Python 2.6.6

Edited by pyTony: n/a

3

Now to something less nit-picky:

# create an accumulator decorator using a class

class Accum(object):
    """
    a decorator class that shows the number
    of times a decorated function is called
    """
    def __init__(self, func):
        self.calls = 0
        self.func = func

    def __call__(self, *args, **kwargs):
        self.calls += 1
        print( 'call %s to %s' % (self.calls, self.func.__name__) )
        # now run the decorated function ...
        self.func(*args, **kwargs)


# implement the decorator for function funcx this way
@Accum
def funcx(a, b, c):
    print( a, b, c )

funcx(11, 12, 13)
funcx('fat', 'bat', 'cat')

"""my result with Python32 -->
call 1 to funcx
11 12 13
call 2 to funcx
fat bat cat
"""
Votes + Comments
sweet code, thanks
great to know
thanks
0

The ordered dictionary container maintains a doubly-linked list of keys, appending new keys to the list as they're inserted. A secondary dictionary maps keys to their corresponding list node, so deletion doesn't have to traverse the entire linked list:

# new in Python 2.7 and Python3

from collections import OrderedDict

d = dict((chr(64+x), x) for x in range(1, 6))
print("a regular dictionary has keys in hash order:")
print(d)
od = OrderedDict((chr(64+x), x) for x in range(1, 6))
print("an ordered dictionary has keys in creation order:")
print(od)

"""my output -->
a regular dictionary has keys in hash order:
{'A': 1, 'C': 3, 'B': 2, 'E': 5, 'D': 4}
an ordered dictionary has keys in creation order:
OrderedDict([('A', 1), ('B', 2), ('C', 3), ('D', 4), ('E', 5)])
"""

# an ordered dictionary can be used similar to a regular dictionary
print("od.items() = %s" % od.items())
print("od.keys() = %s" % od.keys())
print("od.values() = %s" % od.values())
print("value of key 'D' = %s" % od['D'])
# change vlaue at key 'D'
od['D'] = 99
print("changed value of key 'D' = %s" % od['D'])

"""my output -->
od.items() = [('A', 1), ('B', 2), ('C', 3), ('D', 4), ('E', 5)]
od.keys() = ['A', 'B', 'C', 'D', 'E']
od.values() = [1, 2, 3, 4, 5]
value of key 'D' = 4
changed value of key 'D' = 99
"""

Edited by HiHe: spelling

1

Explore what you can do with function memoryview()

# testing memoryview()
# Python 2.7

mv = memoryview('abcdefg')

print(mv)  # <memory at 0x01DB4E40>

print(len(mv))  # 7
# item at index 1
print(mv[1])  # b
# show bytes in mv
print(mv.tobytes())  # abcdefg
# show ordinals
print(mv.tolist())  # [97, 98, 99, 100, 101, 102, 103]

Edited by HiHe: replaced accidental duplicate

Votes + Comments
interesting
0

A look at the new Python module fractions (new with Python27 and Python3):

# Python27 can calculate with fractions
# this avoids the inaccuracies associated with floating point numbers

from fractions import Fraction
import math

# Fraction(numerator, denominator)
# fraction 2/3 would be Fraction(2, 3)
a = Fraction(2, 3)
# fraction 2/5 would be Fraction(2, 5)
b = Fraction(2, 5)

# calculate with fractions
# for instance (2/3) + (2/5) --> 16/15
addition = a + b
print(addition)   # 16/15

# fraction has its own type
print(type(addition))  # <class 'fractions.Fraction'>

# obtain a fraction close to pi
pi_s = str(math.pi)
lim = 1000
pi_f = Fraction(pi_s).limit_denominator(lim)
print(pi_f)    # 355/113
0

Exploring strings with Python:

# using function zip() with strings

a = 'abcdef'
b = 'ghijklmnopq'

# only goes the length of the shortest string
print(list(zip(a, b)))

""" my output -->
[('a', 'g'), ('b', 'h'), ('c', 'i'), ('d', 'j'), ('e', 'k'), ('f', 'l')]
"""
0

A look at the new Python module fractions (new with Python27 and

Just to fix the data, from 2.7.1 documentation:

9.5. fractions — Rational numbers
New in version 2.6.

Edited by pyTony: n/a

1

A trick to create a lot of sequential variable names:

# use the Python local dictionary to create
# variables qq1 to qq7 and initializes them to 99

for n in range(1, 8):
    # create the variable name
    # for instance "qq" + "3" gives "qq3"
    var_name = "qq" + str(n)
    # give it the value 99
    locals()[var_name] = 99

# testing
print(qq1)
print(qq3)

print('-'*9)

for k, v in sorted(locals().items()):
    if 'qq' in k:
        print("%s = %s" % (k, v))

""" my output -->
99
99
---------
qq1 = 99
qq2 = 99
qq3 = 99
qq4 = 99
qq5 = 99
qq6 = 99
qq7 = 99
"""
Votes + Comments
Why wouldn't you use your own dictionary?
1

A trick to create a lot of sequential variable names:

Trick -> alarm bells

Tricks are generally frowned in Python circles. It is difficult to find good place for many variables for which we have to know names to use them, instead of using sequential data structure like list or tuple.

Votes + Comments
Too true.
This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.