CSC111 robust input.py

From CSclasswiki
Jump to: navigation, search

--Thiebaut 17:31, 19 April 2009 (UTC)


# robustInput.py
# D Thiebaut
# example of while loops for getting
# inputs from the user in a manner that
# is robust and rejects obviously wrong data


def getBirthMonthDay():
    # gets the month and day the user was born on
    # checks for validity of input
    
    month = raw_input( "What month were you born in? " )
    # capitalize and keep first 3 l5etters only
    month = month.capitalize()[:3]
    while month not in [ "Jan", "Feb", "Mar", "Apr", "May", "Jun",
                         "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" ]:
        print "%s is not a valid month" % ( month )
        month = raw_input( "Please enter the month you were bon in: " )
        month = month.capitalize()[:3]

    # get the day of the month.  Note the different approach
    # with the while loop
    while True:
        day = input( "What day of the month? " )
        if day >=1 and day <= 31:
            break
        # otherwise get day again
        print "%d is not a valid day" % ( day )

    return month, day


def getSign():
    # gets the user sign
    sign = raw_input( "What is your astrological sign? " ).capitalize()
    while sign not in [ "Aries", "Taurus", "Gemini", "Cancer", "Leo",
                        "Virgo", "Libra", "Scorpio", "Sagittarius",
                        "Capricorn", "Aquarius", "Pisces" ]:
        print "%s is not a recognized sign" % ( sign )
        sign = raw_input( "Please re-enter your sign: " ).capitalize()

    return sign
    
    
def main():
    month, day = getBirthMonthDay()
    sign = getSign()

    print "\n\nYou were born on %s, %d." % ( month, day )
    print "Your sign is %s." % ( sign )

main()