HiveBrain v1.2.0
Get Started
← Back to all entries
patternpythonMinor

Python computing quiz

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
quizpythoncomputing

Problem

The following code is a computing quiz:

```
import random

#the questions/answer dictionary
my_dict = {
"Base-2 number system" : "binary",
"Number system that uses the characters 0-F" : "hexidecimal",
"7-bit text encoding standard" : "ascii",
"16-bit text encoding standard" : "unicode",
"A number that is bigger than the maximum number that can be stored" : "overflow",
"8 bits" : "byte",
"1024 bytes" : "kilobyte",
"Picture Element. The smallest component of a bitmapped image" : "pixel",
"A continuously changing wave, such as natural sound" : "analogue",
"the number of times per second that a wave is measured" : "sample rate",
"A binary representation of a program" : "machine code"
}

#welcome message
print("Computing Revision Quiz")
print("=======================")

#the quiz will end when this variable becomes 'False'
playing = True

#While the game is running
while playing == True:

#set the score to 0
score = 0

#gets the number of questions the player wants to answer
num = int(input("\nHow many questions would you like: "))

#loop the correct number of times
for i in range(num):

#the question is one of the dictionary keys, picked at random
question = (random.choice( list(my_dict.keys())))
#the answer is the string mapped to the question key
answer = my_dict[question]

#print the question, along with the question number
print("\nQuestion " + str(i+1) )
print(question + "?")

#get the user's answer attempt
guess = input("> ")

#if their guess is the same as the answer
if guess.lower() == answer.lower():
#add 1 to the score and print a message
print("Correct!")
score += 1
else:
print("Nope!")

#after the quiz, print their final score
print(

Solution

Just some general syntax notes I have after a quick scan of your code...

Python isn't C, not all evaluations are about equality!

The line while playing == True:, immediately struck me as odd. Python evaluates things in if-statements/while-loops/etc. This is different to a language such as C, which always uses equality (or inequality) for such things.

Specifically, if we take the variable playing to just be (something that is either True or False), and then substitute that into the expression.. We get:

(something that is either True or False) == True


This will ALWAYS evaluate to the same value as just using playing - since it's already either True or False.

Input checking, and why (when dealing with users) even sane people validate

The following excerpt:

#gets the number of questions the player wants to answer
num = int(input("\nHow many questions would you like: "))


As you've discovered, input is returning you a string, and the way to cast this to an int is with (the appropriately named) int. However, if a user enters something like "Tersosaur" instead of a number, you will get a ValueError (raised by int).

The way to deal with this is to use a try/except, like this:

#gets the number of questions the player wants to answer
num = input("\nHow many questions would you like: ")
try:
    num = int(num)
except ValueError:
    print "Error '%s' is not a valid number".format(num)


Just a recommendation, Make your code more Pythonic

I noticed a lot (all) of your initialization and start-up code (things such as setting score = 0, etc) happens in the program itself, and not in a main block.

You don't technically need this, but it is best practise to use a block like this:

if __name__ == "__main__":
    ...initialization code goes here


Functional Decomposition is your frenemy friend

Functional Decomposition is important, even in small program like this. It improves the readability, understandability and (perhaps most importantly here) maintainability of your code.

At the moment, all of your logic is wrapped up inside this mainloop style sequence of commands. The way you get input from the user, the way you keep score, how you check if their answers are correct, etc. All of these ways and hows are behaviours, which in Python can* become methods.

* Note: Functional Decomposition is not ALWAYS your friend (hence frenemy). If you go to far you'll end up with just as big a mess of spaghetti code as you started with. For example, don't extract each and every line from your loop into a separate function and think it's functionally decomposed. Functional decomposition is about the identification of behaviours.

Code Snippets

(something that is either True or False) == True
#gets the number of questions the player wants to answer
num = int(input("\nHow many questions would you like: "))
#gets the number of questions the player wants to answer
num = input("\nHow many questions would you like: ")
try:
    num = int(num)
except ValueError:
    print "Error '%s' is not a valid number".format(num)
if __name__ == "__main__":
    ...initialization code goes here

Context

StackExchange Code Review Q#120235, answer score: 4

Revisions (0)

No revisions yet.