如果输入是字符串并且需求是整数,我该如何处理

时间:2013-10-21 12:27:37

标签: python

Error: Error: if n == 0 or n>4: 
UnboundLocalError: local variable 'n' referenced before assignment. 

尝试过isdigit方法,但似乎无法正常工作。问题是什么?

#!usr/bin/python
import sys
class Person:

    def __init__(self, firstname=None, lastname=None, age=None, gender=None):
        self.fname = firstname
        self.lname = lastname
        self.age = age
        self.gender = gender



    def display(self):
        found = False

        n1 = raw_input("Enter for Search Criteria\n1.FirstName ==  2.LastName ==     3.Age == 4.Gender : " )

        print "Not a valid input"
        if n1.isdigit():
            n = int(n1)
        else:
            print "Enter Integer only" 

        if n == 0 or n>4:
            print "Enter valid search "

        if n == 1:
            StringSearch = raw_input("Enter FirstName :")
            for records in list_of_records:
                if StringSearch in records.fname:
                    found = True
                    print records.fname, records.lname, records.age, records.gender

            if not found:
                print "No matched record"

        if n == 2:
            StringSearch = raw_input("Enter LastName :")
            for records in list_of_records:
                if StringSearch in records.lname:
                    found = True
                    print records.fname, records.lname, records.age, records.gender

            if not found:
                print "No matched record"

        if n == 3:
            StringSearch = raw_input("Enter Age :")
            for records in list_of_records:
                if StringSearch in records.age:


        if not found:
            print "No matched record"

        if n == 4:
            StringSearch = raw_input("Enter Gender(M/F) :")
            for records in list_of_records:
                if StringSearch in records.gender:
                    found = True
                    print records.fname, records.lname, records.age, records.gender

            if not found:
            print "No matched record"



f= open("abc","r")
list_of_records = [Person(*line.split()) for line in f]
#for record in list_of_records:


for per in list_of_records:
    per.display()

请问如何解决这个问题?

3 个答案:

答案 0 :(得分:4)

好的,你做错了。

首先,raw_input将始终为您提供一个字符串。

所以你需要将它转换成整数。但是,您在代码中可能尚未存在的部分代码中使用变量n

您需要更改此部分:

    print "Not a valid input"
    if n1.isdigit():
        n = int(n1)
    else:
        print "Enter Integer only" 

对此:

    try:
        n = int(n1)
    except:
        print "Enter Integer only" 
        raise

除非您想在收到有效输入之前继续询问,否则请创建一个函数:

def get_user_int(prompt="Enter an integer: "):
    while True:
        try:
            return int(raw_input(prompt)))
        except:
            print 'Try again'

并称之为:

n = get_user_int("Enter choice for Search Criteria\n - 1.FirstName\n - 2.LastName\n - 3.Age\n - 4.Gender\n> ")

答案 1 :(得分:0)

n = 0
if n1.isdigit():
    n = int(n1)
else:
    """If the execution comes here (not n1.isdigit())
    the variable `n` will remain undefined.
    Therefore you should define it in this block or before if,
    say initially setting it to zero.

    """

    print "Enter Integer only" 

http://codepad.org/5PNWnDrN

另一种方法:

try:
    n = int(n1)
except ValueError, TypeError:
    n = 0

http://codepad.org/JEdXO9dz

答案 2 :(得分:-1)

在设置n的值之前,您正在测试n ==某些条件。只需将其初始化为零或其他任何默认值。

def display(self):
        found = False
        n = 0