2016-07-06 56 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])