0% found this document useful (0 votes)
20 views10 pages

Help

Uploaded by

prsi007
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
20 views10 pages

Help

Uploaded by

prsi007
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 10

help> print ①

Help on built-in function print in module builtins:

print(...)

print(value, ..., sep=' ', end='\n', file=sys.stdout)

Prints the values to a stream, or to sys.stdout by default.

Optional keyword arguments:

file: a file-like object (stream); defaults to the current sys.stdout.

sep: string inserted between values, default a space.

end: string appended after the last value, default a newline.

help> PapayaWhip ②
no Python documentation found for 'PapayaWhip'

help> quit ③

You are now leaving help and returning to the Python interpreter.

If you want to ask for help on a particular object directly from the

interpreter, you can type "help(object)". Executing "help('string')"

has the same effect as typing a particular string at the help> prompt.

>>> ④

1. To get documentation on the print() function, just type print and press ENTER. The interactive help mode
will display something akin to a man page: the function name, a brief synopsis, the function’s arguments and
their default values, and so on. If the documentation seems opaque to you, don’t panic. You’ll learn more
about all these concepts in the next few chapters.
2. Of course, the interactive help mode doesn’t know everything. If you type something that isn’t a Python
command, module, function, or other built-in keyword, the interactive help mode will just shrug its virtual
shoulders.
3. To quit the interactive help mode, type quit and press ENTER.
4. The prompt changes back to >>> to signal that you’ve left the interactive help mode and returned to the
Python Shell.

31
IDLE, the graphical Python Shell, also includes a Python-aware text editor.

0.8. PYTHON EDITORS AND IDES

IDLE is not the only game in town when it comes to writing programs in Python. While it’s useful to get
started with learning the language itself, many developers prefer other text editors or Integrated
Development Environments (I D E s). I won’t cover them here, but the Python community maintains a list of
Python-aware editors that covers a wide range of supported platforms and software licenses.

You might also want to check out the list of Python-aware I D E s, although few of them support Python 3 yet.
One that does is PyDev, a plugin for Eclipse that turns Eclipse into a full-fledged Python IDE. Both Eclipse
and PyDev are cross-platform and open source.

On the commercial front, there is ActiveState’s Komodo IDE. It has per-user licensing, but students can get
a discount, and a free time-limited trial version is available.

I’ve been programming in Python for nine years, and I edit my Python programs in GNU Emacs and debug
them in the command-line Python Shell. There’s no right or wrong way to develop in Python. Find a way
that works for you!

32
CHAPTER 1. YOUR FIRST PYTHON PROGRAM

❝ Don’t bury your burden in saintly silence. You have a problem? Great. Rejoice, dive in, and investigate. ❞
— Ven. Henepola Gunaratana

1.1. DIVING IN

C onvention dictates that I should bore you with the fundamental building blocks of programming, so we
can slowly work up to building something useful. Let’s skip all that. Here is a complete, working Python
program. It probably makes absolutely no sense to you. Don’t worry about that, because you’re going to
dissect it line by line. But read through it first and see what, if anything, you can make of it.

33
SUFFIXES = {1000: ['KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'],

1024: ['KiB', 'MiB', 'GiB', 'TiB', 'PiB', 'EiB', 'ZiB', 'YiB']}

def approximate_size(size, a_kilobyte_is_1024_bytes=True):

'''Convert a file size to human-readable form.

Keyword arguments:

size -- file size in bytes

a_kilobyte_is_1024_bytes -- if True (default), use multiples of 1024

if False, use multiples of 1000

Returns: string

'''

if size < 0:

raise ValueError('number must be non-negative')

multiple = 1024 if a_kilobyte_is_1024_bytes else 1000

for suffix in SUFFIXES[multiple]:

size /= multiple

if size < multiple:

return '{0:.1f} {1}'.format(size, suffix)

raise ValueError('number too large')

if __name__ == '__main__':

print(approximate_size(1000000000000, False))

