Search

The Secrets Of Random Numbers In Python – The Number Guessing Game Part 2

Yesterday, we explained in depth some of the functions that are included in the random module in python. Today, we will be applying that knowledge to build a simple guessing game. This is how the game goes.

The computer will think of a random number between 1 and 20 inclusive and ask the player to guess it. The player has 6 tries to guess it right. For each guess, the computer will tell the player if the guess is too high, too low, or the correct guess. After 6 tries, if the player has not correctly guessed the number, the game will end.

python random numbers
 

Interesting, not so? Well, here is the code for the game.

Now, let’s explain the code line by line so you understand what is going on.

Line 1: To use the random number functions, we have to import the random module. So, that is what this does.

Line 3: using the random.randint function with arguments 1, 20, we are asking the computer to generate a random number between 1 and 20. Simple. I believe you understood this line.

Lines 4-7: The computer asks the player to input his or her name, initializes num_guesses, the counter we use to calculate how many guesses the player has made so far, and sets the guessed_right switch to False to indicate that the player hasn’t made the right guess yet.

Line 9: Using a while loop, we wait for the player to make at most 6 guesses until he guesses the number right or fails to guess it right. Now, here comes the interesting parts after this line.

Lines 10-28: This is the main logic of the game and it occurs inside the while loop. First the computer informs the player of how many guesses have been made so far and asks him or her to make a guess. We use a try-except-else clause to catch the guess entered. If the player enters a guess that is not a number, such as a float or string, that is an error and the program catches it as an error and penalizes the player for the error by increasing the number of guesses made by 1. But if the player enters a number, it skips through the try-except block and goes to the else block which starts at line 16. From here on we are checking to see what number the player entered. The first conditional checks for whether the number is within the acceptable range. If it is not, the program asks the player to enter a number within the acceptable range and penalizes him by increasing the guess count by 1. The next elif blocks checks if the number, which is within the range for acceptable numbers, is too low or too high. If either of these, the number of guesses count is increased by 1. But if these two are skipped that means the player guessed the right number and the guessed_right switch is set to True. The program then breaks out of the while loop.

Elegant! Not to mention beautiful.

Lines 30-33: This is the cleaning up code. Here after the loop exits the program checks whether the player guessed right or not. If he or she guessed right, the program prints a congratulatory message and tells him how many guesses he took. But if the player guessed wrongly, the program encourages the player to try again and then tells the player what the number was.

You could write your own code that implements the functions in the random module. It is a really useful module. I wish you success in doing so.

You can download the script for the game here if you want to run it on your own machine.

The Secrets Of Random Numbers In Python Part 1

python random numbers
 

When people think of random numbers, they think of something disorganized and that cannot be predicted. That is what I thought until I entered the world of random numbers using python. You see, random numbers do not just run arbitrarily. The name is deceptive. They are based on what are called seeds. A seed can either be provided by the programmer, and if one is not provided, python uses the system clock or what is supplied by the operating system.

If you decide to set the random number generator rather than allow the program to initialize it on its own, you call the random.seed function, supplying it with a seed that you desire. The seed has to be an int. This could be done using the code:

As you can see from running the above code where we gave the random function the same seed, the same output was produced consecutively. That is why the random function is deceptive. Why it is really random is because since the programmer most times does not provide a seed but allows it to self-generate, the random number becomes really random.

By the way, the disclaimer from the makers of the python programming language is that the functions in the random module should not be used in cryptography.

Now let’s take a ride on some of the functions included in the random module.

The functions are divided into functions that manipulate integers, sequences, and real-valued distributions. We will concentrate on the first two in this article.

What are the functions that manipulate integers.

The two functions in the random module that manipulate integers are random.randint and random.randrange. They both do the same thing. They return an integer based on a given range. The differences between them is that in random.randint the second positional argument is included in the range of numbers to be considered, while in random.randrange the range to consider stops just before the second positional argument. The syntax for both of them is random.randint(a, b) and random.randrange(start, stop[, step]). For random.randrange the stop is not included in the range that is to be considered, while in random.randint the last positional argument, b, is considered in the range to be considered. Also, note that you could step through random.randrange using the step argument. For example, you could leave out some numbers in a range using step, just as you can do using the in-built range function.

Overall, both of them serves the same function: give a random integer from a given range and conditions.

