Welcome to the CSC Q&A.
Get help and give help!
Write great code!
It is our choices... that show what we truly are, far more than our abilities.

Categories

+5 votes

For the size section of the problem, I am using the function :

get_int_number(prompt, low_num, high_num) from a previous question.

How do I avoid an error when checking if the user's input is an integer? I originally had an int(input( but then I decided to convert it to an integer after checking to see if it is one.

asked in CSC201 Spring 2021 by (1.1k points)

1 Answer

+1 vote
 
Best answer

For this problem, you can assume that the user DOES type in an integer (although the integer they type could be out of the acceptable range).

So yes, you should just use the get_int_number(...) function that you developed for the earlier Q1, and yes you can use int(input(...)). In fact, my answer key code does use int(input(...))

So, if you're getting an error on Q5, it seems likely that something else is wrong... maybe you're not reading all of the other data correctly, or could there be a problem with your get_word(...) function instead, perhaps where it doesn't keep asking for input enough times, causing one of the "words" that the user to types to get treated as the input for the get_int_number(...) function?

However, to answer your original question, if you want to check whether the string that is typed in can be converted to an integer, the isdigit() method of the str class would be a decent option, to check to make sure that the string they entered only contains numeric digits in it.

(There is another approach that we haven't talked about yet, where we allow the error to occur, and then catch the error and handle it, rather than letting the program die with a red error message. See Zelle section 7.4 if you want to read ahead about Error/Exception Handling in Python.)

answered by (15.5k points)
selected by
...