2015-11-05 35 views
-2
def main(): 
    infile = open ('correctAnswers.txt','r') 
    correct = infile.readlines() 
    infile.close 
    infile1 = open ('studentAnswers.txt','r') 
    student = infile.readlines() 
    infile1.close 
    index=0 
    correctanswer=0 
    wronganswer=[] 
    while index<len(correct): 
     correct[index]=correct[index].rstrip('\n') 
     student[index]=student[index].rstrip('\n') 
     if correct[index]==student[index]: 
      correctanswer=correctanswer+1 
      print(index) 
      index=index+1 
     else: 
      wronganswer.append(index) 
      print(index) 
      index=index+1 
    if correctanswer>0: 
     print("Congratulations you passed the test.") 
    else: 
     print("I'm sorry but you did not pass the test") 
     print(" ") 
     print(" ") 
     print("# Correct Student ") 
     print("-----------------------") 
    for item in incorrectindex: 
     print(item+1,"  ",correctanswers[item]," ",studentanswers[item]) 

的main()格式化基本表

所以這是我執行的整個程序。它讀取我在本地的兩個文件,檢查是一名學生有足夠的正確答案來通過考試。該程序執行得很好,它產生 恭喜你通過了測試。

# Correct Student 
----------------------- 
3  A  B 
7  C  A 
11  A  C 
13  C  D 
17  B  D 

的問題是,是看上去很邋遢,請注意數字從一位數到兩位數變化跨接一個空間轉移的字母。有你這樣做特定的方式,因爲我知道我會在未來

+2

我沒有在你的代碼看到你打印該表。 –

+0

ughhhh,我很sl 012 –

+0

那回答我的問題,有沒有辦法刪除這個問題呢? –

回答

1

只看string formatting的文檔,它可以讓你控制這個碰到過這樣的問題:

>>> def formatted(x, y, z): 
     # column 1 is 10 chars wide, left justified 
     # column 2 is 5 chars wide 
     # column3 is whatever is left. 
... print "{:<10}{:<5}{}".format(x, y, z) 

>>> formatted(1, "f", "bar") 
>>> formatted(10, "fo", "bar") 
>>> formatted(100, "foo", "bar") 

輸出

1   f bar 
10  fo bar 
100  foo bar 

...保持列寬。

在你的榜樣

所以,相反的

for item in incorrectindex: 
     print(item+1,"  ",correctanswers[item]," ",studentanswers[item]) 

類似:

for item in incorrect index: 
    print("{:<5}{:<10}{}".format(item+1, correctanswers[item], studentanswers[item]) 
+0

正確,但我怎麼可以將它合併到for循環? –

+0

而不是使用'print(item + 1,「」,correctanswers [item],「」,studentanswers [item])插入手動空格來打印,使用格式化字符串和format()'方法上面的'formatted()'函數。 – bgporter