-2

Tell me the code that would support this, because if I enter a word into an integer input the program crashes. I know this would be a simple one line code, but I just can't get my head around it.

Traceback (most recent call last):
  File "N:/Controlled Assessment/Task Three v1.py", line 9, in <module>
    c1_strength = int(input("What is character 1's strength? (Between 1 and 50, must be number): ")) #asks user for the strength value of character 1
ValueError: invalid literal for int() with base 10: 'fresd'
Bach
  • 6,145
  • 7
  • 36
  • 61

1 Answers1

2

Try this:

while True:
    try:
        a = int(input())
    except ValueError:
        print "Enter an integer"
        continue
    break
Aswin Murugesh
  • 10,831
  • 10
  • 40
  • 69
  • 1. use `input()` instead of `raw_input()` because OP uses Python 3 otherwise he would get `NameError` on the `input()` call. 2. `a.isdigit()`, `int(a)` and `re.match('\s*\d+\s*$', a)` may have different ideas about what a number is. It is best to use `try: result = int(a) except ValueError` directly – jfs Mar 12 '14 at 11:32
  • @J.F.Sebastian: I agree with you on the `input()` part, but i don't agree in the second part. The OP specified that the input should be integers. So this should work right? – Aswin Murugesh Mar 12 '14 at 11:37
  • @AswinMurugesh See `EAFP` [here](http://docs.python.org/2/glossary.html) – Burhan Khalid Mar 12 '14 at 11:39
  • no e.g., `'\u2466'.isdigit()` is true but `int('\u2466')` produces `ValueError` – jfs Mar 12 '14 at 11:40
  • @BurhanKhalid: Got it!! – Aswin Murugesh Mar 12 '14 at 11:44
  • @J.F.Sebastian: How about now? – Aswin Murugesh Mar 12 '14 at 11:46
  • don't use bare `except:` use `except ValueError` instead. – jfs Mar 12 '14 at 11:47