0

I'm new to python and am trying to check if startmiles and endmiles are input as integer only and gallons are input as float. When I enter alpha the program crashes. Thank You

#!/usr/bin/env python

import os
import sys
import subprocess
import datetime 
clear = lambda: os.system('clear')

clear()

t = datetime.datetime.now()
from time import gmtime, strftime
strftime("%a, %d %b %Y %X +0000", gmtime())
today = strftime("%a, %d %b %Y ")
print(today,'\n')

def main():
    startmiles = input("Enter Your Start Miles = ")
    endmiles = input("Enter Your Ending Miles = ")
    gallons = input("Enter Your Gallons = ")
    mpg = (int(endmiles) - int(startmiles)) / float(gallons)
    print("Miles Per Gallon =", round(mpg, 2))
    answer = input("\n Go Again Y or n ").lower()
    if answer == 'y': print('\n'), main()
    if answer != 'y': print('\n Thank You Goodbye')



if __name__=="__main__":
    main() # must be called from last line in program to load all the code
kuro
  • 3,214
  • 3
  • 15
  • 31
marvin
  • 13
  • 2
  • 1
    `when I enter alpha the program crashes` It would be much easier to help if you posted the exact error message, instead of vaguely telling us "the program crashes". – John Gordon May 21 '17 at 03:36

2 Answers2

0

In Python 2.x the input should result in an integer anyways, unless you use raw_input. It looks like your mpg variable is taking the integer of the endmiles anyways.

In Python 3.x

startmiles = int(input("Enter Your Start Miles = "))

It sounds like you're saying certain characters crash the program, which means you need to do some exception handling. See this question response for more detail, but you need to find a way to handle your exceptions instead of crashing. Here's an example below forcing proper entry of the variable.

while True:
    try:
        # Note: Python 2.x users should use raw_input, the equivalent of 3.x's input
        age = int(input("Please enter your age: "))
    except ValueError:
        print("Sorry, I didn't understand that.")
        #better try again... Return to the start of the loop
        continue
    else:
        #age was successfully parsed!
        #we're ready to exit the loop.
        break
    if age >= 18: 
        print("You are able to vote in the United States!")
    else:
        print("You are not able to vote in the United States.")
Community
  • 1
  • 1
Benloper
  • 448
  • 4
  • 13
0

Convert your inputs to int/float as soon as they are entered, wrapped in a try/except block in a loop to catch exceptions and immediately prompt again for more input:

while True:
    try:
        startmiles = int(input("Enter Your Start Miles = "))
        break
    except ValueError:
        print('that is not an integer, please try again')

Or just wrap your final calculation in a try/except:

try:
    mpg = (int(endmiles) - int(startmiles)) / float(gallons)
except ValueError:
    print('some error message')

But this way you can't easily ask for more input, and you don't know exactly which value caused the error.

John Gordon
  • 29,573
  • 7
  • 33
  • 58