Reputation: 11
I decided to learn python and I chose the book "The python book" to do so but I encountered a problem while coding one of the exercise programs, I'm doing a program that shows how control structures work but it gets stuck in a while loop, I think it is because a boolean variable (isint) is not setting to true so it just gets stuck there, but I'm not sure because I'm new to programming.
#!/usr/bin/env python2
import sys
target_int=raw_input("How many integers? ")
try:
target_int=int(target_int)
except ValueError:
sys.exit("You must enter an integer")
ints=list()
count=0
while count<target_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
print("Using a for loop")
for value in ints:
print(str(value))
print("Using a while loop")
total=len(ints)
count=0
while count<total:
print(str(ints[count]))
count+=1
I would get this result everytime I ran the program:
jonathan@Jonathan:~/Python$ ./construct.py
How many integers? 1
Please enter integer1:2
Please enter integer1:3
Please enter integer1:4
Please enter integer1:4
Please enter integer1:23
Please enter integer1:13
As you can see no matter what I put there the while loop just keeps going.
Upvotes: 0
Views: 117
Reputation: 79
You aren't setting isint
flag to true when checking for an integer.
while count<target_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
Upvotes: 1
Reputation: 15071
First your indentation looks wrong for:
if isint==True:
ints.append(new_int)
count+=1
Then you should add isint = True
in (at the end of) the block
try:
new_int=int(new_int)
Upvotes: 0
Reputation: 103437
Indentation is important in python:
while count<target_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
This is two separate blocks of code: the if isint==True:
part is not inside the while count<target_int:
block.
You need to change it to this:
while count<target_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
Additionally, isint
is never set to anything but False
, anywhere. So the body of your if
statement is never going to execute.
You probably want to set isint
to True
when you know the input is a valid integer.
Upvotes: 1