python - 多个 while 循环的问题

标签 python while-loop

我在尝试获取 while 循环来验证用户输入,然后确保用户不会重复值时遇到问题。下面显示的是我尝试过的两种方法,但我不知道如何让它们发挥作用。

方法1

def test():
my_list = ["", "", ""]
for i in range(3):
    while (my_list[i] != "one") and \
          (my_list[i] != "two") and \
          (my_list[i] != "three"):

        while (my_list[i] == my_list[0]) and \
              (my_list[i] == my_list[1]) and \
              (my_list[i] == my_list[2]):

            text = "Enter, one, two or three", i + 1, ":"
            try:
                my_list[i] = input(text)
            except KeyboardInterrupt:
                sys.exit()

print(my_list)

方法2

def test2():

my_list= ["", "", ""]
while len(my_list)!=len(set(my_list)) == True:
    for c in range(4):
        while (my_list[i] != "one") and \
              (my_list[i] != "two") and \
              (my_list[i] != "three"):
            text = "Enter, one, two or three", c + 1, ":"
            try:
                my_list[c] = input(text)
            except KeyboardInterrupt:
                sys.exit()


print(my_list)

最佳答案

为什么不简化一下:

my_list = []
while len(data) < 3:
    data = input(text) # Valid for Python 3, use raw_input(text) in Python 2
    if data in ("one", "two", "three") and data not in my_list:
        my_list.append(data)

这或多或少是对您的要求的直接翻译:

  1. 我有一个 list
  2. 虽然列表太小
    1. 获取一些数据
    2. 如果数据是有效值之一,并且尚未在列表中
      1. 将其添加到列表

在这种情况下使用 for x in range(y) 只会增加复杂性,因为您实际上并不知道希望循环运行多少次。

没有理由在列表中预先填充无效值 (my_list = ["", "", ""]),因为可以使用 append 调整列表大小>.

此外,您的 sys.exit 代码是不必要的,而且可能有害。只要让异常传播,它就会使程序本身崩溃(除非您捕获它,对于 KeyboardInterrupt 异常,您几乎不应该这样做)。

注意:如果您将两个 while 循环合并为一个,您的第一个版本就可以工作,只是不必要地复杂。

关于python - 多个 while 循环的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13767959/

相关文章:

python - python中使用shutil.copytree()的问题

python - Python 中的双重约束循环

c++ - 只允许从 0 到 1 的数字

javascript - 只能发布 while 循环的第一个结果

Php 一会儿

c - 为什么我的程序使用 for 循环但现在使用 while 循环?

python - Pymongo错误通过atlas连接到mongodb

Python 脚本在终端中执行命令

python - 使用相同的参数初始化两个Python类,得到不同的结果

java - While 循环在提示前执行一次