liveBook · Manning

Integer

As explained in Python Workout, Second Edition

An integer is a whole-number numeric value without a fractional part, represented in Python by the int type.

An integer is a whole-number value without a fractional part, represented in Python by the int type. Integers support calculations, indexes, counters, comparisons, and values returned by functions such as random.randint. section 2.0 section 2.2

Input arrives as a string, so convert it explicitly before numeric work: int('5') produces 5, while str(5) produces '5'. The int function can also accept a base, such as int('ff', 16). section 2.3 section 2.15

Use integers in small programs by combining them with:

  • random.randint(low, high), which returns an integer and includes both endpoints. section 2.3
  • Comparison operators such as ==, <, and >, often inside a while loop. section 2.3
  • Conversion checks, using str.isdigit() or handling ValueError when input may not represent an integer. section 2.4

Number guessing

Generate a secret integer, repeatedly convert the user's guess, compare the values, and stop when they match. The same pattern can be extended with a limited number of attempts or alternate number bases. section 2.2 section 2.5

import random


def guessing_game():
    answer = random.randint(0, 100)

    while True:
        user_guess = int(input('What is your guess? '))

        if user_guess == answer:
            print(f'Right!  The answer is {user_guess}')
            break

        if user_guess < answer:
            print(f'Your guess of {user_guess} is too low!')

        else:
            print(f'Your guess of {user_guess} is too high!')

guessing_game()

Trace a complete integer-guessing program with random generation, input conversion, comparisons, and loop termination. section 2.4

How Python Workout, Second Edition covers it

How deep it goes
Defines int and practices conversion, comparison, bases, and validation, but stops short of integer implementation internals.
Examples
Practices integers through a number-guessing game, run-time accumulation, hexadecimal conversion, and summing or averaging exercises.
What it assumes
Assumes basic Python functions and loops while teaching numeric types, input conversion, and integer validation through exercises.
What you can do after
Build integer-driven programs that parse input, compare values, generate random numbers, and accumulate numeric results.
How it connects
Connects integers with floats, strings, input, loops, comparison operators, random numbers, and number bases.

Also explained in

Compare how 15 books explain integer →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Python Workout, Second Edition. The section links point to the parts of the book it draws on.