Chapter 4: Input/Output Functions and Statements

Example 1.0, Page number: IOF-5

In [1]:
#Variable Declaration and Initialization
a = int(raw_input(""))
b = int(raw_input(""))

#Calculation
sum1 = a + b
product = a * b
#Since sum is a keyword in python, sum1 is used

#Output
print sum1, product
5
3
8 15

Example 1.1, Page number: IOF-6

In [2]:
#Variable initialization
a = int(raw_input("Enter Value to A : "))
b = int(raw_input("Enter Value to B : "))

#Calculation
sum1 = a + b
product = a * b
#Since sum is a keyword in python, sum1 is used

#Output
print "SUM = ",sum1,"\nPRODUCT = ", product
Enter Value to A : 5
Enter Value to B : 3
SUM =  8 
PRODUCT =  15

Example 2, Page number: IOF-10

In [8]:
import sys

#Variable Initialization
f = int(raw_input("Degree fahrenheit ? "))

#Calculation
c = 5.0/9.0 * (f-32)

#Output
sys.stdout.write("Degree centigrade = %6.2f"%(c))
Degree fahrenheit ? 105
Degree centigrade =  40.56

Example 3, Page number: IOF-10

In [14]:
import sys
import math

#Variable Initialization
a = int(raw_input("Enter three sides : "))
b = int(raw_input("Enter three sides : "))
c = int(raw_input("Enter three sides : "))

#Calculation
s = (a+b+c)/2
area = math.sqrt(s * (s-a) * (s-b) * (s-c))

#Output
sys.stdout.write("Area of Triangle = %6.2f Sq.units"%(area))
Enter three sides : 5
Enter three sides : 4
Enter three sides : 6
Area of Triangle =   6.48 Sq.units

Example 4, Page number: IOF-16

In [17]:
#Variable Initialization
ch = raw_input("Enter a character : ")

#Output
sys.stdout.write("\n\nASCII value of %c is %u"%(ch,ord(ch)))
sys.stdout.write("\nPress any key to stop...")
Enter a character : A


ASCII value of A is 65
Press any key to stop...

Example 5, Page number: IOF-16

In [18]:
import sys

#Variable initialization
sno = raw_input("Enter service number : ")
pmr = int(raw_input("\nPrevious month reading ? "))
cmr = int(raw_input("\nCurrent month reading ? "))

#Calculation
units = cmr - pmr
amt = units * 1.50

#Output
sys.stdout.write("\n    Electricity Bill")
sys.stdout.write("\n    ________________")
sys.stdout.write("\nService No. %s"%(sno))
sys.stdout.write("\nUnits Consumed : %d"%(units))
sys.stdout.write("\nElectricity Charges Rs. %0.2f"%(amt))
Enter service number : TMR65358

Previous month reading ? 4305

Current month reading ? 4410

    Electricity Bill
    ________________
Service No. TMR65358
Units Consumed : 105
Electricity Charges Rs. 157.50

Example 6, Page number: IOF-17

In [19]:
import sys

#Variable Initialization
a = int(raw_input("Enter value to A : "))
b = int(raw_input("Enter value to B : "))

#Calculation
temp = a
a = b
b = temp

#Output
sys.stdout.write("\n\nValue of A = %d"%(a))
sys.stdout.write("\nValue of B = %d"%(b))
Enter value to A : 15
Enter value to B : 250


Value of A = 250
Value of B = 15
In [ ]: