Reputation: 11
I've written a program that asks a user for a post code. Here's the code:
_code = str(input('Enter your post code: '))
_exit = True
while _exit:
print(_code)
while len(_code) != 5:
if len(_code) > 5:
print("to long")
_code = str(input('Enter your post code: '))
elif len(_code) < 5:
print("to short")
_code = str(input('Enter your post code: '))
else:
print('post code is: ' + str(_code))
break
The problem is when I start the program it works fine, but when the input has got a len(_code)
equal to 5
it should jump to else statement but it doesn't. It just stops running program (break). I expect the program to print:
post code is: xxxxx
I've downloaded QPython 1.2.7 on my mobile phone, and there it works perfectly!
Upvotes: 1
Views: 245
Reputation: 6500
Looking at you code it seems like you should simply get rid of the else
block and move it outside the while
block. This is because the while
loop aims to keep asking the user for an input as long as he doesn't input 5
.
On receiving 5
, he should not be inside the while
block. Try to write this instead,
while len(_code) != 5:
if len(_code) > 5:
print("too long")
_code = str(input('Enter your post code: '))
elif len(_code) < 5:
print("too short")
_code = str(input('Enter your post code: '))
# The print is no longer inside an `else` block
# It's moved outside the loop
print('post code is: ' + str(_code))
As further improvements, you could move _code = str(input('Enter your post code: '))
outside the if
/ elsif
all together. Something like this would work,
# Initialize to zero length
_code = ""
while len(_code) != 5:
# Executed each time at beginning of `while`
_code = str(input('Enter your post code: '))
if len(_code) > 5:
print("too long")
elif len(_code) < 5:
print("too short")
print('post code is: ' + str(_code))
Upvotes: 1
Reputation: 21
The else clause is inside the while loop so won't be executed when len(_code)=5. If you restructure your code like below, it should work.
_code = str(input('Enter your post code: '))
_exit = True
while _exit:
print(_code)
while len(_code) != 5:
if len(_code) > 5:
print("too long")
_code = str(input('Enter your post code: '))
elif len(_code) < 5:
print("too short")
_code = str(input('Enter your post code: '))
print('post code is: ' + str(_code))
break
Upvotes: 0
Reputation: 3895
It's not going to hit the else
clause. If len(_code)
is 5 you are NOT getting into this
while len(_code) != 5:
So you are not getting into the if/else
in there
I think you just want to get rid of that while statement.
Upvotes: 2