def main():
theList = list()
keepGoing = 1
sizeOfList = 0
while keepGoing == 1:
if sizeOfList == 0:
thisValue = int(input('Enter first number: '))
else:
thisValue = int(input('\nEnter next number: '))
theList.append(thisValue)
sizeOfList += 1
keepGoing = int(input('\nGot it. Enter another number? (enter 1 for yes): '))
print('Here is your list: ',theList)
for i in range(len(theList)):
if i < 0:
largeNeg = max([i for i in theList if i < 0]) # gets largest negative number
print('Largest negative number (closest to zero) in that list is: ',largeNeg)
else:
print('There are no negative #s in that list')
main()
我想打印 theList 中最大的负数,但是如果 theList 中没有任何负数,那么我希望我的程序告诉用户列表中没有任何负数。
这是一个简单的重构,使其更加精简和惯用。
def main():
theList = []
negmax = 0
while True:
if not theList:
thisValue = int(input('Enter first number: '))
else:
thisValue = int(input('\nEnter next number: '))
if thisValue < 0:
if not negmax or thisValue > negmax:
negmax = thisValue
theList.append(thisValue)
keepGoing = int(input('\nGot it. Enter another number? (enter 1 for yes): '))
if keepGoing != 1:
break
print('Here is your list: ', theList)
if negmax:
print('Largest negative number (closest to zero) in that list is: ',largeNeg)
else:
print('There are no negative #s in that list')
main()
输入循环确实很笨重。也许只要用户输入数字就可以继续。
while True:
if not theList:
userinput = input('Enter first number: ')
else:
userinput = input('Enter next number: ')
try:
thisValue = int(userinput)
except ValueError:
exitprompt = input('Not a number. Done? [Y/n] ')
if not exitprompt.startswith(('N', 'n')):
break
continue
theList.append(thisValue)