繁体   English   中英

Python解决“ Goto”问题

[英]Python Work Around For '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”的字符串输入即可。 向正确方向的推动将不胜感激。

您不需要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

当我学习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."

轻描淡写本:


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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM