Skip to main content

Print function with different examples in detail

Print statement in python is not reserved word nor a statement. Print is built in function call which run as expression statement.

The interactive session automatically prints the results of expressions you type, you don’t usually need to
say “print” explicitly at this prompt:

>>>ethosspace = 'Testing Services'
>>>ethosspace  
' Testing Services '

So print function used in files not on interactive prompt.

Syntax
print([object, …][, sep=’ ‘][, end=’\n’][, file=sys.stdout])

print(object(s), sep=separator, end=end, file=file, flush=flush)

Items in square brackets are optional and may be omitted in a given call, and values after = give argument defaults.
In English, this built-in function prints the textual representation of one or more objects separated by the string sep and followed by the string end to the stream file.

SEP is a string inserted between each object’s text, which defaults to a single space if not passed; passing an empty string suppresses separators altogether.

END is a string added at the end of the printed text, which defaults to a \n newline character if not passed. Passing an empty string avoids dropping down to the next output line.

FILE specifies the file, standard stream, or other file-like object to which the text will be sent; it defaults to the sys.stdout standard output stream if not passed.

Here are the real time example of print function.

print function with no parameter print the empty line

>>>print()

To print blank line no need to pass any parameter by default print without any parameter prints blank line.


>>> a=9
 >>> b='Testing'
 >>> c=['Prog']
 >>> print(a,b,c)
         9 Testing ['Prog']

So while printing 3 objects print function added empty space between those three objects. So in place of empty space if we want different separator then we can use below syntax.

 >>> print(a,b,c,sep=' => ')
          9 => Testing => ['Prog']

Output is now separated with separator => which we provided.


By default, print adds an end-of-line character to terminate the output line.

>>>print ('ethosspace'); print('leading software testing provider')
        ethosspace
        leading software testing provider

So if we don’t need new line then we will use end parameter here

>>>print (‘ethosspace’,end=”); print(‘ leading software testing provider’)

ethosspace leading software testing provider

Example of variable, %d and % in print statement. Use of variable in between sentence in print statement.

>>>x=5
>>>y=8
>>>z=2 * (x+y)
>>>print('A rectangle %d by %d has a perimeter of %d units.'%(x,y,z))
A rectangle 5 by 8 has a perimeter of 26 units.

Use online free python compiler to run program from anywhere.

C Program to calculate total Body Mass Index BMI with weight and height

Body Mass Index is a simple calculation using a person’s height and weight. To calculate BMI we can use the formula BMI = kg/m2 where kg is a person’s weight in kilograms and m2 is their height in meters squared. Here is a complete C program code to calculate BMI in float value with 2 decimal places.

/* C Program to print BMI based on formula */
#include <stdio.h>
int main()
{
    float wt,ht,bmi;
    printf("\n\t Enter Weight In Kg\t");
    scanf("%f",&wt);
    printf("\n\t Enter height In Meters\t");
    scanf("%f",&ht);
    //Calculate BMI 
    bmi = wt / (ht*ht);
    if (bmi <= 18.5)
    {
        printf ("BMI Report is : %.2f -> Underweight", bmi);
    }else if(bmi <= 24.9)
    {
        printf("BMI Report is :  %.2f -> Normal",bmi);
    }
    else if(bmi >= 25 && bmi <= 29.9)
    {
        printf("BMI Report is : %.2f -> Overweight",bmi);
    }
else
   printf("BMI Report is : %.2f -> Obese",bmi);   
    return 0;
}

Output after after calculating body mass index using c program is below

Enter Weight In Kg	70
Enter height In Meters	2
BMI Report is : 17.50 -> Underweight

Programs to print different Square, rectangle in Python Language

Below program will accept width and breadth from user. We can print SOLID rectangle, need to use two for loops along with print function with end parameter.

Step 1) Accept breadth and width from user
Step 2) First for loop is to print

#Python program to print hollow rectangle, solid rectangle.
#accept width and breadth from user
width=int(input("Enter Width\t"))
breadth=int(input("Enter breadth \t"))
for i in range(0,breadth):
    for j in range(0,width):
        print("*",end="")
    print()

OUTPUT

Enter Width	5
Enter breadth 	3

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

Python Program to print hollow rectangle

This tricky program. It is important to use print function along with end parameter effectively. Here is the complete code

#Python program to print hollow rectangle
#accept width and breadth from user
width=int(input("Enter Width\t"))
breadth=int(input("Enter breadth \t"))
for i in range(0,breadth):
    for j in range(0,width):
        if (i==0 or j ==0 or i==breadth or j==width):
             print(" *",end="")
        else:
             print(" ",end="*")
    print()

Output

Enter Width	3
Enter breadth 	4
 * * *
 * * *
 * * *
 * * *

Use free online python compiler to write execute any python program.

Programs to print different Square, rectangle in C Language

Print hollow square using for loop for user input length.

Steps to build this program
1) Accept length from user
2) First for loop to iterate pointer row wise
3) second inner for loop for to iterate pointer column wise
4) IF statement to compare first and last row for printing star
5) Else condition to print star for first and last column of every row.

