Small Python Program for combat in a RPG; help?

Post » Fri Aug 30, 2013 2:54 pm

Well, the first thing is that input() always returns a string. Plain fact. That's how python (3.x) works. It's always going to be a string.

This is why you need to typecast the input to an int using int(input("input something ")). Now you have an int!

Except... Not if the user types something not compatible with an Int.

Example of this:

Python is smart enough to know that "10" is a string of the Int 10. However, it's not smart enough to know that "ten" is a string representation of the number 10. As such, if you try to int("ten") you'll get an error (go ahead and try).

When dealing with things that can kick up errors, it's proper to put your code in a try/catch. A try/catch tells Pythong "Hey! This code is risky and might kick up an error, so keep an eye on it for me, ok?" Python will then keep an eye on it. If anything inside the try block kicks up an error, Python quits running the try block and goes to the catch block (which in Python is called except )

The name of the exception trying to treat a non-int-compatible item as an int is known as ValueError

As such "except ValueError:" catches any time a user types "ten" in. And prints to the screen "You didn't type a number". The while loop then loops again, prompting the user for input (because userinput still isn't between min or max).
User avatar
james kite
 
Posts: 3460
Joined: Sun Jul 22, 2007 8:52 am

Post » Fri Aug 30, 2013 9:18 am

I was trying to wrap my head around this "Try" thing for the last hour, googling and what not. Thanks for some info. I should have just asked. Yes, I note I wasted plenty of time.

Moving forward, let me try something...

User avatar
Scott
 
Posts: 3385
Joined: Fri Nov 30, 2007 2:59 am

Previous

Return to Othor Games