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
4

1 に答える 1

2

Add an empty print after the loop:

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

This will print the extra newline you need.

Alternatively, use str.join(), map() and str() to create a new space-separated string from the numbers, printing that with the newline:

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

and

print(' '.join(map(str, range(1,50, 5))))
于 2013-10-25T00:08:00.553 に答える