How to exit without error

This is the place for queries that don't fit in any of the other categories.

How to exit without error

Postby zahrein » Sun Dec 08, 2013 1:10 pm

Hi, i make if else statement below. But if the user key in a different value, i have put an "else" statement. But ive got error as the value is not there in the dictionary.

Code: Select all
def z_payment_dic():
    import random



    list_of_payment={1:"rm700",
                     2:"rm1200",
                     3: "rm306",
                     4:"rm200",
                     5:"rm80"
                    }

    payment=raw_input("Enter your type  payment\n 1. car loan \n 2.house loan \n 3. HSBC loan\n 4.unifi \n  5.Maxis \n The bill that u wanna pay and just key in the value       ")
    if int(payment)==1:
        print "This is Car Loan payment"

    elif int(payment)==2:
        print "this house loan payment"

    elif int(payment)==3:
        print "this HSBC payment"

    elif int(payment)==4:
        print "this unifi payment"

    elif int(payment)==5:
        print "Maxis payment"
    else:
        print "you did not enter correctly"  # i have ERROR here  after executing different value

    payment_pay=list_of_payment[int(payment)]
    print "you need to pay  " + str(payment_pay)
zahrein
 
Posts: 15
Joined: Wed Apr 03, 2013 1:45 am

Re: How to exit without error

Postby rrashkin » Sun Dec 08, 2013 3:27 pm

Actually, you're getting the error when you try to access the dictionary with a value that isn't a key. You should either move the last 2 lines into each if/elif clause or set a flag and only execute the last 2 lines if the flag is set appropriately. Like:

Code: Select all
   ...
    p=1
    if int(payment)==1:
        print "This is Car Loan payment"

    elif int(payment)==2:
        print "this house loan payment"

    elif int(payment)==3:
        print "this HSBC payment"

    elif int(payment)==4:
        print "this unifi payment"

    elif int(payment)==5:
        print "Maxis payment"
    else:
        p=0;
        print "you did not enter correctly" 

   if p:
       payment_pay=list_of_payment[int(payment)]
       print "you need to pay  " + str(payment_pay)
___________________
Bob Rashkin
User avatar
rrashkin
 
Posts: 35
Joined: Tue Feb 12, 2013 4:47 pm


Return to General Coding Help

Who is online

Users browsing this forum: CasualCoding.org, W3C [Linkcheck] and 5 guests