2016-07-06 1 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 :"루프에 넣으려고 할 때마다 "얼마나 많은 숫자를 입력 하시겠습니까?" 어떤 도움을 주셔서 감사합니다, 나는 파이썬에 익숙하지 않으며 이것은 실망 스럽습니다!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 루프를 사용하고 다른 방법으로 문제를 생각해보십시오. 사용자가 더 많은 입력을 입력하고 종료할지 묻는 메시지가 표시됩니다.

나는 이것이 당신이 (당신은 파이썬 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]) 
관련 문제