Skip to main content

Functions and Modules | Core Python 3.8

Functions 

In the “Numbers and Expressions” section, I used the exponentiation operator (**) to calculate powers. The fact is that you can use a function instead, called pow.

>>> 2 ** 3 

>>> pow(2, 3) 

8

A function is like a little program that you can use to perform a specific action. Python has a lot of functions that can do many wonderful things. In fact, you can make your own functions, too (more about that later); therefore, we often refer to standard functions such as pow as built-in functions.
    Using a function as I did in the preceding example is called calling the function. You supply it with arguments (in this case, 2 and 3), and it returns a value to you. Because it returns a value, a function call is simply another type of expression, like the arithmetic expressions discussed earlier in this chapter.6 In fact, you can combine function calls and operators to create more complicated expressions (like I did with int, earlier).
    Function calls can also be used as statements if you simply ignore the return value.

>>> 10 + pow(2, 3 * 5) / 3.0 

10932.666666666666

Several built-in functions can be used in numeric expressions like this. For example, abs gives the absolute value of a number, and round rounds floating-point numbers to the nearest integer.

>>> abs(-10) 

10 

>>> 2 // 3 

>>> round(2 / 3) 

1.0

Notice the difference between the two last expressions. Integer division always rounds down, whereas round rounds to the nearest integer, with ties rounded toward the even number. But what if you want to round a given number down? For example, you might know that a person is 32.9 years old, but you would like to round that down to 32 because she isn’t really 33 yet. Python has a function for this (called floor)—it just isn’t available directly. As is the case with many useful functions, it is found in a module.

Modules 

You may think of modules as extensions that can be imported into Python to expand its capabilities. You import modules with a special command called (naturally enough) import. The function mentioned in the previous section, floor, is in a module called math.

>>> import math 

>>> math.floor(32.9) 

32

Notice how this works: we import a module with import and then use the functions from that module by writing module.function. For this operation in particular, you could actually just convert the number into an integer, like I did earlier, with the results from input.

>>> int(32.9) 

32

 ■ Note  similar functions exist to convert to other types (for example, str and float). In fact, these aren’t really functions—they’re classes. I’ll have more to say about classes later.
The math module has several other useful functions, though. For example, the opposite of floor is ceil (short for “ceiling”), which finds the smallest integral value larger than or equal to the given number.

>>> math.ceil(32.3) 

33 

>>> math.ceil(32) 

32


If you are sure that you won’t import more than one function with a given name (from different modules), you might not want to write the module name each time you call the function. Then you can use a variant of the import command.

>>> from math import sqrt 

>>> sqrt(9) 

3.0

After using the from module import function, you can use the function without its module prefix.
 ■ Tip  You may, in fact, use variables to refer to functions (and most other things in python). By performing the assignment foo = math.sqrt, you can start using foo to calculate square roots; for example, foo(4) yields 2.0.
cmath and Complex Numbers The sqrt function is used to calculate the square root of a number. Let’s see what happens if we supply it with a negative number:

>>> from math import sqrt 

>>> sqrt(-1) 

Traceback (most recent call last):     

... 

ValueError: math domain error

or, on some platforms:

>>> sqrt(-1) 

nan

 ■ Note  nan is simply a special value meaning “not a number.”
If we restrict ourselves to real numbers and their approximate implementation in the form of floats, we can’t take the square root of a negative number. The square root of a negative number is a so-called imaginary number, and numbers that are the sum of a real and an imaginary part are called complex. The Python standard library has a separate module for dealing with complex numbers.

>>> import cmath 

>>> cmath.sqrt(-1) 

1j

Notice that I didn’t use from ... import ... here. If I had, I would have lost my ordinary sqrt. Name clashes like these can be sneaky, so unless you really want to use the from version, you should probably stick with a plain import. The value 1j is an example of an imaginary number. These numbers are written with a trailing j (or J). Complex arithmetic essentially follows from defining 1j as the square root of -1. Without delving too deeply into the topic, let me just show a final example:

>>> (1 + 3j) * (9 + 4j) 

(-3 + 31j)

As you can see, the support for complex numbers is built into the language.

 ■ Note  there is no separate type for imaginary numbers in python. they are treated as complex numbers whose real component is zero.

Back to the __future__ 

It has been rumored that Guido van Rossum (Python’s creator) has a time machine—on more than one occasion when people have requested features in the language, they have found that the features were already implemented. Of course, we aren’t all allowed into this time machine, but Guido has been kind enough to build a part of it into Python, in the form of the magic module __future__. From it, we can import features that will be standard in Python in the future but that aren’t part of the language yet

Comments

Popular posts from this blog

Strings | Core Python 3.8

Strings  Now what was all that "Hello, " + name + "!" stuff about? The first program in this chapter was simply print("Hello, world!") It is customary to begin with a program like this in programming tutorials. The problem is that I haven’t really explained how it works yet. You know the basics of the print statement (I’ll have more to say about that later), but what is "Hello, world!"? It’s called a string (as in “a string of characters”). Strings are found in almost every useful, real-world Python program and have many uses. Their main use is to represent bits of text, such as the exclamation “Hello, world!” Single-Quoted Strings and Escaping Quotes Strings are values, just as numbers are: >>> "Hello, world!"  'Hello, world!' There is one thing that may be a bit surprising about this example, though: when Python printed out our string, it used single quotes, whereas we used double quotes. What’s the differ...

Execution the Program | Core Python 3.8

Saving and Executing Your Programs  The interactive interpreter is one of Python’s great strengths. It makes it possible to test solutions and to experiment with the language in real time. If you want to know how something works, just try it! However, everything you write in the interactive interpreter is lost when you quit. What you really want to do is write programs that both you and other people can run. In this section, you learn how to do just that.     First of all, you need a text editor, preferably one intended for programming. (If you use something like Microsoft Word, which I really don’t really recommend, be sure to save your code as plain text.) If you are already using IDLE, you’re in luck. With IDLE, you can simply create a new editor window with File › New File. Another window appears, without an interactive prompt. Whew! Start by entering the following: print("Hello, world!") Now select File › Save to save your program (which is, in fact, a pl...

Lists and Tuples | Core Python 3.8

This chapter introduces a new concept: data structures. A data structure is a collection of data elements (such as numbers or characters, or even other data structures) that is structured in some way, such as by numbering the elements. The most basic data structure in Python is the sequence. Each element of a sequence is assigned a number—its position, or index. The first index is zero, the second index is one, and so forth. Some programming languages number their sequence elements starting with one, but the zeroindexing convention has a natural interpretation of an offset from the beginning of the sequence, with negative indexes wrapping around to the end. If you find the numbering a bit odd, I can assure you that you’ll most likely get used to it pretty fast.     This chapter begins with an overview of sequences and then covers some operations that are common to all sequences, including lists and tuples. These operations will also work with strings, which will be use...

Exceptions | Core Python 3.8

When writing computer programs, it is usually possible to discern between a normal course of events and something that’s exceptional (out of the ordinary). Such exceptional events might be errors (such as trying to divide a number by zero) or simply something you might not expect to happen very often. To handle such exceptional events, you might use conditionals everywhere the events might occur (for example, have your program check whether the denominator is zero for every division). However, this would not only be inefficient and inflexible but would also make the programs illegible. You might be tempted to ignore these exceptional events and just hope they won’t occur, but Python offers an exception-handling mechanism as a powerful alternative.     In this tutorial, you’ll learn how to create and raise your own exceptions, as well as how to handle exceptions in various ways. What Is an Exception?  To represent exceptional conditions, Python uses exception obj...