Below is a piece of code from Python which has been bothering me for a while.
var=0
while (var <1 or var>100):
var=raw_input('Enter the block number ')
if (var >=1 and var<=100):
print '\nBlock Number : ',var
else:
print 'ERROR!!! Enter again.'
The problem is that the while loop iterates continuously without breaking. Can anyone help me how to break the loop.
Is there any way to implement a do..while in Python?
5 Answers 5
The problem is that raw_input returns a string. You're comparing a string with an integer which you can do in python 2.x (In python 3, this sort of comparison raises a TypeError), but the result is apparently always False. To make this work you probably want something like var=int(raw_input('Enter the block number'))
From the documentation:
objects of different types always compare unequal, and are ordered consistently but arbitrarily.
4 Comments
ints are always less than strsTypeError)You're needlessly checking var twice, and you're trying to compare int and str (because raw_input returns a string), which doesn't work right. Try this:
var=0
while True:
var=int(raw_input('Enter the block number '))
if (var >=1 and var<=100):
print '\nBlock Number : ',var
break
else:
print 'ERROR!!! Enter again.'
Comments
You should convert your string to int.
var=0
while (var <1 or var>100):
# I changed here
var=int(raw_input('Enter the block number '))
if (var >=1 and var<=100):
print '\nBlock Number : ',var
else:
print 'ERROR!!! Enter again.'
Comments
You're running into an issue that strings (as returned by raw_input) are always greater than integers:
>>> "25" > 100
True
You need to convert your input to an integer first:
var = int(raw_input("Enter the block number "))
Of course, you'll want to be resilient in the face of bad input, so you'll probably want to wrap the whole thing in a try block.
Comments
hello you need to enter "break" and also var should be an integer, see below
while True:
var=int(raw_input('Enter the block number '))
if (var >=1 and var<=100):
print '\nBlock Number : ',var
break
else:
print 'ERROR!!! Enter again.'
continue
hope this helps