How do i fix this error, whenever i enter data that should cause an exception more than once the program crashes. Here is my code and what it outputs, it should keep repeating until correct data is entered.
flag=False
while flag==False:
try:
number=int(input("Enter number of books: "))
except ValueError:
print("Please enter number of books as a positive whole number ")
number=int(input("Enter number of books: "))
else:
flag=True
Traceback (most recent call last):
File "C:\Users\Alex\OneDrive\Documents\ComputerScience\Intro2.py", line 5, in <module>
number=int(input("Enter number of books: "))
ValueError: invalid literal for int() with base 10: '3.3'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "C:\Users\Alex\OneDrive\Documents\ComputerScience\Intro2.py", line 8, in <module>
number=int(input("Enter number of books: "))
ValueError: invalid literal for int() with base 10: '3.4'
CodePudding user response:
Try this it evaluates if your string is a digit, then breaks out of the look. Exception handling is expensive in computing terms and should be avoided where possible
while True:
no_of_books = input("enter number of books")
if no_of_books.isdigit():
break
The reason your code didn't keep repeating was that it thew an exception on line 5 which was wrapped in the try block then in the except block it threw another exception on line 8 which was not wrapped in a try block so it terminated
Updated in response to comment, simply cast your string to an int like this then use int_number_of_books
as the int
while True:
no_of_books = input("enter number of books")
if no_of_books.isdigit():
int_number_of_books = int(no_of_books)
break
if int_number_of_books <= 0:
# your code here