If you run the code below, you will be sure to get a random integer between 1 and 20 inclusive.

What are the functions that manipulate sequences.

The functions for manipulating sequences are four in number and they sometimes overlap. I will describe each of them and give code you can run.

random.choice(sequence):

This function returns a random element from sequence provided sequence has items in it otherwise it will raise an IndexError. I think this is simple enough. Now, the code.

Each time you run the code above, it will give you a chosen fruit. There are repeats too. So, don’t be surprised because the list of fruits is not exhaustive.

random.choices(population, weights=None, *, cum_weights=None, k=1):

This function returns a list of size k (default is 1, note) from the population which could be a sequence or a range. If you do not want to apply any probability to the items that would be returned in the list, then you would leave weights and cum_weights keyword arguments alone. But if you want to give some weight or assign probabilities to what can be chosen at random, you have to provide value for weights or cumulative weight, cum_weights. Using the list from above, let us give higher probability to apple and orange using the keyword argument, weights=[5,5,5,15,15]. I will also tell the code to chose just two items from the list of fruits at random.

If you run the code, you will see that you will have a high probability of having orange and apple in the returned list rather than the other fruits. One point to note is that weights cannot be negative.

random.shuffle(x[, random]):

This function takes as argument a sequence, x, and shuffles the items in place. You can provide an optional random function that could be used to shuffle the items. I think this is well explained using code. I will provide code that does not use the random function and one that does.

This code does not use the random function.

Each time you run it, it randomly rearranges the items in the list.

Now this one uses a random function. I want you to run it more than one time and notice the arrangement of the items.

Did you notice that the rand_function acted as a seed to the random.shuffle function? Each time it runs, it returns the list of items in the same sequence. Very cool! You can play with it. Note that the random function can be any function that returns a floating point number between 0.0 and 1.0. I used 0.09.

Now for the last function that manipulates sequences.

random.sample(population, k):

This function is used for random sampling without replacement. It returns a list of size k from the population. It is similar to the choices function but without the weights and without replacement. In random.choices, the returned list can have repeated items but not in random.sample. Now for some code.

Run the above code repeatedly and see. The sample size, k, should not be larger than the population size otherwise python will raise a ValueError.

You can use this function to generate a random list of integers from a very large sample size using the range function as the population argument using code like this: random.sample(range(1000000), 100). Very cool and very efficient.

So, that is the secret to the random function. Now that you have learned what it is and how to use it, why don’t we play with it a little.

Tomorrow, I am going to post a little game that uses the random function. So, make sure to watch out for the game.

Happy pythoning.

7 Ways To Keep Yourself Motivated While Programming

Programming to be honest is not easy. It can be hard especially when you are stuck in a problem, or even when you have a bug and you don’t know a way out of it. I once wrote a project that had 400 lines of code and eventually there was a bug in it. I had to use bisection search to go through each of the lines of code to find out the bug. That one hour of work was very demotivating. You really need to be motivated to be a programmer, even while programming in python which is one of the easiest languages around.

People often ask me: “Nnaemeka David, what do you do to be motivated? Sometimes, it gets hard and frustrating?” So, I decided to write this post on some of the things one can do to get motivated while programming.

