Python Tutorial | Python tuples 6

Iterating Through a Tuple (Programs)

1.
Python program to traverse a tuple and display the elements?
Sol:

#using for loop

n=(1,2,3,4,5,6,7,8,9,10)
for i in n:
    print(i)

#using while loop
    
n=(1,2,3,4,5,6,7,8,9,10)
i=0
while(i<len(n)):
    print(n[i])
    i=i+1

Output:

1
2
3
4
5
6
7
8
9
10
>>> 

2.
Python program to traverse a tuple, calculate and display sum of all the elements?
Sol:

#using for loop

n=(1,2,3,4,5,6,7,8,9,10)
s=0
for i in n:
    s=s+i
    print(i)
print("Sum = ",s)

#using while loop
    
n=(1,2,3,4,5,6,7,8,9,10)
s=0
i=0
while(i<len(n)):
    s=s+n[i]
    print(n[i])
    i=i+1
print("Sum = ",s)

Output:

1
2
3
4
5
6
7
8
9
10
Sum =  55
>>> 

3.
Python program to traverse a tuple, calculate and display product of all the elements?
Sol:

#using for loop

n=(1,2,3,4,5,6,7,8,9,10)
p=1
for i in n:
    p=p*i
    print(i)
print("Product = ",p)
#using while loop
    
n=(1,2,3,4,5,6,7,8,9,10)
p=1
i=0
while(i<len(n)):
    p=p*n[i]
    print(n[i])
    i=i+1
print("Product = ",p)

Output:

1
2
3
4
5
6
7
8
9
10
Product =  3628800
>>> 

4.
Python program to traverse a tuple, calculate and display total +ve elements?
Sol:

#using for loop

n=(51,22,-73,24,-45)
p=0
for i in n:
    print(i)
    if(i>0):
        p+=1
print("Total +ve elements = ",p)

#using while loop
    
n=(51,22,-73,24,-45)
p=0
i=0
while(i<len(n)):
    print(n[i])
    if(n[i]>0):
        p+=1
    i=i+1
print("Total +ve elements = ",p)

Output:

51
22
-73
24
-45
Total +ve elements =  3
>>> 

5.
Python program to traverse a tuple, calculate and display total -ve elements?
Sol:

#using for loop

n=(51,22,-73,24,-45)
p=0
for i in n:
    print(i)
    if(i<0):
        p+=1
print("Total -ve elements = ",p)

#using while loop
    
n=(51,22,-73,24,-45)
p=0
i=0
while(i<len(n)):
    print(n[i])
    if(n[i]<0):
        p+=1
    i=i+1
print("Total -ve elements = ",p)

Output:

51
22
-73
24
-45
Total -ve elements =  2
>>> 

Python Basic Programming Tutorial

Python Introduction     Getting started in Python Programming      Python propgramming fundamentals     Python Operators    Python If Condition     Python for loop    Python range construct      Python While loop    break and continue statements     Different looping techniques     Python List     Python String     Python Functions    Python Inbuilt Functions     Python Recursion     Using Python Library     Python Tuples     Python Dictionary     Python Sets     Python Strings     Python Exception Handling     Python Data File Handling