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!
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]
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()
newCardNumber
to int
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.