def getPhoneNumber():
"""Returns phone number if valid"""
validPhoneNumber = False
emptyString = ''
#prompt user for phone number
while not validPhoneNumber:
phoneNumber = input('\nEnter phone number with last four letters being alphabet'\
'(910-555-book):')
#check if valid form
if len(phoneNumber) != 12 or phoneNumber[3] != '-' or \
phoneNumber[7] != '-':
print('Invalid Entry - Must be of the form 910-555-book')
else:
validPhoneNumber = True
while validPhoneNumber:
if not phoneNumber[0:3].isdigit() or not phoneNumber[4:7].isdigit():
print('Non-digit entered before end')
validPhoneNumber = False
if not phoneNumber[8:12].isalpha():
print('Non-alphabet entered in last four characters')
validPhoneNumber = False
return phoneNumber
def displayPhoneNumber(phoneNumber):
"""Displays alphabet to phone number"""
translate = {'a':2, 'b':2, 'c':2, 'd':3, 'e':3, 'f':3, 'g':4, 'h':4, 'i':4,
'j':5, 'k':5, 'l':5, 'm':6, 'n':6, 'o':6, 'p':7, 'q':7, 'r':7,
's':7,'t':8,'u':8,'v':8,'w':9, 'x':9, 'y':9, 'z':9,'0':0,'1':1}
print(phoneNumber[0:8] + translate[phoneNumber[8]] + translate[phoneNumber[9]]\
+ translate[phoneNumber[10]] + translate[phoneNumber[11]])
#Main
print('This program will allow you to enter a phone number with the last four')
print('characters being in the alphabet and print out the corresponding numbers.')
terminate = False
while not terminate:
phoneNumber = getPhoneNumber()
displayPhoneNumber(phoneNumber)
#continue?
response = input('Enter another phone number? (y/n):')
if response == 'n':
terminate = True
getPhoneNumber
有什么问题吗?因为如果没有传递给displayPhoneNumber
,我会认为它会打印出来。所以我的猜测是getPhoneNumber
。这是我第一次尝试使用切片表示法isdigit
和isalpha
,所以也许它在那里?
答案 0 :(得分:1)
while validPhoneNumber:
if not phoneNumber[0:3].isdigit() or not phoneNumber[4:7].isdigit():
print('Non-digit entered before end')
validPhoneNumber = False
if not phoneNumber[8:12].isalpha():
print('Non-alphabet entered in last four characters')
validPhoneNumber = False
如果phoneNumber
是有效的电话号码,则validPhoneNumber
永远不会为假,因此while validPhoneNumber
循环将永久运行。