Python Code-While loop never end

2019-09-15 18:51发布

问题:

I am new to Python.Trying to learn it. This is my Code:

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

The code is executing but the loop is always repeating and is not allowing me to enter 2nd integer.

Output:

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

Can i know what is wrong with my code? Thank you

回答1:

The problem of your code is that isint is never changed and is always False, thus count is never changed. I guess your intention is that when the input is a valid integer, increase the count;otherwise, do nothing to count.

Here is the code, isint flag is not need:

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")


回答2:

isint needs to be updated after asserting that the input was int

UPDATE: There is another problem on the first try-except. If the input wasn't integer, the program should be able to exit or take you back to the begining. The following will keep on looping until you enter an integer first

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


回答3:

A better code:

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)