我需要创建一个循环,可以在整数列表中搜索可被5和7分割的整数,同时允许读者确定列表的起始和结束编号.Below是我的代码,但对于某些是因为它只打印满足条件的列表的最后一个数字而不是所有内容?我的代码有什么问题?我只允许用循环函数执行此操作。
startRange =int(input("Enter the starting number:"))
endRange = int(input("Enter the end number:"))
a=range(startRange,endRange)
b=list(a)
c=b.append(int(endRange))
#find numbers
def findNumbers(startRange,endRange):
for i in b:
if i%5==0 and i%7==0:
Numbers=[]
z=i
y=Numbers.append(i)
continue
print(favNumbers)
return favNumbers
答案 0 :(得分:0)
startRange =int(input("Enter the starting number:"))
endRange = int(input("Enter the end number:"))
a= range(startRange,endRange)
b= list(a)
c= b.append(int(endRange))
#find numbers
favNumbers = []
def findNumbers(startRange, endRange):
for i in b:
if i%5==0 and i%7==0:
favNumbers.append(i)
print(favNumbers)
答案 1 :(得分:0)
你的代码有一些问题,所以我试着在这里解决它们:
def findNumbers(list): #findNumbers is now passed a list
favNumbers=[] #This needs to be initialized before the for loop, or it will be reset on every iteration
for i in list:
if i%5==0 and i%7==0:
favNumbers.append(i) #The number is appended to favNumbers, and you do not set this equal to a variable.
return favNumbers
def main(): #I don't know about you, but my CS prof would kill me if I didn't have a main()...
startRange = int(input("Enter the starting number:"))
endRange = int(input("Enter the end number:"))
mylist = list(range(startRange,endRange+1)) #This allows you to include endRange in the list without appending it yourself
print(findNumbers(mylist))
main()
我尝试评论我做出重大更改的区域,但如果您有以下问题评论!
希望它有所帮助!
修改强>
或者,这里的代码没有main()
~~颤抖~~更接近你原来的东西,findNumbers函数接受两个整数而不是一个列表!
startRange = int(input("Enter the starting number:"))
endRange = int(input("Enter the end number:"))
#find numbers
def findNumbers(startRange, endRange):
a = range(startRange,endRange+1) #Again, this way you don't have to say c = b.append(int(endRange))
b = list(a)
favNumbers = [] #This needs to be initialized here, or else it won't return the list you want.
for i in b:
if i%5==0 and i%7==0:
favNumbers.append(i)
print(favNumbers)
return favNumbers
findNumbers(startRange, endRange)