当用户在Python2.7中输入字符串时,如何防止出现此错误?

2024-04-29 03:27:03 发布

您现在位置:Python中文网/ 问答频道 /正文

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:'

这是用户输入字符串时的错误

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

Tags: ofthefromimportciforinputis
1条回答
网友
1楼 · 发布于 2024-04-29 03:27:03

在python3之前,input尝试将evaluate the input作为Python表达式。如果键入j,则它将尝试查找名称j,但失败

改为使用raw_input,它不执行该计算,而是返回一个字符串:在这种情况下,您需要更改if条件来测试字符串:

if x == '1':

…等等

然后对于其他input()调用,您可以执行相同的操作,然后将得到的字符串转换为float:

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

当然,如果用户输入非数字数据,这可能会失败,这实际上是一种错误情况。你可以把它放在一个try块中,然后处理这个错误条件

请参阅在repl.it上运行的已更正脚本

相关问题 更多 >