-3

I'm working on a program that prompts a user for a number within a range of integers they've entered. If the number they enter is out of range, they're prompted to give another, and if they enter a letter instead they're prompted to change their answer as well. Here is what I've got:

def code_one(d, f):
    s = input('Enter a number between' + str(d) + 'and' + str(f) + ': ')
    s = int(s)
    if int(d) <= s <= int(f):
        return s
    else:
        while s < int(d) or s > int(f):
            s = input(str(s) + 'is out of range. Please try again. ')
            s = int(s)
            if s < int(d) or s > int(f):
                continue
            else:
                return s
        while s.isdigit == False:
            s = input(str(s) + 'is not a number. Please try again.' )
            if s.isdigit == False:
                continue
            else:
                return s

It works fine up until the line reading "while s.isdigit == False:" and then, if I input a letter instead of a number, I get the error "invalid literal for int() with base 10: 'x'", (the x being whatever letter I happen to enter). What can I do to fix this?

  • 1
    you have to call isdigit: `s.isdigit()`. – Daniel Oct 03 '18 at 21:58
  • You should check whether it's a digit first, instead of converting to an integer first. – John Gordon Oct 03 '18 at 21:59
  • `isdigit` isn't how you test whether a string represents an integer anyway. It rejects `'-1'`. – user2357112 Oct 03 '18 at 21:59
  • You are converting `s` to string using `s = int(s)` and hence if you enter 1, you convert it from string to int. Now if you check int to be `isdigit()`, you will get an error. So better check `if str(s).isdigit()` – Sheldore Oct 03 '18 at 22:01

1 Answers1

0
def code_one(d, f):

    while True:
        answer = input('Enter a number between %d and %d: ' % (d, f))

        try:
            answer = int(answer)

        except ValueError:
            print('%s is not a number.  Please try again.' % answer)
            continue

        if d <= answer <= f:
            return answer

        else:
            print('%d is out of range.  Please try again.' % answer)
John Gordon
  • 29,573
  • 7
  • 33
  • 58