Part 2: mathGame.py

Congratulations for completing Part 1 and welcome to Part 2. Part 2 is going to be a breeze as we’ll mainly just be calling the functions we defined earlier. Exercise 5: Writing the Main Program First, let’s enclose our main program in a try, except statement.

We want to handle any unforeseen errors when running the main program. We’ll start by writing the code for the try block. Firstly, we need to import the myPythonFunctions module. Next, let’s prompt the user for his/her username and assign the value to the variable userName. Pass this variable as a parameter to the function getUserScore(). getUserScore() will either return the score of the user or return ‘-1’ (if the user is not found). Let’s cast this result into an integer and assign it to the variable userScore. Now, we need to set the value of another variable newUser. If the user is not found, newUser = True, else newUser = False. If newUser = True, we need to change userScore from -1 to 0. The next part of our program involves a while loop. Specifically, our program will prompt for input from our user to determine if it should terminate the program or do something else. Step 1: You need to declare another variable userChoice and give it an initial value of 0. Step 2: Next, using a while loop, compare userChoice with a string of your choice, say “-1”. If userChoice is not the same as “-1”, call the function generateQuestion() to generate a new question. Step 3: generateQuestion() will return the score that the user got for that question. Use this result to update the variable userScore. Step 4: Finally, in order to prevent an infinite loop, we need to use the input() function again within the while loop to accept user input and use it to update the value of userChoice. Got that? Try coding it. Doing the actual coding will make everything clearer. Finally, after the while loop terminates, the next step is to update the userScores.txt file. To do that, we simply call the updateUserPoints() function. That’s all for the try block. Now for the except block, we simply inform the user that an error has occurred and the program will exit. That’s it! Once you finish this step, you’ll have a complete program, your first program in Python. Try running the program mathGame.py. Does it work as expected? Excited? I sure hope you are as excited about it as I am. 🙂

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top