Here is the complete code

/* C Program to print Hollow SQUARE  */

#include <stdio.h>

int main()
{
    int i, j, len;

    // Get Length of square from user 
    printf("Enter length of square: ");
    scanf("%d", &len);
    printf("\n");
 // This for loop to change pointer row wise
    for(i=1; i<=len; i++)
    {
        //This for loop to print *
        for(j=1; j<=len; j++)
        {
            //condtion to print all star for first and last line
            //Also to print first and last star of evey line
            if (i==1 || i == len || j ==1 || j == len)
            {
                printf(" *");
            } 
            //this else part to print blank for rows between 1 and n
            else
            {
                printf("  ");
            }
        }
        printf("\n");
    }
    return 0;
}

Output

Enter length of square: 8

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

Printing spaces can be handled. By providing extra spaces in print statement we can print suitable hollow square


Print Hollow square using While Loop

/* C Program to print Hollow SQUARE   */

#include <stdio.h>

int main()
{
    int i=1, j=1, len;

    // Get Length of square from user 
    printf("Enter length of square: ");
    scanf("%d", &len);
    printf("\n");
 // This while loop to change pointer row wise
    while (i<=len)
    {
        //This while loop to print star column wise
        j=1;
        while (j<=len)
        {
            //condtion to print all star for first and last line
            //Also to print first and last star of evey line
            if (i==1 || i == len || j == 1 || j == len)
            {
                printf("*");
            } 
            //this else part to print blank for rows between 1 and n
            else
            {
                printf(" ");
            }
            j++;
        }
        printf("\n");
        i++; 
    }
   
    return 0;
}

Output

Enter length of square: 5
*****
*   *
*   *
*   *
*****

Program to print rectangle by accepting width and breadth.

Print hollow square using while loop for user input width and breadth.

Steps to build this program
1) Accept width and breadth from user
2) First while loop to iterate pointer breadth (row) wise
3) Second inner while loop for to iterate pointer width (column) wise
4) IF statement to compare first and last row for printing star
5) Else condition to print star for first and last column of every row.

Here is the complete code

/* C Program to print rectangle based on user input */

#include <stdio.h>

int main()
{
    int i=1, j=1;
    int breadth,width;

    // Get Length of square from user 
    printf("Enter width square: ");
    scanf("%d", &width);
    printf("Enter breadth square: ");
    scanf("%d", &breadth);
    printf("\n");
 // This while loop to change pointer row wise
    while (i<=breadth)
    {
        //This while loop to print star column wise
        j=1;
        while (j<=width)
        {
            //condition to print all star for first and last line
            //Also to print first and last star of evey line
            if (i==1 || i == breadth || j == 1 || j == width)
            {
                printf("*");
            } 
            //this else part to print blank for rows between 1 and n
            else
            {
                printf(" ");
            }
            j++;
        }
        printf("\n");
        i++; 
    }
   
    return 0;
}

Output

Enter width square: 5
Enter breadth square: 3
*****
*   *
*****

In case if we want to change spacing between rows and column then we need to add more spaces in print statement available in while statement.


Program to print solid rectangle or square based on user input.

  1. Accept width and height from user
  2. Write first while loop to print star row wise
  3. Write second inner while loop to print star column wise
/* C Program to print solid rectangle  */
#include <stdio.h>
int main()
{
    int i=1, j=1;
    int breadth,width;

    printf("Enter width square: ");
    scanf("%d", &width);
    printf("Enter breadth square: ");
    scanf("%d", &breadth);
    printf("\n");
 // This while loop to change pointer row wise
    while (i<=breadth)
    {
        //This while loop to print star column wise
        j=1;
        while (j<=width)
        {
            printf ("*");
            j++;
        }
        printf("\n");
        i++; 
    }
   
    return 0;
}

OUTPUT

Enter width square: 6
Enter breadth square: 4
******
******
******
******

Program to identify and print perfect number in C Language

This C Program is for to identify perfect number. Here program is accepting range up to which need to identify perfect number. Perfect number is  a perfect number is a positive integer that is equal to the sum of its positive divisors, excluding the number itself. for example 6 where it is divisible for 1, 2, 3 so sum of it is 6. To write this program we have used two for loop along with simple if condition.

// Program to find perfect number
#include <stdio.h>

int main() {
    // Write C code here
    int rangeNo,counterNo,perSum;
  
    printf("\n\tEnter Range to find perfect number \t");
    scanf("%d",&rangeNo);
   //Loop to find divisible numbers 

    for (int i = 1;i<=rangeNo;i++)
    {
        perSum=0;
          for (int j = 1;j<i;j++)
            {
                if (i%j == 0)
                perSum = perSum + j;
             }
            if (perSum == i)
            printf("\n\t %d is perfect number ",i);
    }
    return 0;
}

Output

Enter Range to find perfect number 	10000
6 is perfect number 
28 is perfect number 
496 is perfect number 
8128 is perfect number 

Program to find number divisible by 3 or 5 in python

