Start with a user-input problem: input() always returns a string, so numeric input must be converted before arithmetic or ordering comparisons. Call the target type with the source value, as in int('5') or str(5). section 2.2 section 2.3
Use conversion deliberately when the value's required type changes:
- Convert guesses with int(input(...)) before comparing them with a randomly generated integer. section 2.3
- Choose float instead of int when rainfall may contain a floating-point value. section 5.9
- Construct more complex values by calling their types, such as list('abc') or dict([('a', 1), ('b', 2), ('c', 3)]). section 2.3
- Remember that + combines strings instead of adding their numeric meanings when conversion is skipped. section 5.9
Convert and validate rainfall input
try: mm_rain = int(input('Enter mm rain: ')) except ValueError: print("You didn't enter a valid integer; try again.") continue rainfall[city_name] = rainfall.get(city_name, 0) + mm_rain This approach lets invalid input return to the loop instead of terminating the program. An alternative checks mm_rain.isdigit() before calling int(), but that rejects negative and floating-point values. section 5.9
try:
mm_rain = int(input('Enter mm rain: '))
except ValueError:
print('You didn't enter a valid integer; try again.')
continue
rainfall[city_name] = rainfall.get(city_name, 0) + mm_rain
Inspect the complete try/except conversion pattern for accepting an integer and accumulating it in a dictionary. section 5.9




















