How many modes do we have in python?

Mode of a data set is/are the member(s) that occur(s) most frequently in the set. If there are two members that appear most often with same number of times, then the data has two modes. This is called bimodal.

If there are more than 2 modes, then the data would be called multimodal. If all the members in the data set appear the same number of times, then the data set has no mode at all.

Following function modes() can work to find mode(s) in a given list of data:

import numpy as np; import pandas as pd

def modes(arr):
    df = pd.DataFrame(arr, columns=['Values'])
    dat = pd.crosstab(df['Values'], columns=['Freq'])
    if len(np.unique((dat['Freq']))) > 1:
        mode = list(dat.index[np.array(dat['Freq'] == max(dat['Freq']))])
        return mode
    else:
        print("There is NO mode in the data set")

Output:

# For a list of numbers in x as
In [1]: x = [2, 3, 4, 5, 7, 9, 8, 12, 2, 1, 1, 1, 3, 3, 2, 6, 12, 3, 7, 8, 9, 7, 12, 10, 10, 11, 12, 2]
In [2]: modes(x)
Out[2]: [2, 3, 12]
# For a list of repeated numbers in y as
In [3]: y = [2, 2, 3, 3, 4, 4, 10, 10]
In [4]: modes(y)
Out[4]: There is NO mode in the data set
# For a list of strings/characters in z as
In [5]: z = ['a', 'b', 'b', 'b', 'e', 'e', 'e', 'd', 'g', 'g', 'c', 'g', 'g', 'a', 'a', 'c', 'a']
In [6]: modes(z)
Out[6]: ['a', 'g']

If we do not want to import numpy or pandas to call any function from these packages, then to get this same output, modes() function can be written as:

def modes(arr):
    cnt = []
    for i in arr:
        cnt.append(arr.count(i))
    uniq_cnt = []
    for i in cnt:
        if i not in uniq_cnt:
            uniq_cnt.append(i)
    if len(uniq_cnt) > 1:
        m = []
        for i in list(range(len(cnt))):
            if cnt[i] == max(uniq_cnt):
                m.append(arr[i])
        mode = []
        for i in m:
            if i not in mode:
                mode.append(i)
        return mode
    else:
        print("There is NO mode in the data set")

In Python, there are two options/methods for running code:

  • Interactive mode
  • Script mode

In this article, we will see the difference between the modes and will also discuss the pros and cons of running scripts in both of these modes.

Interactive Mode

Interactive mode, also known as the REPL provides us with a quick way of running blocks or a single line of Python code. The code executes via the Python shell, which comes with Python installation. Interactive mode is handy when you just want to execute basic Python commands or you are new to Python programming and just want to get your hands dirty with this beautiful language.

To access the Python shell, open the terminal of your operating system and then type "python". Press the enter key and the Python shell will appear. This is the same Python executable you use to execute scripts, which comes installed by default on Mac and Unix-based operating systems.

