Skip to content Skip to sidebar Skip to footer

Python Code-While Loop Never End

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 int

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

Solution 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

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

Post a Comment for "Python Code-While Loop Never End"