需要询问用户是否要重复使用for循环(Python)

时间:2016-07-06 07:03:05

标签: python

myList = []
numbers = int(input("How many numbers would you like to enter? "))
for numbers in range(1,numbers + 1):
    x = int(input("Please enter number %i: " %(numbers)))
    myList.append(x)
b = sum(x for x in myList if x < 0)
for x in myList:
     print("Sum of negatives = %r" %(b))
     break
c = sum(x for x in myList if x > 0)
for x in myList:
    print("Sum of positives = %r" %(c))
    break
d = sum(myList)
for x in myList:
    print("Sum of all numbers = %r" %(d))
    break

我需要弄清楚如何询问用户他们是否想再次使用该程序。我还没有学习函数,每次我尝试将整个程序放入“while True:”循环时,它只会重复“你要输入多少个数字?”感谢任何帮助,我对python缺乏经验,这令人沮丧!

2 个答案:

答案 0 :(得分:0)

您可以尝试这样的事情:

保留一个变量,询问用户是否想要玩游戏,最后再问他们。

k = input("Do you want to play the game? Press y/n")

while k == 'y':
    myList = []
    numbers = int(input("How many numbers would you like to enter? ")) 
    for numbers in range(1,numbers + 1):
      x = int(input("Please enter number %i: " %(numbers)))
      myList.append(x)
    b = sum(x for x in myList if x < 0)
    for x in myList:
      print("Sum of negatives = %r" %(b))
      break
    c = sum(x for x in myList if x > 0)
    for x in myList:
      print("Sum of positives = %r" %(c))
      break
    d = sum(myList)
    for x in myList:
      print("Sum of all numbers = %r" %(d))
      break
    k = input("Do you want to play again? y/n")

答案 1 :(得分:0)

你在休息时退出循环,所以也不会工作。

使用while循环,并以另一种方式考虑问题:假设用户将输入更多输入,并询问他/她是否想要退出。

我认为这是您正在寻找的(假设您使用的是Python 3):

myList = []

# This variable will change to False when we need to stop.
flag = True

# Run the loop until the user enters the word 'exit' 
#    (I'm assuming there's no further error checking in this simple example)

while flag:
   user_input = input("Please enter a number.  Type 'q' to quit. ")
   if user_input == 'q':
       flag = False
   elif ( . . .  ):   //do other input validation (optional)
       pass
   else:
       myList.append(int(user_input))
       print "The sum of negatives is %d" % sum([i for i in myList if i<0])
       print "The sum of positives is %d" % sum([i for i in myList if i>0])
       print "The sum of all numbers is %d" % sum([i for i in myList])