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
whileTrue:
my_int=raw_input("How many integers?")
try:
my_int=int(my_int)
breakexcept ValueError:
print("You must enter an integer")
ints=list()
count=0while 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 += 1except:
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 = Falsewhilenot proceed:
my_int=raw_input("How many integers?")
try:
my_int=int(my_int)
proceed=Trueexcept:
print ("You must enter an integer")
count=0while count<my_int:
new_int=raw_input("Please enter integer{0}:".format(count+1))
isint=Falsetry:
new_int=int(new_int)
isint=Trueexcept:
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 inrange(0, my_int):
new_int=raw_input("Please enter integer{0}:".format(count+1))
isint=Falsetry:
new_int=int(new_int)
isint = Trueexcept:
print("You must enter an integer")
if isint==True:
ints.append(new_int)
Post a Comment for "Python Code-while Loop Never End"