Запросить пользователя для ввода целого числа в Python

Основываясь на этой информации, вот несколько возможных способов добиться этого:

  1. Использование цикла while:

    while True:
    gallons_used = input("Enter the gallons used: ")
    if gallons_used.isdigit():
        gallons_used = int(gallons_used)
        break
    else:
        print("Invalid input. Please enter a whole number.")
  2. Использование функции:

    def get_gallons_used():
    while True:
        gallons_used = input("Enter the gallons used: ")
        if gallons_used.isdigit():
            gallons_used = int(gallons_used)
            return gallons_used
        else:
            print("Invalid input. Please enter a whole number.")
    gallons_used = get_gallons_used()
  3. Реализация проверки ввода:

    def get_valid_gallons_used():
    while True:
        gallons_used = input("Enter the gallons used: ")
        if gallons_used.isdigit() and int(gallons_used) >= 0:
            return int(gallons_used)
        else:
            print("Invalid input. Please enter a non-negative whole number.")
    gallons_used = get_valid_gallons_used()