簡體   English   中英

需要詢問用戶是否要使用for循環重復(Python)

[英]Need to ask user if they want to repeat with for loop (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經驗不足,這真令人沮喪!

您可以嘗試如下操作:

保留一個變量,該變量詢問用戶是否要玩游戲,最后再次詢問他們。

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

遇到中斷時,您將退出循環,因此也不起作用。

使用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])

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM