Hi guys,
We know that the "print" function
is used to print the data to the standard output device in Python
Programming language. But, the print function automatically adds a newline
character every time we cal it.
For example, consider a program segment to
display numbers from 1 to 5:
for n in range(1,6):
print n
print n
The output of the code will be:
1
2
3
4
5
But what if we want the output
to be something like:
1 2 3 4 5
How do we go about it?
The answer to this is indeed
very simple. The key is to add a "," after the variable
at the end of the print
statement. Consider the following code to print the even and
odd numbers in the given range, to illustrates the technique:
#-*-*-*-*-*-*-*-*- CODE
BEGINS -*-*-*-*-*-*-*-*-*-*-
limit = int(input("Enter the maximum limit\n"));
print"The Even numbers in the given range are:\n"
for i in range(0,limit,2):
print i
print"\nThe odd numbers in the given range are:\n"
for j in range(1,limit,2):
print j,
print"The Even numbers in the given range are:\n"
for i in range(0,limit,2):
print i
print"\nThe odd numbers in the given range are:\n"
for j in range(1,limit,2):
print j,
#-*-*-*-*-*-*-*-*- CODE
ENDS -*-*-*-*-*-*-*-*-*-*-
The output of the above code is:
Enter the maximum limit
10
The Even numbers in the given range are:
0
2
4
6
8
The odd numbers in the given range are:
1 3 5 7 9
So as we can see, the "," added after j helps us to
print the odd numbers in the
horizontal fashion.
And also, please not that the range() function can take two or three
parameters.
Hence the range() function is polymorphic in nature.
I'll be posting more about the range() and xrange() functions in another
post of mine.
I hope you like this post. Please do leave your valuable comments below.
Thank you very much.
Comments
Post a Comment