2009-12-15 77 views
1

我只是要張貼那裏的問題是,該程序沒有錯誤(所有的代碼是除了這個raw_input問題有效)蟒蛇的raw_input高清輸入問題

search_function(1)和等,並測試了部分有效。

但是,如果我這樣做while循環,它不會打印任何東西。 輸出示例:

輸入一個數字打印特定表, 或STOP退出:2輸入數字,以 打印特定的表,或STOP退出: 2輸入一個數字打印特定 表,或STOP退出:1輸入 號碼打印特定的表,或STOP 退出:輸入一個數字打印 特定的表,或STOP退出:1 輸入一個數字打印特定表, 或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: ") 

回答

1

試驗x == 'STOP'第一和break如果真,否則強制轉換爲int並調用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)) 
+0

謝謝,我用它。這很好 – CppLearner 2009-12-15 15:34:30

2

raw_input()返回字符串,而你的代碼期望整數。使用search_function(int(x))或更改條件以與字符串進行比較。

+0

謝謝你的提示。但是,使用raw的一個原因是識別輸入STOP,但因爲它是int,所以它只是返回一個錯誤。對我的目的來說很好,但只是想知道,除此之外還有其他選擇嗎? 我可以創建一個額外的if/else語句,但請int,只是在它返回錯誤之前返回錯誤 – CppLearner 2009-12-15 14:03:40

+0

是的,有替代(引用):「或更改條件以與字符串進行比較」,即更改'x = = 1'到'x =='1''等。但是將'int'傳遞到'search_function()'不會導致錯誤,因爲與「STOP」的比較是外部函數。 – 2009-12-15 14:40:18

+0

呃好主意。 :)非常感謝 – CppLearner 2009-12-15 15:35:03