In this program, we will print the hello world on the output screen. We will be using the built-in print() function.
We also used # symbol to use comments in python to tell what that particular statement does.
We will print it in two different ways so that we can learn more about print() function and also about python language.
Print hello world on separate lines
Using two print() function
Here to print it on separate lines we will use two different print() function, one to print hello and other to print world.
Code:
1 2 3 4 5 | # prints hello world on separate line print("hello") print("world") |
Using one print() function
We can achieve this by using one print() function. We use sep parameter of print() function. This parameter decides how the arguments passed in print() function be separated, by default they are separated by space.
And there is one more way of doing this. We can just include the newline(\n) character in between hello and world.
1 2 3 4 5 | # prints hello world on separate lines using one print() function print("hello","world",sep="\n") print("hello\nworld") |
Printing hello world on the same line
Now to print it on the same line, we can use one print() function and also with two print() function. Let’s discuss both the ways.
Using one print() function
In this, we can just pass the text inside the print() function
Code:
1 2 3 4 5 | # prints hello world on the same line print("hello world") # passing as single argument print("hello","world") # passing as two arguments |
Using two print() function
If we can get it done by using one print() function then why we have to use two print() function? Yes, we can but my aim is to get you know more about print() function so that you will be able to perform other tasks in further python programs. Now let’s discuss the other way.
So, to accomplish this we will learn about other parameter of print() function i.e end. This parameter decides how the print() function is going to be ended. By default it ends with newline(“\n”). So, in this case, we will end the first print() function with space.
Code:
1 2 3 4 5 | # prints hello world on the same line print("hello",end=" ") print("world") |