[英]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'. 我使用“ for循环”编写的程序是正确的,并且通过了所有测试用例,但是,当我将“ for循环”转换为“ while循环”时,发生了“ IndexError”,我想知道我的程序中使用什么问题“循环”。
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 那是我使用for循环编写的程序,这个答案是正确的
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 这个答案是错误的,因为第二个while循环有一些问题
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
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 您执行两次
k+=1
,这导致list index out of range
错误,请仅执行一次
When you do remainder=remainders[k] if remainders[k]>remainder
, this will always evaluate to False, remove the line remainder=remainders[k]
如果执行
remainder=remainders[k] if remainders[k]>remainder
,则此结果将始终为False,请删除行remainder=remainders[k]
Keeping this in mind, the following while loop should work 请牢记这一点,以下while循环应该有效
while k<len(remainders):
if remainders[k]>remainder:
remainder=remainders[k]
count=0
if remainder==remainders[k]:
count+=1
#Increment only once
k+=1
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.