Trybotics Logo

Coding an Addition Game in Python

DESCRIPTION

  • This instruction set will teach you step-by-step how to program an addition game that prompts users to answer simple addition problems using random numbers from 0-9 and prints whether they are correct or not!
  • Click the image in each step to enlarge it and view the code for that part.

Description:

  • This instruction set will be using the IDLE Python program!
  • After launching, create a New File in your Python application to start coding.

Description:

  • We will be using it to generate random numbers!

Description:

  • The input of integer n will determine the number of addition problems the game will print when called!
  • This code calls the method "game(n)".

Description:

  • Within the game method, initialize a Boolean variable to be used in a ‘while’ loop and an integer to be used as a count variable for correct answers.
  • This code calls the Boolean “wrk” and integer “cnt”.
  • Remember the importance of indents in Python, as they determine what code is nested where!

Description:

  • This will loop for the length of the input integer n!

Description:

  • Within this ‘for’ loop, use random.randrange(1,10) to initialize two random integer values between 1 and 9.
  • This code calls these “val1” and “val2”.
  • Then set the Boolean value to True!

Description:

  • While still within the ‘for’ loop, start a ‘while’ loop while the Boolean variable is True.

Description:

  • Next in this ‘while’ loop, we create a try-except statement.
  • In your ‘try’ case, print out an addition question using value 1 and value 2 and define an answer variable as the user’s input (this code defines the answer variable as “ans”).

Description:

  • Within the ‘try’ case, code an if-else statement testing whether ans = val1 + val2.

Description:

  • Still within the 'try' statement, if true:
    • Print a correct message!
    • Set the Boolean variable to False!
    • Increment count by 1!

Description:

  • In the 'else' statement, print an incorrect message and set the Boolean value to False.

Description:

  • In the ‘except’ case, print an error message to account for non-integer inputs!

Description:

  • After all those nested statements, print the count of problems out of n that the player got right!

Description:

  • Remember the importance of indentation in Python, as this program utilizes many nested statements.
  • Your final program should look like this.

Description:

  • After following these steps to code your math program, go ahead and hit Run Module.
  • Enjoy your simple addition game!


YOU MIGHT ALSO LIKE