Python

champak
₹2,000.00 ₹1,500.00
The Python Programming Language at Champak's World
  • 15 students
  • 22 lessons
  • 0 quizzes
  • 10 week duration

Python

How to use the Print function in Python?

Print is now a function in Python and not a statement. This means we will have to write print(x) everytime and not just print x.

The simplest way of printing is to write:
print (“Have a crackerful Deepawali”)
print in python

print can handle multiple items like this: print(x1,x2,x3)
To print variables we would write something like:
s1=”A=”
a=10
print (s1,a)
print in python

Every print statement is ended by a newline “\n”
Thus writing three print statements would print them all in different lines.

print(“one”)
print(“two”)

print(“three”)
print in python

To override this default behavior we need to define the the end variable.

print(“one”,end=””)
print(“two”,end=”:”)
print(“three”)
print(“four”)
The output should be self explanatory.
print in python

By default print elements are separated by spaces. This can be changed by defining the sep variable.
print(1,2,3,4)
print in python

print(1,2,3,4,sep=”,”)
This will print with separators being the comma.
print in python

Then we can have printing using format specifiers like printf in C.

Format Strings
1. %d stands for signed integer, so does %i
print(“%4d”% 10)
print(“%4d”% 110)
print in python

Next, we will learn the format function.

The format function in Python is used in this manner.
1. print(“{0} + {1} = {2}”.format(2,3,2+3 ))
The {}’s  are used as placeholders. Then the given data is fed at the given positions.
Input
print(“{0} + {1} = {2}”.format(2,3,2+3 ))
Output
2 + 3 = 5

Input
print(“{0} + {0} = {1}”.format(2,2+2 ))
Output
2 + 2 = 4

Input
print(“{1} = {0} + {0}”.format(2,2+2 ))
Output
4 = 2 + 2

Specifying width:
Consider the following 2 statements:
print(“{0} X {1} = {2}”.format(9,1,9*1 ))
print(“{0} X {1} = {2}”.format(9,2,9*2 ))

This is manual  field numbering.

Then we can have automatic field numbering and width:
Input
print(“{:04d} X {:04d} = {:04d}”.format(9,1,9*1 ))
print(“{:04d} X {:04d} = {:04d}”.format(9,2,9*2 ))
Output
0009 X 0001 = 0009
0009 X 0002 = 0018
:04d will feed zeroes if data less than 4.
What happens if data size is more than 4.
Input
print(“{:04d} X {:04d} = {:04d}”.format(9,1,9*1 ))
print(“{:04d} X {:04d} = {:04d}”.format(9,2,9*10000 ))
Output
0009 X 0001 = 0009
0009 X 0002 = 90000

The repeat character can be changed:
print(“{:4d} X {:4d} = {:4d}”.format(9,1,9*1 ))
print(“{:4d} X {:4d} = {:4d}”.format(9,2,9*100 ))
This will fill with space.
9 X 1 = 9
9 X 2 = 900

Using variable names:
Input
print(“a={a:4d},b={b:4d}”.format(b=9,a=6))
Output
a= 6,b= 9

 

 

 

Assignments

  1. Print
    *
    **
    ***
    ****
  2. Print s=s(s-a)*(s-b)(s-c)
  3. Print My Name is Champak and I live in Varanasi. The program should show your name and address.

Leave a Reply

Your email address will not be published. Required fields are marked *