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...

Variables and Statements | Core Python 3.8

Variables  Another concept that might be familiar to you is variables. If algebra is but a distant memory, don’t worry: variables in Python are easy to understand. A variable is a name that represents (or refers to) some value. For example, you might want the name x to represent 3. To make it so, simply execute the following: >>> x = 3 This is called an assignment. We assign the value 3 to the variable x. Another way of putting this is to say that we bind the variable x to the value (or object) 3. After you’ve assigned a value to a variable, you can use the variable in expressions. >>> x * 2  6 Unlike some other languages, you can’t use a variable before you bind it to something. There is no “default value.” ■ Note  the simple story is that names, or identifiers, in python consist of letters, digits, and underscore characters (_). they can’t begin with a digit, so Plan9 is a valid variable name, whereas Plan is not. Statements  Until...

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...

Dictionaries: When Indices Won’t Do | Core Python 3.8

You’ve seen that lists are useful when you want to group values into a structure and refer to each value by number. In this chapter, you learn about a data structure in which you can refer to each value by name. This type of structure is called a mapping. The only built-in mapping type in Python is the dictionary. The values in a dictionary don’t have any particular order but are stored under a key, which may be a number, a string, or even a tuple. Dictionary Uses The name dictionary should give you a clue about the purpose of this structure. An ordinary book is made for reading from start to finish. If you like, you can quickly open it to any given page. This is a bit like a Python list. On the other hand, dictionaries—both real ones and their Python equivalent—are constructed so that you can look up a specific word (key) easily to find its definition (value).     A dictionary is more appropriate than a list in many situations. Here are some examples of uses of Pyth...

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...