while循环在抛出垃圾值时不会重复自身

时间:2019-01-01 05:46:23

标签: python python-3.x

我试图使用'not'关键字运行while循环,但是当我这样做时,该循环也接受垃圾值(例如bjskdjb),这不是为while / for循环设置的条件

当我运行for循环时,它抛出语法错误。

我在这里犯什么错误(同时使用for循环和while循环)?

我尝试过使用for循环和while循环。

def askplayerchoice():
    playerchoice = ''
    while playerchoice not in ('X' , 'O'):
        playerchoice = input('Enter X or O: ')
        if playerchoice == 'X':
            return ['X' , 'O']
        else:
            return ['O', 'X']
askplayerchoice()

'''
# Using For loop I am getting a syntax error. 

def askplayerchoice():
    playerchoice = ''
    for playerchoice not in ('X' , 'O'):
        playerchoice = input('Enter X or O: ')
        if playerchoice == 'X':
            return ['X' , 'O']
        else:
            return ['O', 'X']
askplayerchoice()

'''

我希望代码不断询问用户输入“ X”还是“ O”,直到用户输入正确的值为止。

5 个答案:

答案 0 :(得分:3)

您可以添加一个try catch块,并在输入的字符串与所需值不匹配时引发异常。我已经更新了您的代码。以下是代码段:

def askplayerchoice():
    playerchoice = ''
    while playerchoice.lower() not in ('X' , 'O'):
        try:
            playerchoice = str(input('Enter X or O: '))
            if playerchoice.lower() not in ['x','o']:
                raise ValueError('A very specific bad thing happened.')
            if playerchoice.lower() == 'x':
                return ['X' , 'O']
            else:
                return ['O', 'X']
        except ValueError:
            playerchoice = ''


askplayerchoice()

答案 1 :(得分:0)

因为您在循环内使用了return,所以您将在第一遍本身中从循环返回到函数调用者。因此,返回'X'以外的任何值,['O', 'X']

def askplayerchoice():
    playerchoice = ''
    while playerchoice not in ('X' , 'O'):
        playerchoice = input('Enter X or O: ')
    if playerchoice == 'X':
        return ['X' , 'O']
    elif playerchoice == 'O':
        return ['O', 'X']

print(askplayerchoice())

您还可以在此处使用无限循环while True:,如下所示:

def askplayerchoice():
    playerchoice = ''
    while True:
        playerchoice = input('Enter X or O: ')
        if playerchoice == 'X':
            return ['X' , 'O']
        elif playerchoice == 'O':
            return ['O', 'X']

print(askplayerchoice())

答案 2 :(得分:0)

您的函数正在while循环内返回一个值,无论用户输入的内容是什么,这都会导致循环结束。您需要将else的条件更改为else if

if playerchoice == 'X':
     return ['X' , 'O']
elif playerchoice == 'O':
     return ['O', 'X']

答案 3 :(得分:0)

首先,您正在初始化playerchoice = '',但是在循环内部,您仅在检查playerchoice == 'X'。但是您没有检查playerchoice == 'O'。因此,它转到了别的位置并退出循环。

这应该可以完成工作:

def askplayerchoice():
    playerchoice = input('Enter X or O: ')
    while playerchoice not in('X', 'O'):
        playerchoice = input('Enter X or O: ')
        if playerchoice == 'X':
            return ['X', 'O']
        elif playerchoice == 'O':
            return ['O', 'X']
askplayerchoice()

答案 4 :(得分:0)

使用return时,while循环将停止。 试试这个代码,它会不断询问。

react-native upgrade 
react-native link