我正在学习python,我刚刚编写了这个代码用于作业,它没有按照我的预期或想要的方式行事。
while(number != 0):
def sumList(myList):
myList.append(number)
return myList
Sum = (Sum + number)
number = int(input("plese enter a number: "))
if(number == 0):
def printList(myList):
for number in myList:
print(number, " + ")
def main():
myList = createList()
sumList(myList)
printList(myList)
main()
print(Sum, " ")
当输入0时,它应该打印出sumList和Sum,但它不是,我不知道为什么。
答案 0 :(得分:0)
myList = []
sum = 0
while(True):
number = int(input("please enter a number: "))
if (number != 0):
sum = sum + number
myList.append(number);
else:
for number in myList:
print(number, " + ")
print('equals', sum)
break
因为你的错误很多,所以我重写了它。 Hangon我会看看我是否可以修复你的版本。
我仍然无法正确理解你的代码,但我已经尝试了另一个更接近原版的版本,所以希望你能更好地理解。
def appendToList(list, num):
list.append(num)
#return myList No need to return, I may be misunderstanding your intent
def printList(list):
for num in myList:
print(num, " + ")
def sumList(list):
sum = 0
for num in list:
sum = sum + num
return sum
#def main(): I don't know what you're trying to do here.
# myList = createList() no such function exists
myList = [] # Create your list
while (True):
number = int(input("please enter a number: "))
if (number != 0):
appendToList(myList, number)
else:
break
printList(myList)
print('equals', sumList(myList))
虽然我认为第一个版本更容易理解。另请注意,在Python中,首选约定是在函数名称需要时使用由下划线分隔的小写。但我不习惯。