This time the assignment was to write a program that picks a random integer in the range of 1 to 100. It then asks the user to guess the number, it continues to run with hints of ’too high’ or ’too low’, until they guess right. The program also tells the user how many guesses they had made.

PickNumatom PickNumCygwin

The new things in this assignment is the random function, handling exceptions and conditionals inside conditionals.

A function is a named section of a program that performs a specific task whenever it is called. Python has some included functions, to use them you first need to call them, for that we use import and the name of the library. Random has a lot of functions, they are listed here, but the one I used was ranrange, which chooses a random number included in a range I gave, in this case 1 to 100.

We never know what the user will input, to counter that there are many methods. This time I needed an integer from the user, if the user were to write a string the program wouldn’t be able to run with that value, that is when we have to fight this exception. I used the method mentioned here, you can check that out, there are a lot of ways to handle errors and exceptions.

We saw while loops and conditional statements in WSQ05, but now we can see how we can have them one inside another. This may be a little difficult to grasp but it is quite useful when performing more complicated tasks.

There was also a variable whose only purpose was to count the times a loop is repeated. At the end of the loop it always sums 1 to it self. This helps a lot when you want to keep track of the loops.

CC BY 4.0 WSQ06 – Pick a Number by carminaperezguerrero is licensed under a Creative Commons Attribution 4.0 International License.