Can't figure out how to print horizontally in python?

前端 未结 3 2107
一向
一向 2020-12-07 04:23

I need to print this code:

for x in range (1, 21):  

    if x%15==0:
        print(\"fizzbuzz\")

    elif x%5==0:
        print(\"buzz\") 
    elif x%3==0:         


        
相关标签:
3条回答
  • 2020-12-07 04:59

    A '\n' character is written at the end, unless the print statement ends with a comma.

    http://docs.python.org/2/reference/simple_stmts.html

    0 讨论(0)
  • 2020-12-07 05:11

    do this and it will print all on one line:

    for x in range (1, 21):  
    
        if x%15==0:
            print ("fizzbuzz"),
    
        elif x%5==0:
            print ("buzz"), 
        elif x%3==0:
            print ("fizz"),
    
        else:
            print (x),
    

    it will print like this:

    1 2 fizz 4 buzz fizz 7 8 fizz buzz 11 fizz 13 14 fizzbuzz 16 17 fizz 19 buzz

    0 讨论(0)
  • 2020-12-07 05:16

    Two options:

    Accumulate a result string and print that at the end:

    result = ""  
    for x in range (1, 21):  
    
        if x%15==0:
            result = result + "fizzbuzz "
    
        etc...
    print result
    

    Or tell Python not to end the printed string with a newline character. In Python 3, which you seem to be using, you do this by setting the end argument of the print function, which is "\n" (a newline) by default:

    for x in range (1, 21):  
    
        if x%15==0:
            print("fizzbuzz",end=" ")
    
        etc...
    

    Historical note: In Python 2, this could be achieved by adding a comma at the end of the print statement; print "fizzbuzz",

    0 讨论(0)
提交回复
热议问题