如何连接用户输入和列表

时间:2018-11-18 23:44:44

标签: python list

在我的程序中,我接受用户输入(整数1-9),并让用户不断键入数字,直到他们键入0退出。一旦他们输入0,我想打印整数的和然后退出。我是python的新手,所以将不胜感激。我在使用>和<符号时收到无效的语法错误,不确定原因。

  def createList():
         myList=[]
         return myList



  def fillList(myList):
        for number in myList:
            if number >=1 and <= 9:
              number=int(input(" enter a number 1-9, and 0 to quit"))
              myList.append(number)
              return myList


  def printList(myList):
      for number in myList:
          print ( " the sum is" ,sum(myList))
          print(number)
          if number ==0:
              exit()

  def main():
      myList = createList()
      fillList(myList)
      printList(myList)


  main()

3 个答案:

答案 0 :(得分:0)

if number >=1 and number <= 9:

您需要将变量放在和的两侧,因为它们是两个单独的条件。

此外,由于您最初是在创建一个空列表,所以您将永远不会进入获得用户输入的部分。要解决此问题,您应该使用while循环。

while number != 0:

完整程序可能如下所示:

def createList():
     myList=[]
     return myList

def fillList(myList):
    number = 5
    while number != 0:
        if number >=1 and number <= 9:
          number=eval(input(" enter a number 1-9, and 0 to quit"))
          myList.append(number)

     return myList


def printList(myList):
  for number in myList:
      print ( " the sum is" ,sum(myList))
      print(number)
      if number ==0:
          exit()

def main():
  myList = createList()
  fillList(myList)
  printList(myList)


main()

答案 1 :(得分:0)

您只缺少一个单词,请尝试以下操作:

if number >=1 and number <= 9:

太近了!

答案 2 :(得分:0)

_sum = 0
looping = True
while looping: 
    num = input("Enter a number (1-9) or 0 to exit.")
    if num.isdigit() and 0 <= int(num) <= 9:
        _sum += num
        if num is 0:
            looping = False
print("Sum is", _sum)