My Blog

This is my web coding blog. It's the home for several simple, easy-to-understand applications which are written using various programming languages. Feel free to get in touch if you want me to code a specific project for you.

Generate, sort, and display random numbers in Python

Welcome to my first Python tutorial! For those of you who aren't familiar with it, Python is a high-level programming language. This means that you can write Python code using common words such as "print," "sort," and so on.

This convenience comes at a price, though; Python isn't among the fastest programming languages in the world. But who needs a 10-20% extra speed boost when most computers are so fast these days? And lots of people love Python because it is a general-purpose language, meaning that you can create a wide variety of applications using it.

So, let's get started with our first application, which generates five random numbers, sorts them in ascending order, and then displays them. Here's how the source code for the entire application looks like.

import random

def main():
    num1 = random.randint(1, 100)
    num2 = random.randint(1, 100)
    num3 = random.randint(1, 100)
    num4 = random.randint(1, 100)
    num5 = random.randint(1, 100)

    num_list = [num1, num2, num3, num4, num5]
    num_list.sort()

    print("The random numbers in increasing order are:")
    for num in num_list:
        print(num)

main()

If you've never programmed before, you can test the code using an "online python compiler." Just run a Google search for that group of words, and you will discover lots of options. I will use the one that is available here for my examples.

Copy/paste the code above in the editor, and then press the "Run" button. Here's an image that shows the output.
The first line of code imports the random number generation module; without it, we wouldn't be able to create those random numbers. Then, we define main(), which is the entry point of our application.

I chose to name the random numbers num1... num5. It's a simple naming convention, but it does the job. As you can see by looking at the values inside the parenthesis, the value of each random number ranges from 1 to 100.

We create a list called... num_list which stores those five numbers, and then we sort them in ascending order using the sort() method.

The only thing that's left now is to display those random numbers. We print a text on the screen, and then we use a "for" loop. This loop will repeat the "print(num)" action over and over until it processes all the numbers inside num_list, which means that it will display all the numbers on the screen.

If you press "Run" again, the application will generate another set of random numbers.

I hope that you liked this quick tutorial; it shows how many things you can do with Python using only a few lines of code. I'll try to find the time and create another blog post that shows more Python-related coding tricks soon.