print(approximate_size(1000000000000))

Now let’s run this program on the command line. On Windows, it will look something like this:

c:\home\diveintopython3\examples> c:\python31\python.exe humansize.py

1.0 TB

931.3 GiB

34
On Mac OS X or Linux, it would look something like this:

you@localhost:~/diveintopython3/examples$ python3 humansize.py

1.0 TB

931.3 GiB

What just happened? You executed your first Python program. You called the Python interpreter on the
command line, and you passed the name of the script you wanted Python to execute. The script defines a
single function, the approximate_size() function, which takes an exact file size in bytes and calculates a
“pretty” (but approximate) size. (You’ve probably seen this in Windows Explorer, or the Mac OS X Finder,
or Nautilus or Dolphin or Thunar on Linux. If you display a folder of documents as a multi-column list, it
will display a table with the document icon, the document name, the size, type, last-modified date, and so on.
If the folder contains a 1093-byte file named TODO, your file manager won’t display TODO 1093 bytes; it’ll say
something like TODO 1 KB instead. That’s what the approximate_size() function does.)

Look at the bottom of the script, and you’ll see two calls to print(approximate_size(arguments)). These
are function calls — first calling the approximate_size() function and passing a number of arguments, then
taking the return value and passing it straight on to the print() function. The print() function is built-in;
you’ll never see an explicit declaration of it. You can just use it, anytime, anywhere. (There are lots of built-
in functions, and lots more functions that are separated into modules. Patience, grasshopper.)

So why does running the script on the command line give you the same output every time? We’ll get to
that. First, let’s look at that approximate_size() function.

1.2. DECLARING FUNCTIONS

Python has functions like most other languages, but it does not have separate header files like C++ or
interface/implementation sections like Pascal. When you need a function, just declare it, like this:

def approximate_size(size, a_kilobyte_is_1024_bytes=True):

35
The keyword def starts the function declaration,
followed by the function name, followed by the
arguments in parentheses. Multiple arguments are
separated with commas.

Also note that the function doesn’t define a return When you
datatype. Python functions do not specify the datatype
of their return value; they don’t even specify whether or need a
not they return a value. (In fact, every Python function
returns a value; if the function ever executes a return function,
statement, it will return that value, otherwise it will
return None, the Python null value.) just declare
it.
☞ In some languages, functions (that return a
value) start with function, and subroutines
(that do not return a value) start with sub.
There are no subroutines in Python. Everything is a function, all functions return a
value (even if it’s None), and all functions start with def.

The approximate_size() function takes the two arguments — size and


a_kilobyte_is_1024_bytes — but neither argument specifies a datatype. In Python, variables are never
explicitly typed. Python figures out what type a variable is and keeps track of it internally.

☞ In Java and other statically-typed languages, you must specify the datatype of the
function return value and each function argument. In Python, you never explicitly
specify the datatype of anything. Based on what value you assign, Python keeps track
of the datatype internally.

36
1.2.1. OPTIONAL AND NAMED ARGUMENTS

Python allows function arguments to have default values; if the function is called without the argument, the
argument gets its default value. Furthermore, arguments can be specified in any order by using named
arguments.

Let’s take another look at that approximate_size() function declaration:

def approximate_size(size, a_kilobyte_is_1024_bytes=True):

The second argument, a_kilobyte_is_1024_bytes, specifies a default value of True. This means the
argument is optional; you can call the function without it, and Python will act as if you had called it with True
as a second parameter.

Now look at the bottom of the script:

if __name__ == '__main__':

print(approximate_size(1000000000000, False)) ①
print(approximate_size(1000000000000)) ②

1. This calls the approximate_size() function with two arguments. Within the approximate_size() function,
a_kilobyte_is_1024_bytes will be False, since you explicitly passed False as the second argument.
2. This calls the approximate_size() function with only one argument. But that’s OK, because the second
argument is optional! Since the caller doesn’t specify, the second argument defaults to True, as defined by
the function declaration.

