An integer is a Python numeric value representing a whole number without a fractional component. A common programming task is converting text from input into an integer before comparing or calculating with it. section 1.22 section 1.3
Use integers when the value represents a count, index, guess, or exact small unit:
- Convert a string with int('5'), producing the integer 5; convert back with str(5). section 1.3
- Compare integers with ==, <, and >, but convert user input first because input always returns a string. section 1.3
- Represent money as cents rather than floating-point dollars when small rounding errors would matter. section 1.13
- Generate an integer in an inclusive range with random.randint, remembering that its upper bound is included. section 1.2 section 1.3
Number guessing game
Convert the user's text to an integer, compare it with a randomly selected answer, and repeat until the guess is correct. Invalid nonnumeric input raises ValueError unless validation or exception handling is added. section 1.4 section 1.3
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 workflow: generate the answer, read and convert input, compare values, report the result, and break from the loop. section 1.4
Practice integer handling by:
- Limiting the guessing game to three attempts or accepting guesses in randomly selected bases from 2 through 16. section 1.6
- Filtering nondigit strings before converting and summing the remaining integers. section 7.6
- Reading files, finding words containing only integers, and summing them. section 5.5














