python 3 print function

给你一囗甜甜゛ 提交于 2019-12-25 03:22:47

问题


So I want to print this:

*
**
***
****
*****

And my code is:

for row in range(1,6):
    for col in range(row): 
        print('*', end="")
    print('')

My question is about print function, since it includes new line. Knowing some C before, I just can't figure it out what the last print('') does, and why my code doesn't work without it.


回答1:


The end='' parameter to the first call to print suppresses printing a newine after the *, and the second call to print prints only a newline.




回答2:


The extra print line is shorthand for print(end='\n')




回答3:


Since you know C, here's your program in C. You can see that your code prints one character at a time and the "empty" print call results in a newline being printed.

#include <stdio.h>

int main() {
    for (int row = 1; row < 6; row++) {
        for (int col = 0; col < row; col++)
            putchar('*');
        putchar('\n');
    }
}



回答4:


By default python’s print() function ends with a newline. A programmer with C/C++ background may wonder how to print without newline.

Python’s print() function comes with a parameter called ‘end’. By default, the value of this parameter is ‘\n’, i.e. the new line character. You can end a print statement with any character/string using this parameter.

print("Python" , end = '@')  
print("Shubham")

Output: Python@Shubham



来源:https://stackoverflow.com/questions/54546056/python-3-print-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!