You can also pass values into a function by name.

37
>>> from humansize import approximate_size

>>> approximate_size(4000, a_kilobyte_is_1024_bytes=False) ①


'4.0 KB'

>>> approximate_size(size=4000, a_kilobyte_is_1024_bytes=False) ②


'4.0 KB'

>>> approximate_size(a_kilobyte_is_1024_bytes=False, size=4000) ③


'4.0 KB'

>>> approximate_size(a_kilobyte_is_1024_bytes=False, 4000) ④


File "<stdin>", line 1

SyntaxError: non-keyword arg after keyword arg

>>> approximate_size(size=4000, False) ⑤


File "<stdin>", line 1

SyntaxError: non-keyword arg after keyword arg

1. This calls the approximate_size() function with 4000 for the first argument (size) and False for the
argument named a_kilobyte_is_1024_bytes. (That happens to be the second argument, but doesn’t
matter, as you’ll see in a minute.)
2. This calls the approximate_size() function with 4000 for the argument named size and False for the
argument named a_kilobyte_is_1024_bytes. (These named arguments happen to be in the same order as
the arguments are listed in the function declaration, but that doesn’t matter either.)
3. This calls the approximate_size() function with False for the argument named
a_kilobyte_is_1024_bytes and 4000 for the argument named size. (See? I told you the order didn’t
matter.)
4. This call fails, because you have a named argument followed by an unnamed (positional) argument, and that
never works. Reading the argument list from left to right, once you have a single named argument, the rest
of the arguments must also be named.
5. This call fails too, for the same reason as the previous call. Is that surprising? After all, you passed 4000 for
the argument named size, then “obviously” that False value was meant for the
a_kilobyte_is_1024_bytes argument. But Python doesn’t work that way. As soon as you have a named
argument, all arguments to the right of that need to be named arguments, too.

38
1.3. WRITING READABLE CODE

I won’t bore you with a long finger-wagging speech about the importance of documenting your code. Just
know that code is written once but read many times, and the most important audience for your code is
yourself, six months after writing it (i.e. after you’ve forgotten everything but need to fix something). Python
makes it easy to write readable code, so take advantage of it. You’ll thank me in six months.

1.3.1. DOCUMENTATION STRINGS

You can document a Python function by giving it a documentation string (docstring for short). In this
program, the approximate_size() function has a docstring:

def approximate_size(size, a_kilobyte_is_1024_bytes=True):

'''Convert a file size to human-readable form.

Keyword arguments:

size -- file size in bytes

a_kilobyte_is_1024_bytes -- if True (default), use multiples of 1024

if False, use multiples of 1000

Returns: string

'''

Triple quotes signify a multi-line string. Everything


between the start and end quotes is part of a single
string, including carriage returns, leading white space,
and other quote characters. You can use them
anywhere, but you’ll see them most often used when Every
defining a docstring.

function

39
Triple quotes are also an easy way to define
a string with both single and double quotes,
like qq/.../ in Perl 5.

Everything between the triple quotes is the function’s deserves a


docstring, which documents what the function does. A
docstring, if it exists, must be the first thing defined in decent
a function (that is, on the next line after the function
declaration). You don’t technically need to give your docstring.
function a docstring, but you always should. I know
you’ve heard this in every programming class you’ve
ever taken, but Python gives you an added incentive: the
docstring is available at runtime as an attribute of the function.

☞ Many Python IDEs use the docstring to provide context-sensitive documentation, so


that when you type a function name, its docstring appears as a tooltip. This can be
incredibly helpful, but it’s only as good as the docstrings you write.

1.4. THE import SEARCH PATH

Before this goes any further, I want to briefly mention the library search path. Python looks in several places
when you try to import a module. Specifically, it looks in all the directories defined in sys.path. This is just
a list, and you can easily view it or modify it with standard list methods. (You’ll learn more about lists in
Native Datatypes.)

40

You might also like