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" # make a str variable
print("Hello there!")
print(f"Hello {var}") # using f-string we can lookup a variable and insert it!
print("Hello", var, "bars") # print comma separated objects
print("Hello", 1, 2, 3, 4, True, 3.14) # we can print ANY type of python object!
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. There are some cases we can use primarily with strings and the print function.
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.
The len() function returns the number of items in a sequence (string, list, tuple, etc.).
# Example 1: len()
names = ["Ravi", "Meera", "Ajay"]
print(len(names))
# Output: 3
text = "Python"
print(len(text))
# Output: 6
max() returns the largest item in an iterable or the largest of two or more arguments.
# Example 2: max()
numbers = [10, 25, 17]
print(max(numbers))
# Output: 25
print(max("apple", "banana", "cherry"))
# Output: cherry
min() returns the smallest item in an iterable or the smallest of two or more arguments.
# Example 3: min()
values = [3, 8, 1, 9]
print(min(values))
# Output: 1
print(min("zebra", "elephant", "dog"))
# Output: dog
sum() adds all the items in an iterable. It only works with numeric data.
# Example 4: sum()
prices = [100, 200, 300]
print(sum(prices))
# Output: 600
# With a starting value
print(sum(prices, 50))
# Output: 650
sorted() returns a new sorted list from the items of any iterable. The original data remains unchanged.
# Example 5: sorted()
scores = [88, 45, 67, 99]
print(sorted(scores))
# Output: [45, 67, 88, 99]
print(sorted(scores, reverse=True))
# Output: [99, 88, 67, 45]
# When used with a str
print(sorted("Super"))
# Output: ['S', 'e', 'p', 'r', 'u']
enumerate() adds a counter to an iterable and returns it as an enumerate object (which you can loop over).
# Example 6: enumerate()
colors = ["Red", "Green", "Blue"]
for index, color in enumerate(colors):
print(index, color)
# Output:
# 0 Red
# 1 Green
# 2 Blue
If we wanted to start counting from 1 instead of zero, we can use the start parameter.
a = ["apple", "banana", "cherry"]
for index, value in enumerate(a, start=1):
print(f"{index}: {value}")
# Output:
1: apple
2: banana
3: cherry
zip() combines two or more iterables element-wise into tuples. It stops when the shortest iterable is exhausted.
# Example 7: zip()
names = ["Amit", "Reena", "Karan"]
marks = [85, 90, 75]
for name, mark in zip(names, marks):
print(f"{name} scored {mark}")
# Output:
# Amit scored 85
# Reena scored 90
# Karan scored 75
You can combine several of these functions for practical use.
# Example 8: Combine zip, sorted, enumerate
students = ["Neha", "Raj", "Simran"]
grades = [88, 74, 93]
# Sort students by grades in descending order
for i, (name, grade) in enumerate(sorted(zip(students, grades), key=lambda x: x[1], reverse=True), start=1):
print(f"{i}. {name}: {grade}")
# Output:
# 1. Simran: 93
# 2. Neha: 88
# 3. Raj: 74
These built-in functions—len(), max(), min(), sum(), sorted(), enumerate(), and zip()—are the foundation for writing efficient and elegant Python code. They help reduce complexity, improve performance, and keep your code clean. As you get more comfortable with Python, you’ll find yourself using them regularly across all kinds of projects.