Python Code-While循环永不结束

时间:2016-12-16 05:07:32

标签: python python-3.x while-loop revitpythonshell

我是Python的新手。要学习它。 这是我的代码:

import sys
my_int=raw_input("How many integers?")
try:
    my_int=int(my_int)
except ValueError:
    ("You must enter an integer")
ints=list()
count=0
while count<my_int:
    new_int=raw_input("Please enter integer{0}:".format(count+1))
    isint=False
    try:
        new_int=int(new_int)
    except:
        print("You must enter an integer")
    if isint==True:
        ints.append(new_int)
        count+=1

代码正在执行,但循环总是重复,不允许我输入第二个整数。

输出:

How many integers?3
Please enter integer1:1
Please enter integer1:2
Please enter integer1:3
Please enter integer1:

我可以知道我的代码有什么问题吗? 谢谢

3 个答案:

答案 0 :(得分:3)

您的代码存在问题,isint永远不会更改,始终为False,因此永远不会更改count。我想你的意图是当输入是有效整数时,增加count;否则,不对count做任何事。

以下是代码,isint标志不需要:

import sys

while True:
    my_int=raw_input("How many integers?")
    try:
        my_int=int(my_int)
        break
    except ValueError:
        print("You must enter an integer")
ints=list()
count=0
while count<my_int:
    new_int=raw_input("Please enter integer{0}:".format(count+1))
    try:
        new_int=int(new_int)
        ints.append(new_int)
        count += 1
    except:
        print("You must enter an integer")

答案 1 :(得分:1)

声明输入为int

后,需要更新

isint

<强>更新 第一次尝试除外还有另一个问题。如果输入不是整数,程序应该能够退出或带你回到开头。以下将继续循环,直到您输入第一个整​​数

ints=list()

proceed = False
while not proceed:
    my_int=raw_input("How many integers?")
    try:
        my_int=int(my_int)
        proceed=True
    except:
        print ("You must enter an integer")

count=0
while count<my_int:
    new_int=raw_input("Please enter integer{0}:".format(count+1))
    isint=False
    try:
        new_int=int(new_int)
        isint=True
    except:
        print("You must enter an integer")
    if isint==True:
        ints.append(new_int)
        count+=1

答案 2 :(得分:0)

更好的代码:

import sys
my_int=raw_input("How many integers?")
try:
    my_int=int(my_int)
except ValueError:
    ("You must enter an integer")
ints = []


for count in range(0, my_int):

    new_int=raw_input("Please enter integer{0}:".format(count+1))
    isint=False

    try:

        new_int=int(new_int)
        isint = True

    except:

        print("You must enter an integer")

    if isint==True:
        ints.append(new_int)