0
loop =1
while loop==1:
    x = input('Enter 1 for CI, 2 for SI, 3 for Area of cylinder and 4 for area of circle:')

    if x==1:
        from math import*
        p = input('Enter Principal: ')
        r = input('Enter rate: ')
        n = input('Enter number of years: ')
        CI = p*pow((1+r),n)
        print 'The Compound Interest is:', CI
        print '\n'
    elif x==2:
        from math import*
        p = input('Enter Principal: ')
        r = input('Enter rate: ')
        n = input('Enter number of years: ')
        SI = (p*n*r)/100.0
        print 'The Simple Interest is:', SI
        print '\n'
    elif x==3:
        from math import*
        r = input('Enter radius of cylinder: ')
        h = input('Enter height of cylinder: ')
        A= 2*pi*r*(h+r)
        print 'The Area of Cylinder is:', A
        print '\n'

    elif x==4:
        from math import*
        r = input('Enter radius of circle:')
        A = pi*r*r
        print 'The Area of circle is:', A
        print '\n'

    else:
        print 'Enter 1,2,3 or 4:'

This is the error when user enter a string

Traceback (most recent call last):
   line 3, in <module>
    x = input('Enter 1 for CI, 2 for SI, 3 for Area of cylinder and 4 for area of circle:')
  File "<string>", line 1, in <module>
NameError: name 'j' is not defined
Jon Clements
  • 138,671
  • 33
  • 247
  • 280
T.Ewor
  • 1
  • You want to use `raw_input` and then explicitly try and convert the values to the appropriate type, eg: `r = float(raw_input('Enter radius of circle: '))` – Jon Clements Feb 19 '17 at 09:00
  • I tried something like that and it didn't work. if the user enter a string i need it to prompt the user to enter 1,2,3 or 4 something like: elif isinstance(x,str): print 'invalid input' – T.Ewor Feb 19 '17 at 09:06

1 Answers1

2

Before Python 3, input tries to evaluate the input as a Python expression. If you type j, then it will try to find the name j, which fails.

Use raw_input instead, which does not do that evaluation, but returns a string: in that case you need to change your if conditions to test for a string:

if x == '1':

...etc.

Then for the other input() calls you could do the same, and then convert the string you get to float with:

p = float(raw_input('Enter Principal: '))

Of course, that could fail if the user enters non numerical data, which really is an error condition. You could put that in a try block and treat that error condition.

See the corrected script run on repl.it

Community
  • 1
  • 1
trincot
  • 317,000
  • 35
  • 244
  • 286