To find number divisible by 3 or 5 we have accepted user input. Used for loop and mod operator with If condition.

#Program to find numbers divisible by 3 or 5

rangeNo = int(input("\n\tEnter number upto which you need to find number divisible by 3 or 5\n\t"))

#Loop to print numbers divisible by 3
print('\n\nThese numbers are divisible by 3 upto %d'%rangeNo)
for i in range(1,rangeNo+1) :
    if (i%3 ==0):
        print("\t%d"%i)
        
#Loop to print numbers divisible by 5
print('\n\nThese numbers are divisible by 5 upto %d'%rangeNo)
for i in range(1,rangeNo+1) :
    if (i%5 ==0):
        print("\t%d"%i)

Output

Enter number upto which you need to find number divisible by 3 or 5
	10
	These numbers are divisible by 3 upto 10
	3
	6
	9


These numbers are divisible by 5 upto 10
	5
	10

Number divisible by 3 or 5 in C Language

This C Program will accept number accept range from user and then print numbers which are divisible by 3 or 5.

In this program we have accepted range from user. After that using mod operator and for loop we are printing numbers which are divisible by 3 or 5. Compile and Run below program to get the output.

#include <stdio.h>

int main() {
 
    int rangeNo;
    printf("Enter number upto which you need to find number divisible by 3 or 5");
    scanf("%d",&rangeNo);
    //Loop to print number which are divisible by 3
    printf("\n\nThese numbers are divisible by 3\n\n\t\t");
    for (int i = 1;i<=rangeNo;i++)
    {
        
        if (i%3==0)
        printf("\t%d",i);
    }
    printf("\n\nThese numbers are divisible by 5\n\n\t\t");
    for (int i = 1;i<=rangeNo;i++)
    {
        
        if (i%5==0)
        printf("\t%d",i);
    }
    return 0;
}

Output

Enter number upto which you need to find number divisible by 3 or 5300
These numbers are divisible by 3

			3	6	9	12	15	18	21	24	27	30	33	36	39	42	45	48	51	54	
57	60	63	66	69	72	75	78	81	84	87	90	93	96	99	102	105	108	
111	114	117	120	123	126	129	132	135	138	141	144	147	150	153	156	159	162	
165	168	171	174	177	180	183	186	189	192	195	198	201	204	207	210	213	216	
219	222	225	228	231	234	237	240	243	246	249	252	255	258	261	264	267	270	273	276	279	282	285	288	291	294	297	300

These numbers are divisible by 5

			5	10	15	20	25	30	35	40	45	50	55	60	65	70	75	80	85	
90	95	100	105	110	115	120	125	130	135	140	145	150	155	160	165	170	175	
180	185	190	195	200	205	210	215	220	225	230	235	240	245	250	255	260	265	
270	275	280	285	290	295	300

Online C Compilers easy to debug and run

Online C compilers provide facility to code from anywhere and run it. There are many online compilers available online but here is the one which is more useful and tested.

  1. OnlineGDB
  • This compile program in C , Turbo C as per option we select.
  • Editor provide to copy and paste the code. We can type new code and after that run and debug it.
  • This online code compiler provide facility to share written program.
  • User can pass command line arguments as well.
  • Facility to organize written code in tabular format.
  • Three different editor mode are provided like normal, Emacs, VIM.
  • It takes no time to return program output
  • facility to save program, projects by signing up.
  • Easy to share and Embed written code to any other website.

Online GDB complier is useful for languages like C, C++, Python, Java, PHP, C#, HTML, CSS, RUBY, PERL, Pascal, R, Fortran, Haskell, SQLite, Prolog, Swift, Rust, Go, Bash.

Other compilers which are available and also useful are

2) Programiz

3) Tutorialspoint

4) Onecompiler

5) Jdoodle

calculate cube of numbers in python using while, for loop

Here is simple three line program to calculate cube and print it as per user input or range using while loop

#Program to find cube of numbers
#taking input from user till how many numbers user want to print cube
rangeNo=int(input("enter upto which number you want to print cube\t"))

i = 1;
while i <= rangeNo:
    cubeNo = 0
    cubeNo = i * i * i
    print("cube of %d is ===>   %f"  %(i,cubeNo))
    i=i+1

Output

enter upto which number you want to print cube	5
cube of 1 is ===>   1.000000
cube of 2 is ===>   8.000000
cube of 3 is ===>   27.000000
cube of 4 is ===>   64.000000
cube of 5 is ===>   125.000000

Below program is to calculate cube of numbers using for loop up to number (user input)

#Program to find cube of numbers
#taking input from user till how many numbers user want to print cube
rangeNo=int(input("enter upto which number you want to print cube\t"))

j = 1;
for i in range(j,rangeNo+1):
    cubeNo = 0
    cubeNo = i * i * i
    print("cube of %d is ===>   %f"  %(i,cubeNo))

Output

enter upto which number you want to print cube	5
cube of 1 is ===>   1.000000
cube of 2 is ===>   8.000000
cube of 3 is ===>   27.000000
cube of 4 is ===>   64.000000
cube of 5 is ===>   125.000000