2

Im trying to check the length of the string entered by the user and if its < 5 it goes through however no matter what length it still goes through my try except statement

print """ Please put in the Stock symbol for the Company whose last closing stock price you wish to see."""

while True:
   symbol = raw_input("Enter Stock Symbol: ")
   try:
      len(symbol) < 5
      break

   except ValueError:
      print 'Greater than 4 characters, Try again'

print 'Great your stock symbol is less than 5'
Neil
  • 211
  • 1
  • 6
  • 13

2 Answers2

6

You don't need a try/except:

while True:
   symbol = raw_input("Enter Stock Symbol: ")
   if len(symbol) > 4:       
      print 'Greater than 4 characters, Try again'
   else:
       print 'Great your stock symbol {} is less than 5'.format(symbol)
       break


In [3]: paste
while True:
   symbol = raw_input("Enter Stock Symbol: ")
   if len(symbol) > 4:       
      print 'Greater than 4 characters, Try again'
   else:
       print 'Great your stock symbol {} is less than 5'.format(symbol)
       break

## -- End pasted text --
Enter Stock Symbol: FOOBAR
Greater than 4 characters, Try again
Enter Stock Symbol: YHOO
Great your stock symbol YHOO is less than 5

In your code:

try:
    len(symbol) < 5 # always checks len
    break # always breaks
except ValueError:

You would use a try/except if for instance you wanted to cast the input to an int catching a ValueError there but it is not applicable in your case.

Padraic Cunningham
  • 176,452
  • 29
  • 245
  • 321
0

You must first call (TypeError or ValueError or ..Error) in try section in the if statement, and decide what to do with this error in the except section. More information: here

while True:
    name = input (': ')
    try:
        if (len (name) >= 4):
            raise ValueError()
            break
    except ValueError:
        print ('Account Created')
    else:
        print ('Invalid Input')