Loop in a loop python [closed] - python

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
is there a way to add a second loop to a code. So the question says to create a quiz which I've done however, for the last hour I've being trying to add a second loop so the quiz does it three times:
import random
score = 0
questions = 0
loop = 0
classnumber = ("1", "2", "3")
name = input("Enter Your Username: ")
print("Hello, " + name + ". Welcome to the Arithmetic Quiz")
classno = input("What class are you in?")
while classno not in classnumber:
print(
"Enter a valid class. The classes you could be in are 1, 2 or 3.")
classno = input("What class are you in?")
while questions < 10:
for i in range(10):
number1 = random.randint(1, 10)
number2 = random.randint(1, 10)
op = random.choice("*-+")
multiply = number1*number2
subtract = number1-number2
addition = number1+number2
if op == "-":
print("Please enter your answer.")
questions += 1
print(" Question", questions, "/10")
uinput = input(str(number1)+" - "+str(number2)+"=")
if uinput == str(subtract):
score += 1
print("Correct, your score is: ", score,)
else:
print("Incorrect, the answer is: " + str(subtract))
score += 0
if op == "+":
print("Please enter your answer.")
questions += 1
print(" Question", questions, "/10")
uinput = input(str(number1)+" + "+str(number2)+"=")
if uinput == str(addition):
score += 1
print(" Correct, your score is: ", score,)
else:
print(" Incorrect, the answer is: " + str(addition))
score += 0
if op == "*":
print("Please enter your answer.")
questions += 1
print(" Question", questions, "/10")
uinput = input(str(number1)+" * "+str(number2)+"=")
if uinput == str(multiply):
score += 1
print(" Correct, your score is: ", score,)
else:
print(" Incorrect, the answer is: " + str(multiply))
score += 0

First, please consider using functions in your code. Functions make everything neater and functions help make code reusable.
Second, there are a lot of areas where the code is superfluous. It is performing unnecessary checks in spots and several sections of the code could be rearranged to reduce the overall length and increase readability.
Nonetheless, here's a revised version of your code with some of those suggestions implemented:
import random
def RunQuiz():
name = input("Enter Your Username: ")
print("Hello, " + name + ". Welcome to the Arithmetic Quiz")
score = 0
questions = 0
loop = 0
classnumber = ("1", "2", "3")
classno = input("What class are you in?")
while classno not in classnumber:
print("Enter a valid class. The classes you could be in are 1, 2 or 3.")
classno = input("What class are you in?\n>>> ")
# End while input
# Run the 10 question quiz
for questions in range(1,11):
number1 = random.randint(1, 10)
number2 = random.randint(1, 10)
op = random.choice("*-+")
multiply = number1*number2
subtract = number1-number2
addition = number1+number2
print("Please enter your answer.")
print(" Question" + str(questions) "/10")
if( op == "-"):
# Subtraction
uinput = input(str(number1)+" - "+str(number2)+"=")
# Make it an int for proper comparison
uinput = int(uinput)
if uinput == subtract:
score += 1
print("Correct, your score is: %d" %(score,))
else:
print("Incorrect, the answer is: " + str(subtract))
score += 0
elif( op == "+"):
# Addition
uinput = input(str(number1)+" + "+str(number2)+"=")
uinput = int(uinput)
if uinput == addition:
score += 1
print(" Correct, your score is: %d" % (score,))
else:
print(" Incorrect, the answer is: " + str(addition))
score += 0
elif( op == "*" ):
# Multiplication
uinput = input(str(number1)+" * "+str(number2)+"=")
uinput = int(uinput)
if uinput == multiply:
score += 1
print(" Correct, your score is: %d" % (score,))
else:
print(" Incorrect, the answer is: " + str(multiply))
score += 0
# End if( op )
# End For 10 questions
print("\nFinal Score: %d/10" % (score,))
# End RunQuiz()
def main():
# Run the quiz 10 times
for RunCount in range(3):
print("Running quiz #%d\n" % (RunCount,))
RunQuiz()
# End For
# End main
# Call main on script execution
main()
Obviously you can rearrange the code to suit your needs. (For example, I did not know if you want the name & class number to be entered every time).

If you want the whole thing to run 3 times then put for i in xrange(3): above the first lines of the quiz then indent the rest of the code to the loop. If that is what you actually want. Good luck!

Related

How to randomly select a variable in Python?

from random import*
from time import*
print("1. Addition \n2. Subtraction \n3. Multiplication \n4. Division")
count = int(input("How many question do you want? : "))
question = input("What kind of questions do you want? (Type 1/2/3/4) :")
mark = 0
if question == "1":
for x in range(count) :
a = randint(1,100)
b = randint(1,500)
question = input("What is the value of {} + {} : ".format(a,b))
if int(question) == (a + b):
print("You are correct")
mark = mark+1
else:
print("Your answer is wrong")
print("The correct answer is {}".format(a+b))
if question == "2":
for x in range(count) :
a = randint(1,100)
b = randint(1,500)
if b > a:
a,b = b,a
question = input("What is the value of {} - {} : ".format(a,b))
if int(question) == (a - b):
print("You are correct")
mark = mark + 1
elif int(question) != (a - b):
print("Your answer is wrong")
print("The correct answer is {}".format(a-b))
mark = mark + 0
elif question == "3":
for m in range(count) :
a = randint(1,100)
b = randint(1,500)
question = input("What is the value of {} ⨯ {} : ".format(a,b))
if int(question) == (a * b):
print("You are correct")
mark = mark + 1
elif int(question) != (a*b):
print("Your answer is wrong")
print("The correct answer is {}".format(a*b))
mark = mark + 0
elif question == "4":
for m in range(count) :
a = randint(1,100)
b = randint(1,500)
if b > a:
a,b = b,a
question = input("What is the value of {} ÷ {} in integer: ".format(a,b))
if int(question) == (a // b):
print("You are correct")
elif int(question) != (a//b):
print("Your answer is wrong")
print("The correct answer is {}".format(a//b))
sleep(2)
print("\nYour final mark is {}".format(mark))
How to randomly select one of the four operations and change it for every question? It is not necessary to change it but I don't want to display the same type of operation every time.
To clear something, question = input("What kind of questions do you want? (Type 1/2/3/4) :")
I write the line just to test if my code is working or not.
You can use random.randint.
import random
question = random.randint(1, 4) # Returns an integer value between 1 and 4
if question == 1:
# Do Something
elif question == 2:
# Do Something, etc.
You can use the random library and pass a list. It will output a random item from the list.
import random
random.choice([1,2,3,4])

Python 3: Returning variable through multiple functions

I have been given a basic python problem that requires me to make a simple addition quiz. However, I cannot seem to return my count variable which is supposed to update the number of correct questions the user has answered, which makes it stuck at 0. I have tried defining the variable count in every function containing it as an argument but still does not work. Say if the user were to answer 4 questions and got 3 correct, it would display it as "You have answered 4 questions with 3 correct", but instead it displays "You have answered 4 questions with 0 correct".
Every time your check_solution and menu_optionfunctions get called, you initialize count = 0. This means every time the user requests another question, count gets reset to 0, twice. You're going to want to remove those count = 0 calls, and you also want to capture your updates to count within menu_option. Your final program should look something like this:
import random
def get_user_input():
count = 0
user_input = int(input("Enter 1 to play or press 5 to exit: "))
while user_input > 5 or user_input <= 0:
user_input = int(input("Invalid menu option. Try again: "))
menu_option(user_input, count)
if user_input == "5":
print("Exit!")
return user_input
def get_user_solution(problem):
answer = int(input(problem))
return answer
def check_solution(user_solution, solution, count):
curr_count = count
if user_solution == solution:
curr_count += 1
print("Correct.")
else:
print("Incorrect.")
print(curr_count)
return curr_count
def menu_option(index, count):
if index == 1:
num1 = random.randrange(1, 21)
num2 = random.randrange(1, 21)
randsum = num1 + num2
problem = str(num1) + " " + "+" + " " + str(num2) + " " + "=" + " "
user_answer = get_user_solution(problem)
count = check_solution(user_answer, randsum, count) # count returned by check_solution is now being captured by count, which will update your count variable to the correct value
return count
def display_result(total, correct):
if total == 0:
print("You answered 0 questions with 0 correct.")
print("Your score is 0%. Thank you.")
else:
score = round((correct / total) * 100, 2)
print("You answered", total, "questions with", correct, "correct.")
print("Your score is", str(score) + "%.")
def main():
option = get_user_input()
total = 0
correct = 0
while option != 5:
total = total + 1
correct = menu_option(option, correct)
option = get_user_input()
print("Exiting.")
display_result(total, correct)
main()
You need catch the return from check_solution(user_answer, randsum, count) and return that count
As the comment stated, you are initializing count to 0 every time your check_solution or menu_option is called.
It looks like you want to use count = count the variable being passed to your function.
Just a quick edit:
You actually don't need to return count. In Python, variables are passed by reference so your count will get updated as long as it's being passed to your functions.
You have the option of initializing count to 0 before all functions, thus creating a global variable. Then you won't need to declare it on any function nor pass it as argument.
This is a culmination of several errors in logic.
You give count to functions as input and immediately overwrite it.
I would instead say def menu_option(index, count=0):. This will set count=0 if no variable is supplied (creating a default), otherwise it will set count as whatever you pass into the function
Your check_solution() function returns a number, but when you call it with check_solution(user_answer, randsum, count) you never assign this returned value to anything/use it again.
You can assign this to a variable (say output) and then return output instead of return count
Fixing these still doesn't fully solve the problem, but gets a little bit closer (now it gets stuck on "you answered x questions with 1 correct"):
import random
def get_user_input(count = 0):
user_input = int(input("Enter 1 to play or press 5 to exit: "))
while user_input > 5 or user_input <= 0:
user_input = int(input("Invalid menu option. Try again: "))
menu_option(user_input, count)
if user_input == "5":
print("Exit!")
return user_input
def get_user_solution(problem):
answer = int(input(problem))
return answer
def check_solution(user_solution, solution, count):
count = 0
if user_solution == solution:
count += 1
print("Correct.")
else:
print("Incorrect.")
return count
def menu_option(index, count=0):
if index == 1:
num1 = random.randrange(1, 21)
num2 = random.randrange(1, 21)
randsum = num1 + num2
problem = str(num1) + " " + "+" + " " + str(num2) + " " + "=" + " "
user_answer = get_user_solution(problem)
output = check_solution(user_answer, randsum, count)
return output
def display_result(total, correct):
if total == 0:
print("You answered 0 questions with 0 correct.")
print("Your score is 0%. Thank you.")
else:
score = round((correct / total) * 100, 2)
print("You answered", total, "questions with", correct, "correct.")
print("Your score is", str(score) + "%.")
def main():
option = get_user_input()
total = 0
correct = 0
while option != 5:
total += 1
correct = menu_option(option, correct)
option = get_user_input()
print("Exiting.")
display_result(total, correct)
main()
I think a more simplistic approach would look something like:
import random
def generate_question():
num1 = random.randint(1, 25)
num2 = random.randint(1, 25)
question = '{} + {} = '.format(num1, num2)
answer = num1 + num2
return question, answer
def main():
correct = 0
total = 0
option = True
while option != '5':
total += 1
question, answer = generate_question()
user_guess = int(input(question))
if user_guess == answer:
print('Correct.')
correct += 1
else:
print('Incorrect.')
option = input("Enter 5 to exit, or anything else to play again")
print('You answered {} questions with {} correct'.format(total, correct))
main()

Python - Returning variable from function trouble

I'm currently learning Python and am creating a maths quiz.
I have created a function that loops, first creating a random maths sum, asks for the answer and then compares the input to the actual answer; if a question is wrong the player loses a point - vice versa. At the end a score is calculated, this is what I'm trying to return at the end of the function and print in the main.py file where I receive a NameError 'score' is not defined.
I have racked my head on trying to figure this out. Any help / suggestions would be greatly appreciated!
#generateQuestion.py
`def generate(lives, maxNum):
import random
score= 0
questionNumber = 1
while questionNumber <=10:
try:
ops = ['+', '-', '*', '/']
num1 = random.randint(0,(maxNum))
num2 = random.randint(0,10)
operation = random.choice(ops)
question = (str(num1) + operation + str(num2))
print ('Question', questionNumber)
print (question)
maths = eval(str(num1) + operation + str(num2))
answer=float(input("What is the answer? "))
except ValueError:
print ('Please enter a number.')
continue
if answer == maths:
print ('Correct')
score = score + 1
questionNumber = questionNumber + 1
print ('Score:', score)
print ('Lives:', lives)
print('\n')
continue
elif lives == 1:
print ('You died!')
print('\n')
break
else:
print ('Wrong answer. The answer was actually', maths)
lives = lives - 1
questionNumber = questionNumber + 1
print ('Score:', score)
print ('Lives:', lives)
print('\n')
continue
if questionNumber == 0:
print ('All done!')
return score
`
My main file
#main.py
import random
from generateQuestion import generate
#Welcome message and name input.
print ('Welcome, yes! This is maths!')
name = input("What is your name: ")
print("Hello there",name,"!" )
print('\n')
#difficulty prompt
while True:
#if input is not 1, 2 or 3, re-prompts.
try:
difficulty = int (input(' Enter difficulty (1. Easy, 2. Medium, 3. Hard): '))
except ValueError:
print ('Please enter a number between 1 to 3.')
continue
if difficulty < 4:
break
else:
print ('Between 1-3 please.')
#if correct number is inputted (1, 2 or 3).
if difficulty == 1:
print ('You chose Easy')
lives = int(3)
maxNum = int(10)
if difficulty == 2:
print ('You chose Medium')
lives = int(2)
maxNum = int(25)
if difficulty == 3:
print ('You chose Hard')
lives = int(1)
maxNum = int(50)
print ('You have a life count of', lives)
print('\n')
#generateQuestion
print ('Please answer: ')
generate(lives, maxNum)
print (score)
#not printing^^
'
I have tried a different method just using the function files (without the main) and have narrowed it down to the problem being the returning of the score variable, this code is:
def generate(lives, maxNum):
import random
questionNumber = 1
score= 0
lives= 0
maxNum= 10
#evalualates question to find answer (maths = answer)
while questionNumber <=10:
try:
ops = ['+', '-', '*', '/']
num1 = random.randint(0,(maxNum))
num2 = random.randint(0,10)
operation = random.choice(ops)
question = (str(num1) + operation + str(num2))
print ('Question', questionNumber)
print (question)
maths = eval(str(num1) + operation + str(num2))
answer=float(input("What is the answer? "))
except ValueError:
print ('Please enter a number.')
continue
if answer == maths:
print ('Correct')
score = score + 1
questionNumber = questionNumber + 1
print ('Score:', score)
print ('Lives:', lives)
print('\n')
continue
elif lives == 1:
print ('You died!')
print('\n')
break
else:
print ('Wrong answer. The answer was actually', maths)
lives = lives - 1
questionNumber = questionNumber + 1
print ('Score:', score)
print ('Lives:', lives)
print('\n')
continue
if questionNumber == 0:
return score
def scoreCount():
generate(score)
print (score)
scoreCount()
I think the problem is with these last lines in main:
print ('Please answer: ')
generate(lives, maxNum)
print ('score')
You are not receiving the returned value. It should be changed to:
print ('Please answer: ')
score = generate(lives, maxNum) #not generate(lives, maxNum)
print (score) # not print('score')
This will work.
The way it works is not:
def a():
score = 3
return score
def b():
a()
print(score)
(And print('score') will simply print the word 'score'.)
It works like this:
def a():
score = 3
return score
def b():
print(a())

how do i make my python code work? random math quiz

This is my code it has to have + - * in the code and it has to be chosen randomly but it does not work it does not say the correct answer I would appreciate any help thanks.
import random
import operator
question_number = 0
score = 0
ops = {'+':operator.add,
'-':operator.sub,
'*':operator.mul,
'/':operator.truediv}
number1 = random.randint(0,12)
number2 = random.randint(1,10)
op = random.choice(list(ops.keys()))
print ("this is a short maths quiz")
name = input ("what is your name")
age = input ("how old are you " +name)
print ("ok "+name+" im going to start the quiz now")
print(number1, op, number2)
user_input=int(input())
answer = (number1,op,number2)
if user_input == answer:
print("Well done")
score = score + 1
else:
print("WRONG!")
print("The answer was",answer)
question_number = question_number + 1
You need to op as a key to get the appropriate value from the ops dict and call it on the two numbers:
answer = ops[op](number1, number2)
Your code is comparing an int to a tuple i.e 9 == (3, '+', 6)
You may also want to keep the larger number on the left and smaller on the right unless you want negative numbers.
answer = ops[op](max(number1,number2),min(number1, number2))
Also unless this is in a while loop question_number = question_number + 1 is not going to do much.
you need to make the op an op and not a string.
this is your code fixed.
import random
import operator
question_number = 0
score = 0
ops = {'+':operator.add,
'-':operator.sub,
'*':operator.mul,
'/':operator.truediv}
number1 = random.randint(0,12)
number2 = random.randint(1,10)
op = random.choice(list(ops.keys()))
print ("this is a short maths quiz")
name = input ("what is your name")
age = input ("how old are you " +name)
print ("ok "+name+" im going to start the quiz now")
print(number1, op, number2)
user_input=int(input())
if op == "+":
answer = (number1+number2)
elif op == "-":
answer = (number1-number2)
elif op == "*":
answer = (number1*number2)
elif op == "/":
answer = (number1/number2)
if user_input == answer:
print("Well done")
score = score + 1
else:
print("WRONG!")
print("The answer was",answer)
question_number = question_number + 1
you could add a while loop to make it repeating

python - ask random mathematical questions not quite working

I need help with this program that I'm writing. It asks random mathematical questions. It chooses between +, - and x. Here's my code
import random
def questions():
name=input("What is your name: ")
print("Hello there",name,"!")
choice = random.choice("+-x")
finish = False
questionnumber = 0
correctquestions = 0
while finish == False:
if questionnumber < 10 | questionnumber >= 0:
number1 = random.randrange(1,10)
number2 = random.randrange(1,10)
print((number1),(choice),(number2))
answer=int(input("What is the answer?"))
questionnumber = questionnumber + 1
if choice==("+"):
realanswer = number1+number2
if answer==realanswer:
print("That's the correct answer")
correctquestions = correctquestions + 1
else:
print("Wrong answer, the answer was",realanswer,"!")
if choice==("x"):
realanswer = number1*number2
if answer==realanswer:
print("That's the correct answer")
correctquestions = correctquestions + 1
else:
print("Wrong answer, the answer was",realanswer,"!")
elif choice==("-"):
realanswer = number1-number2
if answer==realanswer:
print("That's the correct answer")
correctquestions = correctquestions + 1
else:
print("Wrong answer, the answer was",realanswer,"!")
else:
finish = True
else:
print("Good job",name,"! You have finished the quiz")
print("You scored " + str(correctquestions) + "/10 questions.")
questions()
The output:
What is your name: s
Hello there s !
6 - 9
What is the answer?-3
That's the correct answer
9 - 8
What is the answer?1
That's the correct answer
9 - 7
What is the answer?2
That's the correct answer
8 - 3
What is the answer?4
Wrong answer, the answer was 5 !
5 - 6
What is the answer?1
Wrong answer, the answer was -1 !
8 - 7
What is the answer?1
That's the correct answer
3 - 5
What is the answer?2
Wrong answer, the answer was -2 !
4 - 5
What is the answer?1
Wrong answer, the answer was -1 !
7 - 2
What is the answer?5
That's the correct answer
7 - 1
What is the answer?6
That's the correct answer
Good job s ! You have finished the quiz
You scored 6/10 questions.
Now the program is running fine but it asks the questions with the same operator (+, -, x) every time I start the program a different operator questions happen but I want to run it so it actually asks different adding, subtracting, multiplication questions inside the program so all the questions that it asks it will be different questions like x, + and - every different question.
It should help if you move the choice part inside the loop:
while not finish: # better than finish == False
choice = random.choice("+-x")
# etc
import random
correct = 0
name = input("Please enter your name: ")
for count in range(10):
num1 = ranom.randint(1, 100)
num2 = radom.randint(1, 100)
symbol = rndom.choice(["+", "-", "*"])
print("Please solve:\n", num1, symbol, num2)
user = int(input(""))
if symbol == "+":
answer = num1 + num2
elif symbol == "-":
answer = num1 - num2
elif symbol == "*":
answer = num1 * num2
if user == answer:
print("Wong u wetard")
correct = correct + 1
else:
print("correct")
print(name, ", You Got", correct, "Out Of 10")
After while finish == false put this !
choice = random.choice("+-x")
I have attempted the same problem that you face, and after looking at your code I made the changes detailed below. the code works and it is (relatively) neat and concise.
def name_enter():
global name
name = ""
while name == "" or len(name) > 25 or not re.match(r'^[A-Za-z0-9-]*$', name):
name = input("Please enter your name: ")
enter_class()
def enter_class():
global class_choice
class_choice = None
while class_choice not in ["1","3","2"]:
class_choice = input("Please enter you class (1, 2, 3): ")
print("\nClass entered was " + class_choice)
mathsquestion()
def mathsquestion():
global qa, score
qa, score = 0, 0
for qa in range(0,10):
qa = qa + 1
print("The question you are currently on is: ", qa)
n1, n2, userans = random.randrange(12), random.randrange(12), ""
opu = random.choice(["-","+","x"])
if opu == "+":
while userans == "" or not re.match(r'^[0-9,-]*$', userans):
userans = input("Please solve this: %d" % (n1) + " + %d" % (n2) + " = ")
prod = n1 + n2
elif opu == "-":
while userans == "" or not re.match(r'^[0-9,-]*$', userans):
userans = input("Please solve this: %d" % (n1) + " - %d" % (n2) + " = ")
prod = n1 - n2
else:
while userans == "" or not re.match(r'^[0-9,-]*$', userans):
userans = input("Please solve this: %d" % (n1) + " x %d" % (n2) + " = ")
prod = n1 * n2
userans = int(userans)
prod = int(prod)
if prod == userans:
score = score + 1
print("Well done, you have got the question correct. Your score is now: %d" % (score))
else:
print("Unfortunatly that is incorrect. The answer you entered was %d" % (userans) + " and the answer is actually %d" % (prod))
print("Your final score is: %d" % (score))
name_enter()
This is a very different code but should do the same thing. It's also much shorter and neater.
import random
correct = 0
name = input("Please enter your name: ")
for count in range(10):
num1 = random.randint(1, 100)
num2 = random.randint(1, 100)
symbol = random.choice(["+", "-", "*"])
print("Please solve:\n", num1, symbol, num2)
user = int(input(""))
if symbol == "+":
answer = num1 + num2
elif symbol == "-":
answer = num1 - num2
elif symbol == "*":
answer = num1 * num2
if user == answer:
print("Correct!")
correct = correct + 1
else:
print("Incorrect")
print(name, ", You Got", correct, "Out Of 10")

Categories

Resources