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














