Python while循环不循环

时间:2015-02-01 22:50:05

标签: python python-2.7 loops input while-loop

我正在尝试使用while循环进行错误检查以获取用户输入,以确保用户始终输入超过2个字符的内容。但是 Python 程序从不要求我输入。帮助

first_names = ['fred', 'bob', 'mary', 'john', 'frank', 'james', 'joe', 'jay']
last_names = ['jones', 'smith', 'doe', 'cardinal', 'jesus', 'watson', 'blogs', 'harris']
full_names = ['empty_name']*len(first_names)
i = 0
while True:
    full_names[i] = (first_names[i] + " " + last_names[i])
    print full_names[i]
    i = i + 1
    if i == (len(last_names) + len(first_names))/ 2:
        True = not True
name = 'placeholder_name_for_user_input_via_console'
while True:
    name = raw_input("please enter a new name")
    if len(name) < 2 :
        print " please enter a name longer than 2 characters"
    else:
        True = not True
print "thank you for entering a long name"
full_names.append(name)
print(full_names)

如果这有任何不同,我正在使用Python 2.7。

编辑: 我修复了我的代码。在第一个while循环之后=需要编写True = not False以使其正常工作。

2 个答案:

答案 0 :(得分:4)

您无法更改True的值。 TrueTrue最重要的事情。而是使用break

while True:
    full_names[i] = (first_names[i] + " " + last_names[i])
    print full_names[i]
    i = i + 1
    if i == (len(last_names) + len(first_names))/ 2:
        # True = not True; some_int / 0
        break

break退出了它所在的最里面的循环。

答案 1 :(得分:-1)

我修复了我的代码。在第一个while循环之后,我需要编写True = not False以使其工作:

first_names = ['fred', 'bob', 'mary', 'john', 'frank', 'james', 'joe', 'jay']
last_names = ['jones', 'smith', 'doe', 'cardinal', 'jesus', 'watson', 'blogs', 'harris']
full_names = ['empty_name']*len(first_names)
i = 0
while True:
    full_names[i] = (first_names[i] + " " + last_names[i])
    print full_names[i]
    i = i + 1
    if i == (len(last_names) + len(first_names))/ 2:
        True = not True
name = 'placeholder_name_for_user_input_via_console'
True = not False
while True:
    name = raw_input("please enter a new name")
    if len(name) < 2 :
        print " please enter a name longer than 2 characters"
    else:
        True = not True
print "thank you for entering a long name"
full_names.append(name)
print(full_names)