Skip to Main Content
Learning Python
book

Learning Python

by Mark Lutz, David Ascher
April 1999
Beginner content levelBeginner
384 pages
11h 15m
English
O'Reilly Media, Inc.
Content preview from Learning Python
  1. Basics.

    % python
    >>> def func(x): print x
    ...
    >>> func("spam")
    spam
    >>> func(42)
    42
    >>> func([1, 2, 3])
    [1, 2, 3]
    >>> func({'food': 'spam'})
    {'food': 'spam'}
  2. Arguments. Here’s what one solution looks like. You have to use print to see results in the test calls, because a file isn’t the same as code typed interactively; Python doesn’t echo the results of expression statements.

    % cat mod.py
    def adder(x, y):
        return x + y
    
    print adder(2, 3)
    print adder('spam', 'eggs')
    print adder(['a', 'b'], ['c', 'd'])
    
    % python mod.py
    5
    spameggs
    ['a', 'b', 'c', 'd']
  3. varargs. Two alternative adder functions are shown in the following code. The hard part here is figuring out how to initialize an accumulator to an empty value of whatever type is passed in. In the first solution, we use manual type testing to look for an integer and an empty slice of the first argument (assumed to be a sequence) otherwise. In the second solution, we just use the first argument to initialize and scan items 2 and beyond. The second solution is better (and frankly, comes from students in a Python course, who were frustrated with trying to understand the first solution). Both of these assume all arguments are the same type and neither works on dictionaries; as we saw in Chapter 2, + doesn’t work on mixed types or dictionaries. We could add a type test and special code to add dictionaries too, but that’s extra credit.

    % cat adders.py def adder1(*args): print 'adder1', if type(args[0]) == type(0): # integer? sum = 0 ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Learning Python

Learning Python

Fabrizio Romano
Getting Started with Python

Getting Started with Python

Fabrizio Romano, Benjamin Baka, Dusty Phillips

Publisher Resources

ISBN: 1565924649Supplemental ContentCatalog PageErrata