If you have ever used Excel, you have seen functions. Functions in Python are similar, and even have similar names (such as max and min for example) with one very small but important difference- Python is case sensitive. Case matters. Python comes with a number of builtin functions- this means there are a lot of functions built and "ready to go" without having to import them from other modules.
builtin functions- we will likely use about twenty something of those shown here.
We will write our own functions later, but some of the most common functions you will use in Python are the input and print functions. You may also find the help function useful!
An important aspect of functions is that they "take" something (sometimes not, but for the most part they do) and they return something – ALWAYS. The way we describe this is called a type contract. The type contract specifies what (if anything) the function takes – aka the arguments, and what it returns.
The help function in Python is similar to the help in an application you might use. At the python interpreter ( the three chevrons >>> ) you pass an argument to the help function and it returns back some information on that "thing" you passed in. Just passing in the following will have the function return a load on information on what an int is.
>>> help(int)
Help on class int in module builtins:
class int(object)
| int([x]) -> integer
| int(x, base=10) -> integer
|
| Convert a number or string to an integer, or return 0 if no arguments
| are given. If x is a number, return x.__int__(). For floating point
| numbers, this truncates towards zero.
|
| If x is not a number or if base is given, then x must be a string,
| bytes, or bytearray instance representing an integer literal in the
| given base. The literal can be preceded by '+' or '-' and be surrounded
| by whitespace. The base defaults to 10. Valid bases are 0 and 2-36.
| Base 0 means to interpret the base from the string as an integer literal.
| >>> int('0b100', base=0)
| 4
There is more information returned by the help function but you can check that yourself if you are interested. The main takeaway is that this functions takes something- a Python object – and returns a string called the docstring- the documentation string written – for that object.
It's type-contract is:
(obj) -> str
An object could be anything such as a data type, a function, a method or a module.
For the input function, the most important thing to remember is that it returns a string. It takes a prompt – usually a string.
We can use another builtin function to find some information on the input function.
>>> help(input)
Help on built-in function input in module builtins:
input(prompt=None, /)
Read a string from standard input. The trailing newline is stripped.
The prompt string, if given, is printed to standard output without a
trailing newline before reading input.
If the user hits EOF (*nix: Ctrl-D, Windows: Ctrl-Z+Return), raise EOFError.
On *nix systems, readline is used if available.
So, the input statement takes an optional value for prompt but the default is None. It returns a string.
It's type-contract is:
(obj) -> str
What this means is that inside the brackets it accepts an argument (usually a string but you can enter an int, float, bool, list or other object here) and it returns (denoted by the arrow ->) a string. It always returns a string.
Usually one of the first things people see in a language is the class print("Hello World!") and then we use the print function quite a lot without giving it much thought. We most often pass in a print string, but can also pass in other data types, a comma separated sequence of different objects like
var = "9"
print("Hello there!")
print(f"Hello {var}")
print("Hello", var, "bars")
print("Hello", 1, 2, 3, 4, True, 3.14)
All of these commands will work fine. Let's look at what the help function says about the print function.
>>> help(print)
Help on built-in function print in module builtins:
print(...)
print(value, ..., sep=' ', end='\n', file=sys.stdout, flush=False)
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.
flush: whether to forcibly flush the stream.
What this shows is that print can:
Take one or more values
Has an optional argument called sep – short for separator - which is a single space by default
Has an optional argument called end which is a 'next line' or \n character by default
This means we can do some more interesting things with the print statement, such as change the separator:
>>> print("Hello", "bars")
Hello bars
>>> print("Hello", "bars", sep='~')
Hello~bars
>>> print("Hello", "bars", sep='-!-')
Hello-!-bars
We can similarly change the end-of-line character from '\n' to something else.
>>> print("Hello", "bars", end='-!-')
Hello bars-!->>> print("Hello", "bars", end='~')
Hello bars~>>> print()
>>>
In the example you can see that there is no clear "next-line" after a print statement. The chevrons appear right after the previously printed line. We will use these later in the course, but for early programs we'll be keeping it fairly simple.
It's type-contract is then something like:
(obj:opt, str:opt, str:opt) -> None
So it takes optionally something(s) or object(s) to print, and two optional arguments which are strings- one for the separator and one for the end.
There is a lot more to the print function than you might think.
This returns the type or class of the object passed to it. You can run these at the prompt for the Python interpreter.
>>> type(32) -> <class int>
>>> type(3.14) -> <class float>
>>> type("hello") -> <class str>
>>> type(True) -> <class bool>
>>> type([1, 3.2, 'm']) -> <class list>
>>> type((5, 8)) -> <class tuple>
>>> type({1: "Ted", 2: "Mary"}) -> <class dict>
The arrow is shown here to indicate the result, or the value returned by the function.
It's type-contract is:
(obj) -> type
This checks the type or class of the object passed to it. You can run these at the prompt for the Python interpreter.
>>> isinstance(32, int) -> True
>>> isinstance(32, float) -> False
>>> isinstance(7.2, int) -> False
>>> isinstance(7.2, float) -> True
>>> isinstance("Hello", int) -> False
>>> isinstance("Hello", str) -> True
>>> isinstance(True, bool) -> True
We are asking if the first argument to the function is of the same type as the second arg. We can also use it to check if the object passed to the function is one of several types:
>>> isinstance(32, (float, int)) -> True
>>> isinstance("Hi", (float, str)) -> True
>>> isinstance(7.2, (bool, int, str)) -> False
It's type-contract is:
(obj, type) -> bool
It is possible to change the type of a variable, but it is important to note that python would:
make a copy of the original and change it's type- if possible
this would NOT mutate the original variable
the coder would have to explicitly over-write the original variable
e.g.
>>> x = "22"
>>> x
'22'
>>> int(x)
22
>>> x
'22'
>>> type(x)
<class str>
The variable x is STILL a string. To make the var into an int, it MUST be assigned to overwrite the var- conversion happens on the right, and is then assigned to the var on the left:
>>> x = int(x)
>>> type (x)
<class int>
Use the help function to find information on the following:
float
bin
hex
ord
chr
These are commonly used functions. You can run help on any or all of them in the interactive terminal below.