Reputation: 45
The While loop I have created won't exit. I have tested it multiple times and can't figure out why. If I enter the ISBN code of "0764526413" it returns "All Numbers" and exits the loop. BUT if I test it with a letter in the code (making sure it loops back around), it goes back to the top and asks me to enter the code again. I do, and I enter the all numeric code. At this point, I'm in an infinite loop. Even when entering the all numeric code the second time, it won't exit. I don't understand why it seems to be looping correctly if I enter the all numeric code the first go-round, but not if I enter an incorrect code and THEN a correct code.
Code is below:
# Variable to start loop
Digits = 'N'
ISBN_temp = ''
# The loop asks for the ISBN, removes the dashes, removes check digit,
# And checks to see if the info entered is numeric or not.
while Digits == 'N':
print('Please enter the ISBN code with or without the check digit.')
temp_ISBN = input('You may enter it with dashes if you like: ')
ISBN_no_dash = temp_ISBN.replace('-','')
no_dash_list = list(ISBN_no_dash)
# If the user entered a check digit, remove it.
if len(no_dash_list) == 10:
del no_dash_list[9]
ISBN_no_check = no_dash_list
elif len(no_dash_list) == 13:
del no_dash_list[12]
ISBN_no_check = no_dash_list
else:
ISBN_no_check = no_dash_list
# Turn list back into a string and then make sure all characters are
# Numeric.
for num in ISBN_no_check:
ISBN_temp = ISBN_temp + str(num)
if ISBN_temp.isnumeric():
print('All numbers')
Digits = 'Y'
else:
print()
print('Please verify and reenter the ISBN number.')
print()
Digits = 'N'
I know some of the coding may seem weird, but this is actually a small part of a bigger program I'm writing for homework. This is the only part that is giving me problems. Any help is greatly appreciated. I'm really hoping it's something small that I'm just not seeing because I've been working on the whole program for days. Thank you very much everyone! Please know that I need this to either return either "All Numbers" and exit the loop when the ISBN is entered correctly, or to loop back if anything other than numbers is entered.
Upvotes: 0
Views: 1526
Reputation: 191983
ISBN_temp is being kept between iterations of the while loop. There's no clear reason for keeping it outside of the while loop
An alternative to this loop
for num in ISBN_no_check:
ISBN_temp = ISBN_temp + str(num)
Is to generate a new string from the numbers
ISBN_temp = ''.join(str(num) for num in ISBN_no_check)
You can also use a while True
with a break
when the numeric check passes. Then you don't need digits
variable
Upvotes: 2
Reputation: 24291
You should re-set ISBN_temp
to empty string prior to:
for num in ISBN_no_check:
ISBN_temp = ISBN_temp + str(num)
Otherwise you keep on adding to the very same string with every iteration.
Upvotes: 3