Software & Finance





Python - How to use Arrays





 

I have given here a python program to explain on how to use arrays. arrNumbers = [] is syntax to declare it as an array. You can use append method to add elements into the array.

This code is tested with Python version 2.6

 

        print "Program to find the sum of N numbers"
        arrnumbers = []
        n = 0
        a = 0
        sum = 0
        
        print "Total Numbers:", 
        n = input()
        
        for i in range (0, n):
           print "Enter", i + 1, "Number: ", 
           a = input()
           arrnumbers.append(a)
           sum += a
        
        print "The sum of numbers: [", 
        for i in range (0, n):
           print arrnumbers[i],  
        
        print " ] is: ", sum
        
		#sample output
		#Program to find the sum of N numbers
		#Total Numbers: 5
		#Enter 1 Number:  10
		#Enter 2 Number:  30
		#Enter 3 Number:  20
		#Enter 4 Number:  40
		#Enter 5 Number:  50
		#The sum of numbers: [ 10 30 20 40 50  ] is:  150