Python language basics 13: our first Python application


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))

Asking for the limits

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/”, 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/”, line 6, in
randomNumber = randint(int(lowerLimitInput), int(upperLimitInput))
File “C:\Python34\lib\”, line 218, in randint
return self.randrange(a, b+1)
File “C:\Python34\lib\”, 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')
        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
Your first guess: 5
Too small
Your next guess: 8
Too large
Your next guess: 6
Too small
Your next guess: 7
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.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s


A great site

iReadable { }

.NET Tips & Tricks

Robin Sedlaczek's Blog

Developer on Microsoft Technologies

HarsH ReaLiTy

A Good Blog is Hard to Find

Softwarearchitektur in der Praxis

Wissenswertes zu Webentwicklung, Domain-Driven Design und Microservices

the software architecture

thoughts, ideas, diagrams,enterprise code, design pattern , solution designs

Technology Talks

on Microsoft technologies, Web, Android and others

Software Engineering

Web development

Disparate Opinions

Various tidbits

chsakell's Blog

Anything around ASP.NET MVC,WEB API, WCF, Entity Framework & AngularJS

Cyber Matters

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

Guru N Guns's

OneSolution To dOTnET.

Johnny Zraiby

Measuring programming progress by lines of code is like measuring aircraft building progress by weight.

%d bloggers like this: