2013-10-25 73 views
0

大家好,所以我有這個代碼,我添加了(end =「」),這樣打印就會出現水平而不是垂直的默認值,但現在這帶來了一個問題。打印功能保持原有功能。循環

這是我的代碼,下面你會看到我的錯誤。

def main(): 
    print ("This line should be ontop of the for loop") 
    items = [10,12,18,8,8,9 ] 
    for i in items: 
     print (i, end= " ") 

    print("This line should be ontop of the for loop") 
    for x in range(1,50, 5): 
     print (x, end = " ") 

輸出:

This line should be ontop of the for lopp 
10 12 18 8 8 9 This line should be ontop of the for loop 
1 6 11 16 21 26 31 36 41 46 

所需的輸出:

This line should be ontop of the for loop 
10 12 18 8 8 9 
This line should be ontop of the for loop 
1 6 11 16 21 26 31 36 41 46 

回答

2

在循環後添加一個空的打印:

for i in items: 
    print (i, end= " ") 
print() 

這將打印您需要的額外的換行符。

或者,使用str.join()map()str()以形成從數的新的空間分隔的字符串,打印與換行:

items = [10, 12, 18, 8, 8, 9] 
print(' '.join(map(str, items))) 

print(' '.join(map(str, range(1,50, 5))))