Python raw_input 和 input 问题

1 投票
2 回答
1917 浏览
提问于 2025-04-15 17:02

我只想发出问题的部分,这个程序没有错误(除了这个 raw_input 的问题,其他代码都是有效的)

我用 search_function(1) 等测试过,结果是正常的。

但是如果我这样做一个循环,它就什么都不打印。 示例输出:

请输入一个数字以打印特定的表格,或者输入 STOP 退出:2 请输入一个数字以打印特定的表格,或者输入 STOP 退出:2 请输入一个数字以打印特定的表格,或者输入 STOP 退出:1 请输入一个数字以打印特定的表格,或者输入 STOP 退出: 请输入一个数字以打印特定的表格,或者输入 STOP 退出:1 请输入一个数字以打印特定的表格,或者输入 STOP 退出: 请输入一个数字以打印特定的表格,或者输入 STOP 退出:STOP

def search_function(x):
    if x == 1:
        for student in students:
            print "%-17s|%-10s|%-6s|%3s" % student.print_information()
        print '\n'

    if x == 2:
        print "%-17s|%-10s|%s" %(header[0],header[1],header[4])
        print "-" * 45
        for student in students:
            print "%-17s|%-10s|%s" %student.print_first()
        print '\n'
        print "Simple Analysis on favorite sports: "
        # Printing all sports that are specified by students
        for s in set(Student.sports): # class attribute
            print s, Student.sports.count(s), round(((float(Student.sports.count(s)) / num_students) *100),1)

        # Printing sports that are not picked 
        allsports = ['Basketball','Football','Other','Baseball','Handball','Soccer','Volleyball','I do not like sport']
        for s in set(allsports) - set(Student.sports):
            print s, 0, '0%'
        choice_list = Student.sports
        for choice in choice_list:
            choice_dict[choice] = choice_dict.get(choice, 0) + 1
        print max(choice_dict)
        print min(choice_dict)

    elif x == 3:
        print "%-17|%-10s|%-16s|%s" %(header[0],header[1],header[5],header[6])
        print "-" * 45
        for student in students:
            print "%-17s|%-10s|%-16s|%s" % student.print_second()
        print '\n'

    elif x == 4:
        print "%-17s|%-10s|%s" %(header[0],header[1],header[7])
        print "-" * 45
        for student in students:
            print "%-17s|%-10s|%s" %student.print_third()
        print '\n'

    elif x == 5:
        print "%-17s|%-10s|%-15s|%s" %(header[0],header[1],header[8],header[9])
        print "-" * 45
        for student in students:
            print "%-17s|%-10s|%-16s|%s" % student.print_fourth()
        print '\n'

x = raw_input("Enter a number to print specific table, or STOP to quit: ")
while x != 'STOP':
    search_function(x)
    x = raw_input("Enter a number to print specific table, or STOP to quit: ")

2 个回答

2

raw_input() 返回的是字符串类型,而你的代码需要的是整数类型。你可以用 search_function(int(x)) 来把字符串转换成整数,或者把条件改成和字符串比较。

1

首先检查一下 x == 'STOP' 是否为真,如果是,就执行 break,也就是跳出循环。如果不是,就把 x 转换成整数,然后调用 search_function 函数:

while True:
    x = raw_input("Enter a number to print specific table, or STOP to quit: ")
    if x == 'STOP':
        break
    search_function(int(x))

撰写回答