簡體   English   中英

當用戶在python 2.7中輸入字符串時,如何防止出現此錯誤?

[英]How can I prevent this error from coming up when the user enters a string in python 2.7?

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

在Python 3之前, input嘗試將輸入評估為Python表達式。 如果鍵入j ,它將嘗試查找名稱j ,但失敗。

請使用raw_input ,它不執行該評估,而是返回一個字符串:在這種情況下,您需要更改if條件以測試字符串:

if x == '1':

...等等。

然后,對於其他input()調用,您可以執行相同的操作,然后將要轉換為浮點的字符串轉換為:

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

當然,如果用戶輸入非數字數據,那可能會失敗,這確實是錯誤情況。 您可以將其放在try塊中並處理該錯誤情況。

查看在repl.it上運行的更正腳本

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM