I wish to add a feature which tells the user when he/she has answered correctly to the random maths questions that are given.
import random
def answers():
correct_answer_P_ = ((str(difficulty_one + difficulty_one))) #P = PLUS, ADDITION +
correct_answer_M_ = ((str(difficulty_one * difficulty_one))) #M = MULTIPLY *
correct_answer_T_ = ((str(difficulty_one - difficulty_one))) #T = TAKE AWAY, MINUS -
def random_symbols():
symbols = random.choice (["+","-","*"])
return symbols
def difficulty_one():
dif_one = random.randrange (1,10,1)
return dif_one
def questions():
question = (str(difficulty_one())) + random_symbols() + (str(difficulty_one())) + " = "
return question
start = input("press start to begin!: ")
if (start == "start"):
print ("here's ten questions, good luck!")
for questions_num in range(1,11):
print ("Question ",questions_num)
input(questions())
if (random_symbols == "+"):
if (dif_one == correct_answer_P_):
print("correct!")
elif(random_symbols == "-"):
if (dif_one == correct_answer_T_):
print("correct!")
elif(random_symbols == "*"):
if (dif_one == correct_answer_M_):
print("correct!")
else:
print("incorrect!")
I tried this from getting some advice from a friend who said that i needed to create variables for each symbol that would be randomly inserted; the variables should compare the users answer and say its correct but it skips all the if statements and goes straight to saying its incorrect.
Any suggestions? Don't be harsh if I'm doing something dumb because I've just started python at the moment.
Quick note the part in this code has been cut out of my original to make it simple for people to see what I'm trying to do.
There's a way easier way of implementing this. Try this instead:
import operator
questions = [(1,2), (4,2), (8,1), (10,100)] # operands for your questions
operators = {"+" : operator.add,
"-" : operator.sub,
"*" : operator.mul}
# a dictionary containing each operator's symbol and the resulting function
# (operator.add(x,y) is equivalent to x+y)
for num, operands in enumerate(questions,start=1):
# iterate through each set of operands, enumerating starting at 1
operator = random.choice(operators)
# return a random symbol from operators
answer = operators[operator](*operands)
# operators[operator] is the function, which we then call with the operands
q_text = "{} {} {} = ?".format(str(operands[0]), operator, str(operands[1]))
print("Question {}".format(str(num)))
print(q_text)
user_answer = input(">>")
if float(user_answer) == answer:
# correct!
else:
# fail!
Related
This is a small quiz program that loops 5 times, every time it loops a different totally random question is asked. I keep getting an error that says (rand_quiz() ) function not defined, although I have defined it. I think I've done it wrongly. Could you help me correct it. Code is below.
import random
import operator
operators = {
"+":operator.add,
"-":operator.sub,
"*":operator.mul,
"/":operator.truediv,
}
questions = 0
star = 0
def star_score():
while questions <= 4:
star = star + 1
return star
def check_ans():
if que_ans == que:
print("Correct! You earned yourself a star.")
star_score()
elif que_ans != que:
print("Wrong! Better luck next time.")
def rand_quiz():
rand_num1 = random.randint(9, 999)
rand_num2 = random.randint(9, 999)
ops = random.choice(list(operators.keys()))
que = int(operators[ops](rand_num1, rand_num2))
print("What is",rand_num1, ops, rand_num2)
que_ans = input(">>>")
if que_ans.isdigit():
check_ans()
else:
return("Error! Invalid input.")
def quiz_loop():
while questions <= 4:
rand_quiz()
quiz_loop()
In python, indentation is very important. You have defined some functions at an indented level. You must define your functions at the base level.
I'm making a maths skills testing program and was wondering if there's a way in which i can make random questions appear in my program instead of having to do this every single time;
import time
start = time.time()
userinput = input("\nWhat is 11+7?")
if userinput=="18":
print("\nNot bad, lets try something a little harder...")
print('It took you {0:0.1f} seconds to answer the
question'.format(time.time() - start))
else:
print("\nAt least you got one right")
print('It took you {0:0.1f} seconds to answer the
question'.format(time.time() - start))
exit()
Also, how can i add a while statement into this? I would also like to add a def function in if possible. Thanks.
Choose a random operator and random numbers:
import operator
import random
ops = {'+': operator.add,
'-': operator.sub} # add mul and div if you wish
keys_tuple = tuple(ops.keys())
num_a = random.randint(1, 10) # use larger range if you wish
num_b = random.randint(1, 10) # use larger range if you wish
op = random.choice(keys_tuple)
print('{}{}{}=?'.format(num_a, op, num_b))
expected_answer = ops[op](num_a, num_b)
user_answer = int(input())
if user_answer == expected_answer:
print('Correct')
else:
print('Wrong')
As for the while, simple wrap the whole code in a while True loop that breaks if the user inputs a certain value (ie 'quit', which will currently raise a ValueError)
This is almost entirely #DeepSpace's code, but to answer your question of how to add the while loop, just throw all of the code after the initial definitions into the scope of a while loop:
import operator
import random
ops = {'+': operator.add,
'-': operator.sub} # add mul and div if you wish
keys_tuple = tuple(ops.keys())
while True:
num_a = random.randint(1, 10) # use larger range if you wish
num_b = random.randint(1, 10) # use larger range if you wish
op = random.choice(keys_tuple)
print('{}{}{}=?'.format(num_a, op, num_b))
expected_answer = ops[op](num_a, num_b)
user_answer = int(input())
if user_answer == expected_answer:
print('Correct')
else:
print('Wrong')
So you want to make math problems basically? Here is what you need to do for that:
Make two random ints - step 1
See if the answer adds up to the answer - step 2
You can now try solving it yourself. In case you need some help, you can come back and see this:
from random import randint
def get_random_int(): # Function to get random int
random_num = randint(1, 20) #Gets an int between 1 and 20. Change if needed
return random_num
def check_answer(first_number, second_number, input_ans): # function to check answer correction
if (first_number + second_number == input_ans):
return "Correct answer!"
else:
return "Try again!"
number_1 = get_random_int()
number_2 = get_random_int()
user_input = input("What is %s plus %s?" % ( str(number_1), str(number_2) ))
# Wrap in str() to display as string
print( check_answer(number_1, number_2, int(user_input) ) )
# Wrap in int() because it is a number
And if you need this to loop constantly, wrap this in a while True: endless loop. Be sure to give a way to exit from it! (Use break in the code to exit from loop)
Hope this helps :)
Making a math quiz in python with random equations. I'm not sure how to stop the program from asking the same thing twice?
The program asks ten questions from a list of add, subtract or multiply, each using random numbers. I've managed to make the ten questions random, but I'm not sure how to stop it from choosing the same two numbers twice? For example, it would choose 1+3 for one question, but it will ask the same question multiple times after. Here is the code:
import random
#Asks for name
name = input("What's your name?")
#Stops user from entering invalid input when entering their class
classchoices = ["A","B","C"]
classname = input("What class are you in?")
while classname not in classchoices:
classname = input("Not a valid class, try again:")
print(name, ",", classname)
print("Begin quiz!")
questions = 0
def add(a,b):
addQ = int(input(str(a) + "+" + str(b) + "="))
result = int(int(a) + int(b))
if addQ != result:
print ("Incorrect!", result)
else:
print("Correct")
a = random.randint(1,12)
b = random.randint(1,12)
def multiply(a,b):
multQ = int(input(str(c) + "X" + str(d) + "="))
results = int(int(c) * int(d))
if multQ != results:
print ("Incorrect! The answer is", results)
else:
print("Correct")
c = random.randint(1,12)
d = random.randint(1,12)
def subtract(a,b):
subQ = int(input(str(e) + "-" + str(f) + "="))
resultss = int(int(e) - int(f))
if subQ != resultss:
print ("Incorrect! The answer is", resultss)
else:
print("Correct")
e = random.randint(1,12)
f = random.randint(1,12)
while questions in range(10):
Qlist = [add, subtract, multiply]
random.choice(Qlist)(a,b)
questions += 1
if questions == 10:
print ("End of quiz")
Any help would be appreciated, thanks.
The issue here is that you are generating random numbers at the start of the program, but not regenerating them every time a question is asked: your add function will always use a and b, multiply will always use c and d, and subtract will always use e and f for all of their respective calculations, the values of which never change.
In addition, the parameters you are inputting are of no value for multiply and subtract as you are just disregarding them and using c, d and e, f respectively without note of the parameters inputted.
In order to remedy both these issues, I would place the random generation of the numbers inside the while loop and make the functions use the correct inputted parameters for calculations.
Moreover, the while iteration is a bit redundant a simple for questions in range(10) without the extra bits is much more straightforward. Hence the questions variable is useless.
With all that in mind, here is the rewritten code.
import random
#Asks for name
name = input("What's your name?")
#Stops user from entering invalid input when entering their class
classchoices = ["A","B","C"]
classname = input("What class are you in?")
while classname not in classchoices:
classname = input("Not a valid class, try again:")
print(name, ",", classname)
print("Begin quiz!")
def add(a,b):
addQ = int(input(str(a) + "+" + str(b) + "="))
result = int(int(a) + int(b))
if addQ != result:
print ("Incorrect!", result)
else:
print("Correct")
def multiply(a,b):
multQ = int(input(str(a) + "X" + str(b) + "="))
results = int(int(a) * int(b))
if multQ != results:
print ("Incorrect! The answer is", results)
else:
print("Correct")
def subtract(a,b):
subQ = int(input(str(a) + "-" + str(b) + "="))
resultss = int(int(a) - int(b))
if subQ != resultss:
print ("Incorrect! The answer is", resultss)
else:
print("Correct")
for i in range(10):
Qlist = [add, subtract, multiply]
random.choice(Qlist)(random.randint(1, 12),random.randint(1, 12))
print ("End of quiz")
The program could be refined further by creating a function that manages the printing and checking of the result dependent on a third parameter that dictates what operation it should perform.
for each problem you have asked, you can add it to a set of "asked_questions" and use "in" method to test if already asked, and if yes, generate a new question.
not sure if it's the most efficient method, but it definitely works, and more than enough for your little application.
I am a programming beginner and I am trying to build a fill-in-the-blank quiz. I am almost finished but I am stuck on 2 problems I am not able to solve, whatever I do. I would really appreciate your help with this. Thank you for helping me with this!
If you try to run the code and play the game:
1) It prints the quiz according to the difficulty(easy-insane) and quiz you want to play(apple, bond and programming quiz) which is great but afterwards it prompts you to choose difficulty again (the player_level() function keeps going even though the player/user has already chosen the difficulty level. I don't really understand why it does it? The player_level() procedure seems perfectly okay and logical to me.
2) The errors:
a) local variable blanks_index referenced before assignment
b) global name list_of_answers is not defined.
I know that it is related to the initialize_game() function but I don't know how to change the code so it refers all the variables (blanks_index, answers_index, player_lives) correctly.
It could be solved by creating global variables(I guess) but that is not a good practice so I am trying to avoid it. Formerly, the whole function initialise_game() and play_game() were one function, but as there are over 25 lines of code in one function, it is not a good practice as it is long and messy and I know that I can separate it but I don't know how.
Here is the code:
"""3 diffferent quizzes : Apple quiz, James Bond quiz, Programming quiz"""
"""Quiz and answers about Apple"""
Apple_quiz = ("The most valuable company in terms of market cap in 2016 is, ___1___."
"It was founded in ___2___. Its flagship product is called ___3___."
"___1___ has many competitors, the biggest rival is ___4___,founded by"
" nobody but the richest man on the planet,___5___ ___6___.")
list_of_answers_Apple = ["Apple", "1976", "Iphone", "Microsoft", "Bill", "Gates"]
"""Quiz and answers about Bond"""
Bond_quiz = ("James Bond is agent ___1___. He serves his country,___2___ ___3___"
" against its enemies. His car of choice is usually ___4___ ___5___."
" His favorite drink is ___6___.")
list_of_answers_Bond = ["007", "United", "Kingdom", "Aston", "Martin", "Martini"]
"""Quiz and answers about programming basics"""
Programming_quiz = ("___1___ are created with the def keyword. ___1___ are also called ___2___"
" You specify the inputs a ___1___ take by adding ___3___ separated by commas"
" between the parentheses. ___3___ can be standard data types such as string, number"
" ,dictionary, tuple, and ___4___ or can be more complicated such as ___5___"
" and ___6___ functions.")
list_of_answers_Programming = ["Functions", "procedures", "arguments", "lists", "objects", "lambda"]
blank_space = ["___1___", "___2___", "___3___", "___4___", "___5___", "___6___]"]
#List of levels with corresponding lives/guesses that player can have
quiz_list = ["Apple", "Bond", "Programming"]
level_list = ["easy", "medium", "hard", "superhard", "insane"]
lives_easy = 5
lives_medium = 4
lives_hard = 3
lives_superhard = 2
lives_insane = 1
def choose_quiz():
""" Prompts player to pick a type of quiz and loads the quiz """
#Input = player_quiz (raw input from player)
#Output = loaded quiz, player chose
while True:
player_quiz = raw_input("Please, select a quiz you want to play: "
"(Apple, Bond or Programming): ")
if player_quiz == "Apple":
return Apple_quiz
elif player_quiz == "Bond":
return Bond_quiz
elif player_quiz == "Programming":
return Programming_quiz
else:
print "We don't have such quiz, pick again!"
def answers_for_quiz():
""" Loads appropiate answers to the quiz that player has chosen"""
#Input = player quiz (raw input from player)
#Output = loaded quiz answers from the quiz player chose
player_quiz_pick = choose_quiz()
if player_quiz_pick == Apple_quiz:
return list_of_answers_Apple
elif player_quiz_pick == Bond_quiz:
return list_of_answers_Bond
elif player_quiz_pick == Programming_quiz:
return list_of_answers_Programming
def player_level():
""" Loads a difficulty that player chooses """
#Input = player_level_input (raw input of player choosing a difficulty)
#Output = corresponding number of lives:
#Easy = 5 lives, Medium = 4 lives
#Hard = 3 lives, Superhard = 2 lives
#Insane = 1 life
while True:
player_level_input = raw_input("Please type in a difficulty level: "
"(easy, medium, hard, superhard, insane): ")
if player_level_input == "easy":
return lives_easy #Easy = 5 lives
elif player_level_input == "medium":
return lives_medium #Medium = 4 lives
elif player_level_input == "hard":
return lives_hard #Hard = 3 lives
elif player_level_input == "superhard":
return lives_superhard #Superhard = 2 lives
elif player_level_input == "insane":
return lives_insane #Insane = 1 life
else:
print "We do not have such difficulty! Pick again!"
def correct_answer(player_answer, list_of_answers, answers_index):
""" Checks, whether the the answer from player matches with the answer list. """
#Input: player_answer (raw input that player enters in order to fill in the blank)
#Output: "Right answer!" or "Wrong! Try again!" this output will be later used in the game
if player_answer == list_of_answers[answers_index]:
return "Right answer!"
return "Wrong! Try again!"
def initialize_game():
"""Functions that sets up a game so we can play it """
player_quiz_pick, player_level_pick, list_of_answers = choose_quiz(), player_level(), answers_for_quiz()
print player_quiz_pick
print "\nYou will get maximum " + str(player_level_pick) + " guesses for this game. Good luck.\n"
blanks_index, answers_index, player_lives = 0, 0, 0
#for elements in blank_space:
while blanks_index < len(blank_space):
player_answer = raw_input("Please type in your answer for " + blank_space[blanks_index] + ": ")
if correct_answer(player_answer,list_of_answers,answers_index) == "Right answer!":
print "Correct answer! Keep going!\n"
player_quiz_pick = player_quiz_pick.replace(blank_space[blanks_index],player_answer)
answers_index += 1
blanks_index += 1
print player_quiz_pick
if blanks_index == len(blank_space):
print "Congratulations! You nailed it! You are the winner!"
else:
player_level_pick -= 1
if player_level_pick == 0:
print "Game over! Maybe next time!"
break
else:
print "One life less, that sucks! Have another shot!"
print "You have " + str(player_level_pick) + " guesses left."
initialize_game()
Your main problem is that you keep calling the same functions over and over again and do not save the input into variables. Here are some tips about your code and questions:
You are not doing anything with your player_level() method call, so the player doesn't actually chooses a level in a way that affects the game. You should change the function call, so the returned value will be stored.
//the call to the method:
player_level_pick = player_level()
Afterwards, you keep calling the player_level() method, and not using the actual answer that the user supplied. Change all player_level() appearences to player_level_pick - the variable you use to save the answer (as I showed above). Same goes to all other unneeded function calls such as choose_level().
You should initialize number_of_guesses, player_lives, list_of_answers, and other vars to a matching value to player_level_pick as well, so it will hold the right value according to the level. Likewise, you should change this line:
# the line that checks if game is over
# change from:
if number_of_guesses == player_lives:
# to :
if number_of_guesses == 0:
In order to return multiple values, you have to use tuples. Using multiple return statements one after the other does not work anywhere.
so, instead of:
return list_of_answers
return number_of_guesses
return blanks_index
return answers_index
return player_lives
you should use tuples, and unpack them properly:
# the return statement:
return (list_of_answers, number_of_guesses, blanks_index, answers_index, player_lives)
# and the unpacking in the calling function:
list_of_answers, number_of_guesses, blanks_index, answers_index, player_lives = initialize_game()
this way, all of the returned values go into the wanted variables in the calling function. this way, you need to call the initialize_game() from play_game(). it will be the efficient way for you.
Just saying it again, as I said in the end of (4) - you should unit initialize_game() and play_game() into a single function (because a lot of data is the same needed data), or just call initialize_game() from play_game().
Better practice then using this recursivly: return choose_level(), you should use a while True: loop, and just brake when you get a proper answer.
I need to add a validation whilst in a while loop.
However when I use this validation it doesn't work and instead only comes up with the error message saying I haven't used a base 10/an integer when I want it to come up with the validation error message and let the user try again.
I don't know if having it in a while loop makes the validation I use any different, does it?
Also do I need to change this "def inputNumber(message):" to what my input is stored as?
And this "userInput = int(input(message))" to what my input is stored as?
import time
import random
question = 0
score = 0
name = input("What is your full name?")
print ("Hello " + name, "welcome to The Arithmetic Quiz. Use integers to enter the answer!")
time.sleep(2)
operands1 = list(range(2, 12))
operators = ["+","-","x"]
operands2 = list(range(2, 12))
while question < 10:
operand1 = random.choice(operands1)
operand2 = random.choice(operands2)
operator = random.choice(operators)
def inputNumber(message):
while True:
try:
userInput = int(input(message))
except ValueError:
print("Not an integer! Try again.")
continue
else:
return userInput
break
user_answer =int(input('{} {} {} = '.format(operand1, operator, operand2)))
I doubt you want to have your function definitions within a while loop like you're doing here:
while question < 10:
...
def inputNumber(message):
...
Instead, you can define the function outside the loop and call it x number of times from a loop elsewhere. E.g.
def inputNumber(message):
...
return userInput
while question < 10:
# pick random numbers/operators
...
# call inputNumber() with numbers/operators as message. Return user_answer
user_answer = int(inputNumber('{} {} {} = '.format(operand1, operator, operand2)))
# check if the answer is correct
...
# increment question so it doesn't run infinitely
question += 1
#user6104134 has already solved this problem; however, I'd like to provide an answer for anyone else having similar issues.
Try this solution
import random
import time
question = 0
score = 0
def inputnumber(prompt):
while True:
response = raw_input(prompt)
try:
if isinstance(response, int):
return int(response)
else:
print "Not an integer! Try again."
except ValueError:
print "Not an integer! Try again."
name = raw_input("What is your full name? ")
print ("Hello " + name, "welcome to The Arithmetic Quiz. Use integers to enter the answer!")
time.sleep(2)
operands1 = list(range(2, 12))
operators = ["+", "-", "x"]
operands2 = list(range(2, 12))
while question < 10:
operand1 = random.choice(operands1)
operand2 = random.choice(operands2)
operator = random.choice(operators)
user_answer = int(inputnumber('{} {} {} = '.format(operand1, operator, operand2)))
question += 1
Issues
First, you should declare function definitions outside of your script and call the function by identifier 'inputNumber()'
Also notice the slight change in Try/Except, and the PEP 8 Style Guide compliant formatting.