Python 的 'Goto' 解决方法

0 投票
4 回答
739 浏览
提问于 2025-04-16 12:59

目前我在检查一个字符串里是否包含特定的字符。

我正在尝试找到一个替代'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 个回答

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
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."
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

撰写回答