Q. Write a program to print the alternate elements of a tuple T.
Answer =
By While loop method :-
tup = eval(input("Enter input for tuple:")) tup2 = () tup3 = () i = 0 while i < len(tup): if i % 2 == 0: tup2 += (tup[i],) else: tup3 += (tup[i],) i += 1 print(tup2) print(tup3)
By For Loop Method :-
T = eval(input("Enter a tuple :-")) tup1 = () tup2 = () for i in range( len(T)) : if i % 2 == 0 : tup1 += ( T[ i ], ) else : tup2 += ( T[ i ], ) print("Alternate elements") print( tup1 ) print( tup2 )
Output :-
Enter a tuple :-(0,1,2,3,4,5,6,7,8,9)
Alternate elements
(0, 2, 4, 6, 8)
(1, 3, 5, 7, 9)
>>>
I suggest an edit to the program
ReplyDeleteIn the last line (index=index+1)
Replace 1 with 2
You are wrong.
DeleteBut in this question, we have to use while loop.
ReplyDeleteyou have too use while loop in the program. use the given below program
ReplyDeletetup = eval(input("Enter input for tuple:"))
tup2 = ()
tup3 = ()
i = 0
while i < len(tup):
if i % 2 == 0:
tup2 += (tup[i],)
i += 1
else:
tup3 += (tup[i],)
i += 1
print(tup2)
print(tup3)
Correct.
DeletePost a Comment
You can help us by Clicking on ads. ^_^
Please do not send spam comment : )