Chapter 11 : Structures

Example: 1, Page No.: 5.81

In [39]:
#Print the student number, name and marks through accessing structure elements.

#Defining Structure in class
class std:
    no=0
    name = ''
    m1 = m2 = m3 =0

#assigning variable to structure class    
s=std()

#UserInput
s.no=raw_input("Give Student Number: ")
s.name=raw_input("Enter the Student Name: ")
s.m1=input("Enter Student Mark1: ")
s.m2=input("Enter Student Mark2: ")
s.m3=input("Enter Student Mark3: ")

total=avg=0.0

total = (s.m1 + s.m2 + s.m3)
avg='%.2f' %(total / 3)

#Result
print "\nThe Output is.... \n",s.no,s.name,total,avg
Give Student Number: 1
Enter the Student Name: raja
Enter Student Mark1: 99
Enter Student Mark2: 97
Enter Student Mark3: 95

The Output is.... 
1 raja 291 97.00

Example: 2, Page No. 5.83

In [1]:
#print a value from Structure.

class struct:
    a=b=0
    
x=struct()
y=struct()

x.a=29
y=x

#Result
print "The Value of a %d"%y.a
The Value of a 29

Example: 3, Page No.:5.84

In [55]:
#Program for User defined data type 

#There is no preprocessor directive in python
D = 7

#No typedef function in python
wk = int(raw_input("Enter Weeks : "))

#Result
print "\nNumber of Days = %d"%(wk*D)
Enter Weeks : 4

Number of Days = 28

Example: 4, Page.No.:5.85

In [68]:
#Program to create user defined data type from structure


class struct:
    name=''
    sex=''
    age=0
    


candidate = [struct() for i in range(0,2)]

for a in range(0,2):
    candidate[a].name= raw_input("Name of the Employee: ")
    candidate[a].sex= raw_input("Sex: ")
    candidate[a].age= input("Age: ")

#Result
print "\n Name\t Sex\t Age\n"

for a in range(0,2):
    print " %s\t"%(candidate[a].name),"  %s\t"%(candidate[a].sex)," %d\n"%(candidate[a].age)
Name of the Employee: venkat
Sex: m
Age: 25
Name of the Employee: geetha
Sex: f
Age: 23

 Name	 Sex	 Age

 venkat	  m	 25

 geetha	  f	 23