[Tutor] invalid literal for int error in Game loop

Dave Angel d at davea.name
Thu Dec 20 22:07:40 CET 2012


On 12/20/2012 03:51 PM, Steven D'Aprano wrote:
> On 21/12/12 07:40, Ciaran Mooney wrote:
>
>> def difficultyLevel():
>>      FPS = ''
>
> Here you set the variable FPS to the empty string.
>
>>          if event.type == KEYDOWN:
>>              if event.key == ord('b'):
>>                  FPS = 30
>>              elif event.key == ord('m'):
>>                  FPS = 70
>>              elif event.key == ord('h'):
>>                  FPS = 120
>
> These three options set FPS to an integer value. But notice that if
> the user
> does not press one of the b m or h keys, FPS never gets changed so it
> still
> has the initial value of the empty string.
>
>>      return FPS
>>
>> The function is then called and FPS converted too a  integer value in
>> the main game loop as follows:
>
>>      FPS = int(difficultyLevel())
>
>> However I keep getting the following error:
>>
>> ValueError: invalid literal for int() with base 10: ''
>
> There are three possible values that difficultyLevel() may return:
>
> * if the user hits the 'h' key, it returns the integer value 120;
> * if the user hits the 'm' key, it returns the integer value 70;
> * if the user hits the 'b' key, it returns the integer value 30;
> * otherwise, it returns the empty string.
>
> Three of the four values are already ints and don't need to be converted;
> the fourth cannot be converted because it is not a numeric string.
>
> To fix this, change the line FPS = '' to a default integer value,
> say, FPS = 30.
>
>
>

Or even better, remove that default value and add an else clause to the
if/elif/elif section.  That way it's all in one place, and it's more
obvious that the return value will always be an int.

And of course you can remove the int() call on the line
    FPS = int( difficultyLevel() )
becomes
    FPS = difficultyLevel()

BTW, when quoting an error, please include the whole traceback, not just
one line of it.  Here it was obvious, but many times other parts will be
very useful, or even essential.



-- 

DaveA



More information about the Tutor mailing list