How to give an error msg based on user input in my program?
Hire the world's top talent on demand or became one of them at Toptal: https://topt.al/25cXVn
and get $2,000 discount on your first invoice
--------------------------------------------------
Music by Eric Matyas
https://www.soundimage.org
Track title: Puddle Jumping Looping
--
Chapters
00:00 How To Give An Error Msg Based On User Input In My Program?
01:36 Answer 1 Score 0
02:22 Answer 2 Score 0
02:52 Answer 3 Score 0
03:48 Accepted Answer Score 0
04:26 Thank you
--
Full question
https://stackoverflow.com/questions/3877...
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#python #ifstatement #errorhandling #whileloop
#avk47
ANSWER 1
Score 0
I put your error message in an if statment, and the calculation code in an else. This way it won't do the calculation when the hour isn't correct and instead will exit main and go back to the while loop and ask the user if they will like to play again. Also as other user's have pointed out following what I did below you should add more error testing and messages for negative numbers, etc.
def main():
    star = '*' * 70
    print star
    print ("Nick's Electric Bill Calculator")
    print star
    watts = input("Enter the watts of appliance, or total watts of        appliances ")
    hours = input("Enter the number of hours that appliance(s) run per day ")
    cost = input("Enter the cost in cents per KwH you pay for electricty " )
    if hours > 24:
        print("Don't be silly, theres not more than 24 hours in a day ")
    else:
        x = (watts * hours / 1000.0 * 30) * cost
        total = x
        print star
        print ("""If you use %s watts of electricity for %s hours per day, at a cost of %s cents per Kilo-watt hour, you will add $%s to your monthly electric bill""") % (watts, hours, cost, total)
       print star
playagain = 'yes'
while playagain == 'yes': 
main()
print('Would you like to do another Calculation? (yes or no)')
playagain = raw_input()
ANSWER 2
Score 0
The input you get from the user is a string type, but you compare it to int type. That's an error. You should cast the string to int first:
hours = int(input("How many hours per day? "))
#    ----^---
Then you can do something like:
while hours > 24:
    print("Don't be silly, theres not more than 24 hours in a day ")
    hours = int(input("How many hours per day? "))
If you don't sure the user will input a number you should use a try/catch statemant.
Except from this you should validate you indent the code correctly
ANSWER 3
Score 0
My python skills are a little rusty, but when I have to do stuff like checking input, I usually use a structure something like this:
hours = 0
while True:
   hours = input("How many hours per day? ")
   #first make sure they entered an integer
   try:
      tmp = int(hours) #this operaion throws a ValueError if a non-integer was entered
   except ValueError:
      print("Please enter an integer")
      continue
   #2 checks to make sure the integer is in the right range
   if hours > 24:
      print("Don't be silly, theres not more than 24 hours in a day ")
      continue
   if hours < 1:
      print("Enter a positive integer")
      continue
   #everything is good, bail out of the loop
   break
Basically, it starts by going into an 'infinite' loop.  It gets the input, goes through all the checks to see if it is valid, and hits the break (leaving the loop) if everything went okay.  If the data was bad in any way, it informs the user and restarts the loop with the continue.  hours = 0 is declared outside the loop so it is still accessible in the scope outside, so it can be used elsewhere.
Edit: adding an idea to the example code that I thought of after seeing @Ohad Eytan's answer
ACCEPTED ANSWER
Score 0
An optimized version of @JamesRusso code :
def main():
    star = '*' * 70
    print star
    print ("Nick's Electric Bill Calculator")
    print star
    watts = int(input("Enter the watts of appliance, or total watts of appliances"))
    hours = int(input("Enter the number of hours that appliance(s) run per day"))
    # Check that the hours number is good before getting to the cost
    while (hours > 24) or (hours < 0):
        print("Don't be silly, theres not more than 24 or less than 0 hours in a day ")
        hours = int(input("Enter the number of hours that appliance(s) run per day "))
    cost = int(input("Enter the cost in cents per KwH you pay for electricty "))
    # We don't need an auxiliary variable x here
    total = (watts * hours / 1000.0 * 30) * cost
    print star
    print ("""If you use %s watts of electricity for %s hours per day, at a cost of %s cents per Kilo-watt hour, you will add $%s to your monthly electric bill""") % (watts, hours, cost, total)
       print star
if __name__ == '__main__':
    playagain = 'yes'
    while playagain == 'yes': 
        main()
        print 'Would you like to do another Calculation? (yes or no)'
        playagain = raw_input()
        # Checking that the user's input is whether yes or no
        while playagain not in ['yes', 'no']:
            print "It's a yes/no question god damn it"
            print 'Would you like to do another Calculation? (yes or no)'
            playagain = raw_input()