1

I need to input some error handling into my program. My program takes a line of text from the user but this text should only contain letters and spaces. I have tried to input some error handling but I want to improve it. When the user enters something other than a letter or space I print an error message but the code underneath is still executed. When the user enters something that is not a letter or space I want the error message to be printed and the program to terminate.

print ""

# To God be the Glory

text = raw_input("Please enter a line of text: ")
text_lower = text.lower()

I want my error handling to be inputted around here such that if the user enters something that is not a letter or space the program will print the error message and the user will not be asked for a key.

print ""
key = int(input("Please enter a key: "))


def ascii_func (text) :

This is the error handling method I attempted it recognises if there is incorrect input but still executes the code underneath it.

    for charc in text_lower:
        if charc not in ["a","b","c","d","e","f","g","h","i","j","k","l","m","n",\
    "o","p","q","r","s","t","u","v","w","x","y","z"," "]:
        print "Error input is not correct"
        break

    result = ''

    print ""

    for charc in text:


        if charc != " " :
            charc = ord(charc)
            charc = (charc - 97) + key
            charc = (charc % 26)
            charc = charc + 97
            charc = chr(charc)

        result += charc

    print result

ascii_func(text)           
jayoguntino
  • 133
  • 1
  • 7

2 Answers2

1

break only exits the for loop. Not the program or function. You could either use return to exit the function, or, if you'd rather halt the script entirely, you could use one of the options shown here.

Community
  • 1
  • 1
cheniel
  • 3,473
  • 1
  • 14
  • 15
0

A fairly simply way to do this is as below.

fail = False
for charc in text_lower:
    if charc not in acceptable list:
        fail = True
        print "bad input"
        break

if not fail:
    #rest of your code goes here

Much nicer ways exist. For example, you should read up on try... except.

For your purposes, probably the cleaner way is

import sys
for charc in text_lower:
    if charc not in acceptable list:
        sys.exit("bad input")
#rest of your code.
Joel
  • 22,598
  • 6
  • 69
  • 93