Skip to main content
GameDev.net gamedev.net

PRO Tired of ads? Read GameDev.net ad-free and help keep the community independent with GameDev Pro — $3/month.

Discover Python and Patterns (5): Integers

Discover Python and Patterns (5): Integers

phylyp
phylyp
Design Patterns and Video Games · · 1 min read
3,190 0

In previous posts, I only used strings and booleans. In this one, I use a new data type called “int” (for integer) that allows the storage and computation of natural numbers (numbers without a decimal part). I use them to create the famous “guess the number” game!

This post is part of the Discover Python and Patterns series

Integers

You can create a variable with an integer value in the following way:

magicNumber = 3

Python understands that magicNumber is an int: there are only digits, and there is no dot. If we use quotes, then it becomes a string:

magicNumber = "3"

Variable types change the behavior of operators. For instance, if you run the following program:

magicNumber = 3
print(2*magicNumber)

You see the value “6”, because magicNumber is an int, and the result of 2 times 3 is 6.

If you run this other program:

magicNumber = "3"
print(2*magicNumber)

You see the value “33”, because magicNumber is a string, and the result of 2 times “3” is “33” (Python repeats two times the string).

You can do many different computations, and we’ll see examples throughout this series.

Types and comparisons

If we want to implement the game “guess the number” with an integer variable, we can try the following program:

magicNumber = 3
while True:
    playerNumber = input("What is the magic number? ")
    if playerNumber == magicNumber:
        print("This is correct! You win!")
        break
    print("This is not the magic number. Try again!")

Continue reading on https://www.patternsgameprog.com/discover-python-and-patterns-5-integers/


Discussion

Loading comments...