-1

I am creating a simple calculator program and want to shorten down the amount of typing I have to do when checking input variables. Is there a way to assign of my IF/ELSE statements and call them to save time and typing? I have to write this out for a lot variables. I do not have a lot of knowledge in python yet, so please try to make it simple and easy to understand.

loop = 1
while loop == 1:
    a1 = input("Add this number of apples: ")
    if a1.isdigit():
        a1 = int(a1)
    else:
        print("You cannot add a letter, changed to 0.")
        a1 = 0
        loop = 1
    if a1 < 0:
        print(user_name + ", You cannot choose a negative number!")
        loop = 1
    else:
        print("")
        print(a1, "apples +", a2, "apples =", a1 + a2, "total apples.")
        print("")
        loop = 1
    a2 = input("to this number of apples: ")
    if a2.isdigit():
        a2 = int(a2)
    else:
        print("You cannot add a letter, changed to 0.")
        a2 = 0
        loop = 1
    if a2 < 0:
        print(user_name + ", You cannot choose a negative number!")
        loop = 1
    else:
        print("")
        print(a1, "apples +", a2, "apples =", a1 + a2, "total apples.")
        print("")
        loop = 1
Sam
  • 7,252
  • 16
  • 46
  • 65
  • 1
    possible duplicate of [Asking the user for input until he gives a valid response](http://stackoverflow.com/questions/23294658/asking-the-user-for-input-until-he-gives-a-valid-response) – Kevin May 01 '14 at 16:18
  • I didn't understand the question. – yazz.com May 01 '14 at 16:44

1 Answers1

0
def get_int(prompt):
    while True:
        try:
            return int(raw_input(prompt))
        except ValueError:
            print "Please Enter An Integer"

def get_conditional_int(prompt,condition,error):
    while True:
          a = get_int(prompt)
          if condition(a):
             return a
          print error


a = get_conditional_int("Enter The Number Of Apples:",lambda x:x>0,"Enter A Positive Value!")
print a + 54

as an aside with your current code you will never get a negative

print "-5".isdigit()
Joran Beasley
  • 110,522
  • 12
  • 160
  • 179