2016-07-06 28 views
0
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没有经验,这令人沮丧!需要问用户是否要重复使用for循环(Python)

回答

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") 
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])