Python为'转到'工作

时间:2011-03-04 05:50:43

标签: python goto

目前,我检查字符串中是否包含特定字符。

我正在尝试寻找一个'Goto'功能。

这就是我现在所拥有的:

chars = set('0123456789$,')

if any((c in chars) for c in UserInputAmount):
    print 'Input accepted'
else:
    print 'Invalid entry. Please try again'

如果条目无效,我只需要Python返回'UserInputAmount'的字符串输入。推进正确的方向将是值得的。

4 个答案:

答案 0 :(得分:6)

你不需要goto,你只需要一个循环。试试这个,除非用户提供有效的输入,否则它会永远循环:

chars = set('0123456789$,')

while True: # loop "forever"
    UserInputAmount = raw_input() # get input from user

    if any((c in chars) for c in UserInputAmount):
        print 'Input accepted'
        break # exit loop

    else:
        print 'Invalid entry. Please try again'
        # input wasn't valid, go 'round the loop again

答案 1 :(得分:2)

当我学习Pascal时,我们习惯称之为“启动阅读”的一种技巧:

chars = set('0123456789$,')

UserInputAmount = raw_input("Enter something: ")
while not any((c in chars) for c in UserInputAmount):
    UserInputAmount = raw_input("Wrong! Enter something else: ")
print "Input accepted."

答案 2 :(得分:2)

在Ben的身上徘徊:


>>> chars = set('1234567')
>>> while not any((c in chars) for c in raw_input()):
...  print 'try again'
... else:
...  print 'accepted'
... 
abc
try again
123
accepted

答案 3 :(得分:-1)

goodEntry = False
first = True
chars = frozenset("abc")  #whatever
validateEntry = lambda x: any( (c in chars) for c in inString)

while not goodEntry:
    if not first: print "Invalid input"
    first = False
    print "Enter input: "
    inString = raw_input()
    goodEntry = validateEntry(inString)