# Python computing quiz

The following code is a computing quiz:

import random

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

#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("\nYour final score was " + str(score))

#store the user's input...
again = input("Enter any key to play again, or 'q' to quit.")

#... and quit if they types 'q'
if again.lower() == 'q':
playing = False

• What specifically about your code are you looking to improve? – Joseph Farah Feb 16 '16 at 21:26
• It is common practice not to post too many review questions at the same time. Although your other questions is currently on-hold, you should focus on one questions at the time... And it seems like you're having indentation issues here as well... – holroy Feb 16 '16 at 21:30
• Please note that normally having this much errors in your indentations is a close reason (as you've experienced) in your other post. And code should not be edited after posting, so take on the next post (or when editing your closed post) that the indentation is correct and the same as in your editor. – holroy Feb 16 '16 at 21:40

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.

• @Stefan Pochmann Yes, you could do while (playing) { in C99, assuming playing as a bool, or in ANSI C (C89) if playing were an int. However, Python doesn't have stack ints or bools, everything is a pointer. And if playing is an int*, then you most certainly cannot just do while (playing) {(unless, of course, your plan is that users have to keep playing until you cause a stack overflow to get playing to stop being positive. But I suppose you're right, it's not immediately clear to any inexperienced C programmers what is meant with that comparison. – Tersosauros Feb 16 '16 at 22:32
• @Tersosauros Why would you make playing an int*? It should clearly be a bool (or int) in C as well. I doubt it's about my C experience, I think it's just not at all an example for the argument your trying to force into this. – Stefan Pochmann Feb 16 '16 at 22:50
• @Stefan Pochmann C89 (ANSI standard C) doesn't have bool, as I pointed out. And Python doesn't have stack types, as I also pointed out. I don't think I'm the one trying to force anything? As I said, the comparison may not be immediately clear. Perhaps you should suggest an edit if you believe it can be so easily improved? – Tersosauros Feb 16 '16 at 22:53
• I know it doesn't have bool, that's why I said "or int". Why do you point it out again? And no idea what your point is with stack types (as you just stated it without making a point about it) and why you think I didn't read it. You are trying to force a C comparison into this. If I were to edit it, I'd just take out the talk about C and just point out that == True is pointless here. – Stefan Pochmann Feb 16 '16 at 23:10