0

I've tried to find out how to check for string input for mario.py. I know to check for the range of integers when getting input from the user, but if they enter a string instead of a number, is there any way to set up a condition to check for that? I've looked through the documentation but everything I try comes back to:

Enter height of pyramid no higher than 23:
25
 Enter height of pyramid no higher than 23:
foo
Retry: ^CTraceback (most recent call last):
  File "mario.py", line 8, in <module>
    height = cs50.get_int()
  File "/usr/lib/python3/dist-packages/cs50/cs50.py", line 49, in get_int
    s = get_string();
  File "/usr/lib/python3/dist-packages/cs50/cs50.py", line 78, in get_string
    s = sys.stdin.readline()
KeyboardInterrupt

It seems if I use get_int() and the user enters a string, then right away that's an error for the program.

0

Maybe you were using the method incorrectly?

If you import the cs50 library in python like this:

import cs50

at the top of your screen, you should be able to use

cs50.get_int()

which does the same thing as get_int() in c.

It takes a bit of getting used to because we use the dot operator, and I think the reason we do this is explained in the lecture, if I remember correctly it is because cs50 is treated as an object by python (like a struct) and so the dot operator is used to get the method from the cs50 object which we already imported.

However if you don't want to use cs50's library check out method .isdigit() (best to search for it , it is about 1/3 down the page) which should be enough to ensure that the input is an integer.

3
  • I did use cs50.get_int() and for the ints that worked. The problem came when a user enters a string. Rather than repeating the "Enter..." statement, the response is Retry: I tried any number of methods to check if height is a string and to repeat the Enter statement if so, but it appears the error occurs even before I reach the if statement and happens because a user enters a string rather than the integer asked for by the function of cs50.get_int(). – KitSeason Jul 13 '17 at 19:59
  • You mean that you want to override the implementation by the cs50 staff? I thought the idea of cs50.get_int() is that is prompts the user to retry. As for how to customize that to your "Enter..." statement, I don't know. – dumbitdownjr Jul 13 '17 at 20:04
  • Yes, I thought that we needed to return the user to the original prompt if they didn't put in the correct input, but I see that Retry: has the same outcome. Thanks. – KitSeason Jul 13 '17 at 20:22

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .