[Tutor] invalid literal for int error in Game loop

Steven D'Aprano steve at pearwood.info
Thu Dec 20 21:51:03 CET 2012


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.



-- 
Steven


More information about the Tutor mailing list