Most of the people start their python journey using print(). Print function seems to be simple and easy-go thing where whatever you put in Strings gets printed !
But print function is not that simple as we can even use it for file handling and other things also.
Print Function Syntax
print(object(s), sep=separator, end=end, file=file, flush=flush)
We will be focusing on first 4 arguments Object, sep, end and file.
In python everything is an object and print() allow any number and any type of objects and prints the value depending on the arguments. It will be converted to string before printing.
print( “Learning print function”, 2, 2.789, 0+0J )OUTPUTLearning print function 2 2.789 0j
In print() there is a default seperator and it is empty space. We can change it as per our wish. Default value of sep is “”
print( "Learning","print","function" ) # sep=""print( “Learning”, “print”, “function” , sep=”-” )OUTPUTLearning print function
Here in the first print the sperator is taking space by default. In the second print we explicitly mentioned our sep argument to see a different output.
In python print function default value of end is the new line character.
print(“second”)print("Learning", end = ' something ')
Learning something with print
Here we see that an empty print() creates a blank line. That's because in python every print function by default has a new line argument at the end. We can easily change this as per our need.
sourceFile = open(‘my_file.txt’, ‘w’)print(‘Pretty cool, huh!’, file = sourceFile)sourceFile.close()
The first line creates a text file names my_file in write mode. After this we can start writing using our print function easily. The file location will depend on your editor, so search in that area where your editor saves file.
Thats all !
Happy learning !!