programming motivation
 

  1. Be disciplined.

  2. According to some dictionaries, discipline is the practice of obeying rules or a code of behavior. This skill is essential in programming because if you are not disciplined, you will end up in a lot of obstacles to your programming. Disciplining frees up your mind to think about solutions, and not just to rush into putting lines of code on an editor. Discipline makes you set up your programming defensively; you plan ahead for obstacles to your programming when disciplined. Discipline involves understanding the conventions of python as a programming language and following them. They keep you motivated. The style guide for python code, or sometimes called PEP8, is a good resource to instill discipline.

    When I learned programming from Professor Eric Grimm at MIT, (online course), he kept emphasizing on doing tests and setting yourself up for defensive programming before you begin writing code. I have seen the wisdom of that as time goes by. It helps me to debug; and bugs are something you will find all the time.

    If you are not disciplined, you will find yourself looking for a needle in a haystack. That is a very frustrating endeavor.

  3. Start with the bare minimum.

  4. Often beginners to python keep asking the question: Can I learn python in 3 months? What do I do to be a data scientist in the shortest space of time? I always tell anyone that asks me that they should go with the flow. Don’t force it. If you force it and you want to learn everything in the shortest time, you will get disappointed. Start with the bare minimum. Increase your aptitude as time passes by and your confidence increases. Otherwise, when it is 3 months and you discover you have not even scratched the surface of python programming, you will lose motivation. It is similar to when someone is working on the treadmill.

    While working on the treadmill, you don’t just start all at once doing 3 hours at a go. First, you start with five minutes intervals and take breaks. Then, as your body gets used to the routine, you increase the time you spend. So it is with programming in python and any other language. My advice to anyone who wants to take a fast paced approach is that they might be setting themselves up for disappointment. Rather, you take it slowly, one step at a time. Don’t constrain yourself to a time limit, but regularity is the secret to success.

  5. Try the Pomodoro technique.

  6. The Pomodoro technique is a time management technique that encourages you to work using the time you have rather than work against it. For example, say you can spare 30 minutes for programming, what you do is you spend that 30 minutes and set a timer to alert you when the time is up. When it is up, you take a break, and when you can spare another 30 minute you continue again, setting the timer. Many programmers have confessed that the pomodoro technique helps them to be productive. It can also help you.

    As programmers, we spend a lot of time in front of the computer and burn-out can easily set in, causing you to lose motivation. With the pomodoro technique, you will never get burned out because you are pacing yourself and taking breaks that helps you to get refreshed. Pomodoro technique also helps to boost your concentration and focus. There are a lot of softwares that implement the pomodoro technique and you can use them, like the focus booster app that runs on both windows and mac.

    A programming friend of mine on a forum told me that he used the pomodoro technique to learn 3 languages in 2 months. You can try it out yourself.

  7. Set goals.

  8. There is a trite saying that if you fail to plan, you are planning to fail. I have found setting specific goals helpful in helping me to get motivated while programming. But you don’t want to be setting goals you cannot achieve like starting from zero to hero in python in one month. You would be setting up yourself for failure. Set SMART goals, that is, goals that are specific, measurable, achievable, relevant, and time-oriented. After you have achieved one goal, congratulate yourself and move on to the next. Doing this, you will find python programming, or any other programming task, very enjoyable and fun.

    When I started programming, one goal I set is to do one challenge on hackerrank.com on a daily basis. I succeeded in completing the 30 days of code challenge and also doing other challenges. On some days, I would really feel in high spirits, congratulating myself for moving on to the next level. Try it out yourself by signing up at hackerrank.com and take a challenge. If you are a new programmer, take the basic challenge. There are lots of languages to choose from at the website.

  9. Projects, Projects and lots of Projects.

  10. To boost your confidence level and set yourself up for the industry, you can never underestimate the value of doing projects. My advice is that you do projects, more projects and lots of projects. Sign up at github and look for projects to collaborate. There are even projects on github.com that accepts beginners. You could sign up for those if you are new to python programming.

    If you don’t have ideas on what projects to do that would fit your level, just Google it. You will find all sorts of projects that you can choose from on Google; from beginner to expert.

    If you keep going from tutorial to tutorial while on your programming journey, you will be disappointed in record time. You need to learn to practice. That is the secret to being motivated.

  11. Love what you are doing.

  12. You must be passionate about programming, in python or any other language, to survive in this industry. Without passion and love for coding, you would be disappointed in no time. It involves lots of screen time, sometimes it steals the time from your relationships. You could set yourself up for failure if you are doing it for the money because you will encounter a lot of obstacles in the programming journey.

    Love programming. Write a line of code every day. In fact, to be motivated, you must love doing this and if you have read this post this far, I believe you love coding and want to improve. So congratulations.

  13. Start teaching others about programming.

  14. Teaching is a way of imparting knowledge to others. While you are teaching, you are improving your ability to use python and to learn python. Remember, as you are teaching others, you are teaching yourself. You are gaining benefits for yourself that are valuable.

    Also, teaching others imparts other soft skills to you. By teaching others, you gain communication skills and presentation skills. While successfully teaching others, you increase your confidence in using python programming language and you also gain leadership skills. According to glassdoor.com, a job search site, these skills are in high demand in the programming industry.

    If you cannot be part of a class to teach, you can participate in forums to help others. Forums like python-forum.io, freecodecamp.org, and Stackoverflow.com, can be of immense help to you to get teaching opportunities.

I wish you success in your programming career.

Matched content