Python代码 - 虽然循环永远不会结束

问题描述:

我是Python新手,试图学习它。 这是我的代码: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: 

我能知道什么是错我的代码? 谢谢

+4

'如果isint == TRUE; - 当将它永远是真实的吗? – user2357112

+2

为什么你需要布尔检查?只要把所有你需要的时候在一个int'try' –

isint需要断言输入为INT

更新后进行更新: 有第一次尝试 - 除了一个问题。如果输入不是整数,程序应该能够退出或将您带回开始。下面将继续循环,直到你输入一个完整的第一

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 
+0

多少整数代码3 请输入整数1:1 请输入整数2:2 请输入integer3:3个 –

+0

多少整数3 请输入整数1 :1 请输入整数2:2 请输入整数3:3 现在它的运行完好 谢谢男人。 我感谢大家帮助我。 –

+0

欢迎大家接受我的回答;) – kthouz

你的代码的问题是,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") 

更好的代码:

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)