While循环未正确循环,否则有条件

时间:2020-04-29 12:32:39

标签: python python-3.x

board = ["-","-","-","-","-","-","-","-","-"]

i = False
user_input=input("Enter position: ")

while not i:

    while user_input not in ["1","2","3","4","5","6","7","8","9"]:
        user_input=input("Enter position: ")

    block = int(user_input)-1

    if board[block]=="-":
        i = True
    else:
        print("Position not available, try again")

我编写了一个while循环,该循环应循环执行,直到iTrue为止,当if条件不满足该条件时,它应移至{{1 },打印语句,然后再次循环。但是它不断地打印else语句。

2 个答案:

答案 0 :(得分:0)

好像您希望代码只要程序为true及其在该数字列表中就一直要求输入一个数字。这符合您的要求吗?

board = ["-", "-", "-", "-", "-", "-", "-", "-", "-"]

i = False
user_input = input("Enter position: ")

while not i and user_input in ["1", "2", "3", "4", "5", "6", "7", "8", "9"]:
    taken_number = []
    user_input = input("Enter position: ")
    block = int(user_input)-1
    taken_number.append(block)
    if board[block] == "-":
        i = False
    else:
        break

print("Position not available, try again")

答案 1 :(得分:0)

这是因为如果用户输入不在列表中,则名为user_input的变量将保持不变,因此在lopp时将无法再访问内部。

您可以尝试以下操作:

board = ["-","-","-","-","-","-","-","-","-"]

user_input=None # Set it to None by default

while "Input not correct": #a string is always evaluated as true, thus you can give a more explicit condition


    user_input=input("Enter position: ") #prompts user for an input
    try:
        block = int(user_input)-1
    except ValueError:  #if the user enter something else than a position
        print("Position must be an integer")
    try:
        if board[block]=="-": # will raise an IndexError if block is not a valid index
            break #if the condition is satisfied it will quit the while lopp
    except IndexError:
        pass
    print("Position not available, try again") # if we're here it means that the input was not correct (either there is no '-' in the block or the block doesn't exists)
       ```
Hope this will help you
相关问题