# Python language basics 13: our first Python application

Introduction

In the previous post we saw how to get the user’s input in a command window. In this post we saw how to construct a while loop in Python. In this post we’ll marry the two concepts and build our first “real” application which requires user input. We’ll put together a simple number-guessing game where the computer “thinks” of a number between two integers and the user has to keep guessing until they find the correct one.

Random numbers in Python

The game will start by the user’s inputs for the lower and upper limit of the random number. Let’s first see how to generate a random integer in Python. It’s very simple. The following code bit will print a random number between 1 and 10 where both 1 and 10 are inclusive:

```from random import randint
print(randint(1, 10))
```

The following bit of code will ask the user to enter a lower limit and an upper limit and generate a random integer:

```from random import randint

lowerLimitInput = input('Lower limit: ')
upperLimitInput = input('Upper limit: ')

randomNumber = randint(int(lowerLimitInput), int(upperLimitInput))
```

All of these should be familiar from the previous posts on Python. You may be wondering why we use the int() constructor in the randint function. The reason is that all user inputs from the input() function will be stored as strings. That’s the case for numbers as well. So even if you enter 10 it will be stored as “10” in the variable. As randint is expecting integers and not strings we need to convert the strings into integers using the int() constructors as we saw here.

There are some other important concepts from basic programming that we could introduce here. However, I don’t want to overwhelm you if you’re a novice programmer. E.g. if you run the above code and provide a value other than an integer, say “elvis” then you’ll get an angry message like this:

Traceback (most recent call last):
File “C:/PythonProjects/HelloWorld/NumberGuessing.py”, line 6, in
randomNumber = randint(int(lowerLimitInput), int(upperLimitInput))
ValueError: invalid literal for int() with base 10: ‘elvis’

This angry message is called an exception. We say that the application throws an exception. We’ll look at exceptions later in the course and how to handle them. The reason why the exception was thrown is that we tried to convert a non-integer string into an integer and the program could not handle it.

Similarly if you provide a lower limit which is higher than the lower limit then you’ll see a different exception:

Traceback (most recent call last):
File “C:/PythonProjects/HelloWorld/NumberGuessing.py”, line 6, in
randomNumber = randint(int(lowerLimitInput), int(upperLimitInput))
File “C:\Python34\lib\random.py”, line 218, in randint
return self.randrange(a, b+1)
File “C:\Python34\lib\random.py”, line 196, in randrange
raise ValueError(“empty range for randrange() (%d,%d, %d)” % (istart, istop, width))
ValueError: empty range for randrange() (10,6, -4)

the randint function couldn’t handle the case where the lower limit was higher than the upper limit and threw an exception.

The notion of validation is strictly connected to exceptions. User input should be validated in order to avoid exceptions.

However, for now just be careful with the inputs and make sure you enter valid integers. We’ll revisit those ideas mentioned above later on.

The game

The game flow is simple. While the number provided by the user is not equal to the initial random one the program will keep asking the user for a new input and recheck its correctness:

```guess = int(input('Your first guess: '))
guessCounter = 1

while randomNumber != guess:
if guess > randomNumber:
print('Too large')
else:
print('Too small')
guessCounter += 1
guess = int(input('Your next guess: '))

print('Congratulations. It took you ' + str(guessCounter) + ' guesses to guess the correct number.')
```

That shouldn’t be too difficult to follow. We need to convert the string into an integer again when asking for the guess. The conversion works in the other direction as well. The print() function accepts strings and guessCounter is an integer. We need to convert it to a string using the str constructor.

Run the code and have fun. A typical game output might look like this:

Lower limit: 1
Upper limit: 10
Too small
Too large
Too small
Congratulations. It took you 4 guesses to guess the correct number.

Read the next post which takes up string variables here.

Read all Python-related posts on this blog here. About Andras Nemes
I'm a .NET/Java developer living and working in Stockholm, Sweden.

### One Response to Python language basics 13: our first Python application

1. hardik says:

randomNumber is not in code. the correct one is guessCounter

Elliot Balynn's Blog

A directory of wonderful thoughts

Software Engineering

Web development

Disparate Opinions

Various tidbits

chsakell's Blog

WEB APPLICATION DEVELOPMENT TUTORIALS WITH OPEN-SOURCE PROJECTS

Once Upon a Camayoc

Bite-size insight on Cyber Security for the not too technical.