# Guess the number — The return

We have seen this example previously. There I included a lot of loops to handle user input and the main logic… Now it is time to refactor the application to use functions. This should make the code readable and we could re-use parts later.

One of those re-usable parts is the number reading. We have two points where we want the user to enter a number and have written slightly the same code. This is a very good place to start refactoring and extract this into one function.

This article is an excerpt of my book Python 3 in Anger. For a more detailed version take a look at the book.

So let’s extract this into a function. The only difference is the message we print to ask the user for a number. This can be handled as a parameter of the function because this is the only variable part. So let’s see the definition of the function:

<br /> def ask_user_for_number(message_text):<br /> while True:<br /> try:<br /> return int(input(message_text))<br /> except ValueError:<br /> print("This was not a number!")<br /> continue<br />

As you can see this is a very straightforward approach where we ask the user for `input`

and return it if it is a number.

Naturally we cannot handle the verification of the number to be `100`

or `1000`

in this method so we have to modify out code block there too.

At the end of this simple modification we have the application with following code (and it has the same functionality):

<br /> __author__ = 'GHajba'</p> <p>import random</p> <p>def ask_user_for_number(message_text):<br /> while True:<br /> try:<br /> return int(input(message_text))<br /> except ValueError:<br /> print("This was not a number!")<br /> continue<br /> return number</p> <p>while True:<br /> max_number = 0<br /> while max_number != 100 and max_number != 1000:<br /> max_number = ask_user_for_number('Should the secret number between 1 and 100 or 1 and 1000? ')</p> <p> if max_number == 100:<br /> guess_count = 7<br /> else:<br /> guess_count = 10</p> <p> print('You have chosen {}, you will have {} guesses to find the secret number.'.format(max_number, guess_count))</p> <p> secret_number = random.randint(1, max_number)</p> <p> print('I have chosen the secret number...')</p> <p> guesses = 0</p> <p> while guess_count - guesses:<br /> guesses += 1<br /> guessed = ask_user_for_number("What's your guess? ")<br /> if guessed == secret_number:<br /> print('Congrats, you have Won!')<br /> break<br /> elif guessed > secret_number:<br /> print('The secret number is lower...')<br /> else:<br /> print('The secret number is higher...')<br /> else:<br /> print("Sorry, you lose.")</p> <p> print("The secret number was ", secret_number)<br /> answer = ''<br /> while answer.lower() not in ['yes', 'no', 'y', 'n']:<br /> answer = input("Do you want to play another round? (yes / no) ")</p> <p> if 'no' == answer or 'n' == answer:<br /> break<br />

This looks like a very nice code without duplication and it is very lean. However if you know something about testing you might say that this code has a very big “main” block which is hard to test.

I have to agree. Unit testing (although I will write about it in a later chapter) would be bothersome here. The solution would be to split this big main loop into smaller functions which can be tested on their own.

For example evaluating if the user has won or lost. For this we could write a function which takes the secret number, the guesses, the guess count and the guessed number as input and would evaluate the message to tell the user. But four parameters for a function are quite much so let’s divide it for now. I’ll create a function which tells the user if the secret number is higher or lower as the guessed number — based on these inputs.

<br /> def user_won(guessed, secret):<br /> if guessed == secret_number:<br /> print('Congrats, you have Won!')<br /> return True<br /> if guessed > secret_number:<br /> print('The secret number is lower...')<br /> else:<br /> print('The secret number is higher...')<br />

In the function `user_won`

we use a `return`

statement to indicate if the user has won. If not then we return the implicit `None`

which will evaluate to false.

One more thing we can test is asking the user if he/she wants to play another round or not.

<br /> def want_continue():<br /> answer = ''<br /> while answer.lower() not in ['yes', 'no', 'y', 'n']:<br /> answer = input("Do you want to play another round? (yes / no) ")</p> <p> return answer in ['yes','y']<br />

After all these changes let me show you again the full code:

<br /> __author__ = 'GHajba'</p> <p>import random</p> <p>def ask_user_for_number(message_text):<br /> while True:<br /> try:<br /> return int(input(message_text))<br /> except ValueError:<br /> print("This was not a number!")<br /> continue<br /> return number</p> <p>def user_won(guessed, secret):<br /> if guessed == secret_number:<br /> print('Congrats, you have Won!')<br /> return True<br /> if guessed > secret_number:<br /> print('The secret number is lower...')<br /> else:<br /> print('The secret number is higher...')</p> <p>def want_continue():<br /> answer = ''<br /> while answer.lower() not in ['yes', 'no', 'y', 'n']:<br /> answer = input("Do you want to play another round? (yes / no) ")</p> <p> return answer in ['yes','y']</p> <p>while True:<br /> max_number = 0<br /> while max_number != 100 and max_number != 1000:<br /> max_number = ask_user_for_number('Should the secret number between 1 and 100 or 1 and 1000? ')</p> <p> if max_number == 100:<br /> guess_count = 7<br /> else:<br /> guess_count = 10</p> <p> print('You have chosen {}, you will have {} guesses to find the secret number.'.format(max_number, guess_count))</p> <p> secret_number = random.randint(1, max_number)</p> <p> print('I have chosen the secret number...')</p> <p> guesses = 0</p> <p> while guess_count - guesses:<br /> guesses += 1<br /> guessed = ask_user_for_number("What's your guess? ")<br /> if user_won(guessed, secret_number):<br /> break<br /> else:<br /> print("Sorry, you lose.")</p> <p> print("The secret number was ", secret_number)<br /> if not want_continue():<br /> break<br />