This week we are going to do our first game in python. It is a very simple game where the participant must guess a random number chosen automatically in less than 10 attempts with the help of the clues that the system will provide when entering a number.
We are going to practice loops, the conditionals and we will learn to import modules and generate random numbers.
If you want to develop your career in Python, we recommend you visit our master in Advanced Programming in Python for Big Data, Hacking and Machine Learning and train with the best experts.
As we saw weeks ago, Python includes predefined functions so we can use them whenever we want, but we can also import modules that include specific functions for each module and that will make our lives easier when programming.
The only thing we have to do is import the module we want with the declaration “import” followed by the name of the module in question.
We start by looking at all the game code

We have started by importing the module random which includes functions related to random numbers:

We create a counter by name "Attempts” to show the player how many guesses he has used to guess the number which we will increment each time he enters the while loop.

With the function randint, we generate a random integer number between the two values that we indicate below between the parentheses. In that line, we indicate that the variable x It will be a random integer between 1 and 50.

We create a loop while where as a condition we indicate that Attempts is less than 10 (with this we already have the 10 attempts). Once inside, we increase the variable Attempts in 1 and we request the entry of a number and then offer information to the user depending on whether that number is greater, less or equal to the randomly generated one.

In the last part of the code we will show a message to the player that will depend on whether they have guessed the number correctly or have exceeded the number of attempts. As we can see in the code, we convert the variables to text Attempts and x with str().

Finally, we leave you some screenshots of the game.

