I don't quite understand the while loop in python

拥有回忆 提交于 2020-01-07 03:07:23

问题


def AddSingleCard(self):
   symbols = ['heart', 'diamond', 'club', 'spade']
   #newCardSign = ''
   newCardNumber, newCardSign = raw_input().split()
   try:
       newCardNumber = int(float(newCardNumber))
   except:
       newCardNumber, newCardSign = raw_input().split()
   while (newCardNumber not in (2,15) or newCardSign not in symbols):
      newCardNumber, newCardSign = raw_input().split()
   newCard = [newCardNumber, newCardSign]

I'm trying to loop until the input will be a number between 2-15, and the string will be one of the symbols, but the while loop works for me only if the wrong input is the numbers, if the numbers are in range and the string is not, the program just gets stuck in the while line, and waits for next input, instead of going down to the next line and get the input to the right place... I believe it's connected to the syntax of my while loop, but I can't put my finger on the problem. (my programming background is c, I'm new to python)

tnx!


回答1:


def AddSingleCard():
    symbols = ['heart', 'diamond', 'club', 'spade']
    newCardNumber = newCardSign = None
    while (newCardNumber not in range(2, 16) or newCardSign not in symbols):
        newCardNumber, newCardSign = raw_input('Enter Number and Symbol with space between:').split()
        try:
            newCardNumber = int(newCardNumber)
        except:
            continue
    newCard = [newCardNumber, newCardSign]
    return newCard


AddSingleCard()
  1. Convert newCardNumber to int
  2. change (2,15) to range(2,16)



回答2:


If you know C, you might want to use a do ... while loop, because the loop body must be executed at least once. But there is no such thing as a do ... while loop in Python. You have to start with while True: and break out of the loop if your condition is met.

def AddSingleCard(self):
   symbols = ['heart', 'diamond', 'club', 'spade']

   while True: 
       newCardNumber, newCardSign = raw_input("Enter card number and sign (heart, diamond, club, spade), seperated by space").split()
       try:
           newCardNumber = int(newCardNumber)
       except ValueError:
           print "Card number must be a number between 2 and 15"
           continue

       if newCardNumber in range(2,16) and newCardSign in symbols:
              break

       print "Card number or symbol not valid"

   newCard = [newCardNumber, newCardSign]


来源:https://stackoverflow.com/questions/34617242/i-dont-quite-understand-the-while-loop-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!