C:\Windows\system32>python
Python 3.5.0 (v3.5.0:374f501f4567, Sep 13 2015, 02:27:37) [MSC v.1900 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>>

The >>> indicates that the Python shell is ready to execute and send your commands to the Python interpreter. The result is immediately displayed on the Python shell as soon as the Python interpreter interprets the command.

To run your Python statements, just type them and hit the enter key. You will get the results immediately, unlike in script mode. For example, to print the text "Hello World", we can type the following:

>>> print("Hello World")
Hello World
>>>

Here are other examples:

>>> 10
10
>>> print(5 * 20)
100
>>> "hi" * 5
'hihihihihi'
>>>

We can also run multiple statements on the Python shell. A good example of this is when we need to declare many variables and access them later. This is demonstrated below:

>>> name = "Nicholas"
>>> age = 26
>>> course = "Computer Science"
>>> print("My name is " + name + ", aged " + str(age) + ", taking " + course)

Output

My name is Nicholas, aged 26, taking Computer Science

Using the method demonstrated above, you can run multiple Python statements without having to create and save a script. You can also copy your code from another source then paste it on the Python shell.

Consider the following example:

>>> if 5 > 10:
...     print("5 is greater than 10")
... else:
...     print("5 is less than 10")
...
5 is less than 10
>>>

The above example also demonstrates how we can run multiple Python statements in interactive mode. The two print statements have been indented using four spaces. Just like in script mode, if you don't indent properly you will get an error. Also, to get the output after the last print statement, you should press the enter key twice without typing anything.

Getting Help

You can also get help with regards to a particular command in interactive mode. Just type the help() command on the shell and then hit the enter key. You will see the following:

>>> help()

Welcome to Python 3.5's help utility!

If this is your first time using Python, you should definitely check out
the tutorial on the Internet at http://docs.python.org/3.5/tutorial/.

Enter the name of any module, keyword, or topic to get help on writing
Python programs and using Python modules.  To quit this help utility and
return to the interpreter, just type "quit".

To get a list of available modules, keywords, or topics, type "modules",
"keywords", or "topics".  Each module also comes with a one-line summary
of what it does; to list the modules whose summaries contain a given word
such as "spam", type "modules spam".

help>

Now to find the help for a particular command, simple type that command, for instance, to find help for the print command, simply type print and hit the enter key. The result will look like this:

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.

As shown in the above output, the help utility returned useful information regarding the print command including what the command does and what are some of the arguments that can be used with the command.

To exit help, type q for "quit" and then hit the enter key. You will be taken back to the Python shell.

Pros and Cons of Interactive Mode

The following are the advantages of running your code in interactive mode:

  1. Helpful when your script is extremely short and you want immediate results.
  2. Faster as you only have to type a command and then press the enter key to get the results.
  3. Good for beginners who need to understand Python basics.

The following are the disadvantages of running your code in the interactive mode:

Check out our hands-on, practical guide to learning Git, with best-practices, industry-accepted standards, and included cheat sheet. Stop Googling Git commands and actually learn it!

  1. Editing the code in interactive mode is hard as you have to move back to the previous commands or else you have to rewrite the whole command again.
  2. It's very tedious to run long pieces of code.

Next, we will be discussing the script mode.

Script Mode

If you need to write a long piece of Python code or your Python script spans multiple files, interactive mode is not recommended. Script mode is the way to go in such cases. In script mode, You write your code in a text file then save it with a .py extension which stands for "Python". Note that you can use any text editor for this, including Sublime, Atom, notepad++, etc.

If you are in the standard Python shell, you can click "File" then choose "New" or simply hit "Ctrl + N" on your keyboard to open a blank script in which you can write your code. You can then press "Ctrl + S" to save it.

After writing your code, you can run it by clicking "Run" then "Run Module" or simply press F5.

Let us create a new file from the Python shell and give it the name "hello.py". We need to run the "Hello World" program. Add the following code to the file:

print("Hello World")

Click "Run" then choose "Run Module". This will run the program:

Output

Hello World

Other than executing the program from the graphical user interface, we can do it from the terminal of the operating system. However, you must be aware of the path to the directory where you have saved the file.

Open the terminal of your operating system then navigate to the location of the file. Of course, you will use the "cd (change directory)" command for this.

Once you reach the directory with the file, you will need to invoke the Python interpreter on the file. This can be done using the following syntax:

> python 

To run the Python file from the terminal, you just have to type the python keyword followed by the name of the file. In our case, we need to run a file named "hello.py". We need to type the following on the terminal of the operating system:

> python hello.py
Hello World

If you want to get to the Python shell after getting the output, add the -i option to the command. This is demonstrated below:

> hello -i hello.py
Hello World

The following example demonstrates how to execute the multiple lines of code using the Python script.

name = "Nicholas"
age = 26
course = "Computer Science"
print("My name is", name, ",aged", age, ",taking", course)

Pros and Cons of Script Mode

The following are the advantages of running your code in script mode:

  1. It is easy to run large pieces of code.
  2. Editing your script is easier in script mode.
  3. Good for both beginners and experts.

The following are the disadvantages of using the script mode:

  1. Can be tedious when you need to run only a single or a few lines of cod.
  2. You must create and save a file before executing your code.

Key Differences Between Interactive and Script Mode

Here are the key differences between programming in interactive mode and programming in script mode:

  1. In script mode, a file must be created and saved before executing the code to get results. In interactive mode, the result is returned immediately after pressing the enter key.
  2. In script mode, you are provided with a direct way of editing your code. This is not possible in interactive mode.

Conclusion

There are two modes through which we can create and run Python scripts: interactive mode and script mode. The interactive mode involves running your codes directly on the Python shell which can be accessed from the terminal of the operating system. In the script mode, you have to create a file, give it a name with a .py the extension then runs your code. The interactive mode is suitable when running a few lines of code. The script mode is recommended when you need to create large applications.

What is mode in python?

mode() function in Python statistics module The mode of a set of data values is the value that appears most often. It is the value at which the data is most likely to be sampled.

What are the two different modes of Python?

There are two ways to use the python interpreter: interactive mode and script mode. (a) You can also save your commands in a text file, which by convention have the suffix “. py”, for example, program.py.