Eric
Eric

Reputation: 177

Convert a for loop into a while loop in Python 3.x

The program I wrote by using 'for loop' is correct and passed all the testcases,however, when I transfer 'for loop' to 'while loop',an 'IndexError' occurred,I wonder what are the problems in my program which using 'while loop'.

nums = []
remainders=[]
while True:
    num=int(input('Number: '))
    if num==0:        
        break
    nums.append(num)    
if len(nums)==0:
    print('No integers were entered')
    exit()
a=0
while a<len(nums):
    num=nums[a]
    remainder=num%10
    remainders.append(remainder)
    a+=1
index=remainders.index(max(remainders))
count=0   
for i in remainders:
    if i > remainder:
        remainder=i
        count=0
    if i ==remainder:
        count+=1
if count ==1:
    print('The most interesting integer was: {}'.format(nums[index]))  
elif count>1 and count<len(nums):
    print('Two or more integers are the most interesting')
else:
    print('All integers have the same remainder')  

That's the program I wrote by using for loop, this answer is correct

nums = []
remainders=[]
while True:
    num=int(input('Number: '))
    if num==0:        
        break
    nums.append(num)    
if len(nums)==0:
    print('No integers were entered')
    exit()
a=0
while a<len(nums):
    num=nums[a]
    remainder=num%10
    remainders.append(remainder)
    a+=1
index=remainders.index(max(remainders))
count=0   
k=0
while k<len(remainders):
    remainder=remainders[k]
    if remainders[k]>remainder:
        remainder=remainders[k]
        count=0
    k+=1    
    if remainders[k]==remainder:
        count+=1
    k+=1    
if count ==1:
    print('The most interesting integer was: {}'.format(nums[index]))  
elif count>1 and count<len(nums):
    print('Two or more integers are the most interesting')
else:
    print('All integers have the same remainder')  

This answer is incorrect because the second while loop have some problems

actual:
Number: 4
Number: 20
Number: 9
Number: 3
Number: 5
Number: 0
Traceback (most recent call last):
  File "numbers.py", line 26, in <module>
    if remainders[k]==remainder:
IndexError: list index out of range
expected:
Number: 4
Number: 20
Number: 9
Number: 3
Number: 5
Number: 0
The most interesting integer was: 9

Upvotes: 0

Views: 59

Answers (1)

Devesh Kumar Singh
Devesh Kumar Singh

Reputation: 20490

Two issues in your code

  • You are doing k+=1 twice, which is causing the list index out of range error, do it only once

  • When you do remainder=remainders[k] if remainders[k]>remainder, this will always evaluate to False, remove the line remainder=remainders[k]

Keeping this in mind, the following while loop should work

while k<len(remainders):
    if remainders[k]>remainder:
        remainder=remainders[k]
        count=0
    if remainder==remainders[k]:
        count+=1
    #Increment only once
    k+=1

Upvotes: 1

Related Questions