Tuesday, February 08, 2011

Python Basics: Built-in function Print usage

Before embarking on a journey to learn any programming language most people create a sample Hello World application to see how the language works. Today we are going to learn this only with a variation of how you use it's in-built print function.

So, Let's get started.
I'll be using vim to write programs and python 3.2 to run it. If you are using windows prefer python IDLE which comes bundled with python.

1. Source Code: Vim 












Explanation:
1. The first line of the code is called the shebang line
2. Line 2 is a comment.
3. Line 4 uses the built-in print function to print the string on the standard output on screen.
4. Line 5 uses a variation of the function.
5. Line 7 is a comment
6. Line 9 has nothing special
7. from Line 10 onwards it shows you the variation of how to use the print function.
Before i explain you line no 10, 11 and 12 i want you to look at the definition of the function itself.
print([object...][, sep=' '][, end='\n'][, file=sys.stdout])
sep and end keyword arguments take a string and if nothing is given the defaults are taken and for last file keyword takes a file object and how it works is explained in Line 12. You might have noticed the output. It doesn't print out line 12 on the screen instead it writes that line to a file specified pybuf.txt. Here, open function returns you a file object and it is defined as follows.
open(filename, mode)
Both of them are strings. I'll explain open function later in detail except the filename is name of the file to be created if not existed and mode is set to 'a' which means append text to the end of a file.

2. Output: Python 3.2












3. pybuf.txt file





0 comments:

Post a Comment