Python, Explain def function and scoring system? [closed] - python

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
Can someone explain this piece of code to allow me to understand def functions better, i need to know how the code below acts as a counter and adds up the score at the end of the test,:
for i in range(questions): #ask 10 questions
if quiz():
score +=1
this code was for a test I created, if it can be explained thanks alot, also can someone maybe give an alternative version of this piece of code, the whole code is below :
import random
import math
import operator as op
name = input("What is your name? ")
print("Hi {}! Welcome to the Arithmetic quiz...".format(name))
score = 0
questions = 10
def quiz():
x = random.randint(1, 10)
y = random.randint(1, 10)
ops = {'+': op.add,'-': op.sub,'*': op.mul}
keys = list(ops.keys())
opt = random.choice(keys)
operation = ops[opt]
answer = operation(x, y)
print ("What is {} {} {}?".format(x, opt, y)) #prints the question
user_answer= int(input("Your answer: ")) #prompts users answer
if user_answer != answer: #validate users answer to correct answer
print ("Incorrect. The right answer is",answer"")
return False
else:
print("Correct!")
return True
for i in range(questions): #ask 10 questions
if quiz():
score +=1 #counter
print("{}: You got {}/{} questions correct.".format(name, score, questions,))#'question' if (score==1) else 'questions'
thanks <3

i need to know how the code at the top of the page allows a counter to add up all the correct answers in the quiz
Formatting matters in Python, so take care:
for i in range(questions): #ask 10 questions
if quiz():
score +=1
quiz() gets called 10 times, and returns True if a question was answered correctly. In this case, the variable score will be incremented.

The quiz function asks a single question, takes the user's input, checks it and prints a message accordingly. It is defined in the block of code following def quiz(): and it is called (run) with quiz(). It also returns the value True if the answer was correct or False if it was incorrect.
So, every time it is called, its return value is checked and if it's True (if quiz(): is equivalent to if quiz() == True:), the counter score is incremented.
In fact, you can add True (which actually equals 1) and False (==0) to an integer, so your code (note the indenting):
for i in range(questions): #ask 10 questions
if quiz():
score +=1
could be written:
for i in range(questions): #ask 10 questions
score += quiz()

Related

Even though I am writing different code same problem is shown !! in python [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 months ago.
Improve this question
File "", line 1, in
ValueError: source code string cannot contain null bytes
Remainder of file ignored
def guess(x):
random_number = random.randint(1, x)
guess= 0
while guess = input (f'Guess a number beween 1 and %x')
guess(10)```
I am running this code in PyCHarm community edition !!
Please Help !
I am not to find this solution eventhough I tried multiple Sources
! !
if you want to computer guess a number, you can use:
import random
random.randint(1, 10)
or, if you want to get a guess from user:
x = 10
input(f'Guess a number between 1 and {x}')
and if you want to computer always guess a number untill it can find user input:
import random
def guess(x):
number = int(input(f'Guess a number between 1 and {x}'))
while True:
num = random.randint(1, x)
print(num)
if num == number:
break
guess(10)
or, human guess what computer selected:
import random
def guess(x):
number = random.randint(0,x)
while True:
user_num = int(input(f"Guess a number between 0 and {x}:"))
if user_num == number:
print("You guessed it!")
break
guess(10)

Python Simple Quiz Program - How to solve the question loop

learner in the Python (with version 2.7.5).
Currently I am working on a simple quiz script that allows the user to re-answer a question, and limit the number of chances the user can answer a question incorrectly.
So a total limit of 5 is set and a message (e.g. "END!") would be displayed to the user when the limit is reached. The limit is shared across all questions.
When I was testing the below-mentioned script, I found several problems.
1) Even the question 1 is wrongly answered for 5 times, question 2 would still be displayed, how could I prevent the next question from appearing if the limit was already reached?
2) I would like to ask where should I insert the code for the end message ("END!") if the limit was reached?
Thanks a lot!
def quiz():
score = 0
counter = 0
print "Please answer the following questions:"
print "Question 1 - ?"
print "a."
print "b."
print "c."
while counter <5:
answer = raw_input("Make your choice:")
if answer == "c":
print("Correct!")
score = score +1
else:
print("Incorrect!")
counter = counter +1
print "Question 2 - ?"
print "a."
print "b."
print "c."
while counter <5:
answer2 = raw_input("Make your choice:")
if answer2 == "a":
print("Correct!")
score = score +1
else:
print("Incorrect!")
counter = counter +1
print
print ("Your score is ") + str(score)
p.s. the code seems a bit off-placed with the copy and paste function. Sorry for causing the inconvenience
You should really refactor this to make it a little less repetitious. So I'd put the question and answer logic into their own function and pass in the question text and correct answer. However, using your code as-is, every time you increment the counter, you need to check if it's > 5 and just use while True for the loop. So for each question:
correct = "a"
while True:
answer = raw_input("Make your choice:")
if answer == correct:
print("Correct!")
score = score +1
break
else:
print("Incorrect!")
counter = counter +1
if counter == 5:
print "END!"
return
break
You are always printing the second question without checking if the limit of wrong answers has been reached. Before printing the second question you could do something like
if counter >= 5:
print "END!"
return
The return statement inside the conditional would terminate the quiz function if the limit has been reached. This needs to be done before printing any question.
Also, you could improve your code using a list of questions with answers and a simple for loop to iterate over all the questions and avoid repeating the same logic every time.

How to make every 'beginner' shown at random during the run of the program [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
Im currently in make of creating a math game that involves: addition, subtraction, multiplication and division. These parts with purple borders around them are the questions that i had created for the addition part when the user chooses to pick addition.
I dont know how to make these question be shown at random. When the user goes to select addition for addition questions everytime he does or goes back to do it again after he is done i want the questions not to be the same each time i want them to be in a different order. So its random each time.
#addition questions
def beginnerquestionsaddition():
os.system('clear')
score = 0
beginner1 = input("2 + 3 = ")
if beginner1 == ("5"):
print("Correct, Well Done!")
score += 1
time.sleep(1)
else:
print("Sorry you got it wrong :(")
time.sleep(1)
os.system('clear')
beginner2 = input("6 + 7 = ")
if beginner2 == ("13"):
print("Correct, Well Done!")
score += 1
time.sleep(1)
else:
print("Sorry you got it wrong :(")
time.sleep(1)
os.system('clear')
beginner3 = input("2 + 5 = ")
if beginner3 == ("7"):
print("Correct, Well Done!")
score += 1
os.system('clear')
time.sleep(1)
endquestadditionbeginner()
print("your score was: ")
print(score)
time.sleep(3)
introduction()
else:
print("Sorry you got it wrong :(")
time.sleep(1)
os.system('clear')
endquestadditionbeginner()
print("your score was: ")
print(score)
time.sleep(3)
introduction()
So this isn't exactly an answer for the specific way you decided to go about this program but this is a much simpler way:
from random import randrange
def beginner_addition():
A = randrange(1,11) # Increase range on harder questions
B = randrange(1,11) # Ex. for intermediate_addition(), randrange would be (10,21) maybe...
C = A + B
ans = input("What's the answer to " + str(A) + "+" + str(B) + "? ")
if ans == str(C):
print('Correct')
else:
print('Incorrect')
while True:
beginner_addition()
Of course, this is just example code. You could easily include your points system and perhaps move up in difficulty when the points hit a certain level. You could also randomize the operation. Sorry if this isn't what you want but I saw your code and I figured there is nothing wrong with simplifying your code...

Displaying the number of questions the user inputs

Currently in the process of making a True or False quiz. Would anyone be kind enough to help me out with the code? As I am unable to display the amount of questions the user wants to answer. The questions are all arranged in an array however, I am having trouble with it.
For example:
-There are 20 questions and the quiz asks the user for how many questions they want to answer
-User enters 5 questions
-Quiz displays 5 random questions out of the 20 in the list
Thank you in advance!
questionlist = [" "]
answerslist=[" "]
score = 0
questions = 0
while True :
questions = int(input("How many questions do you want to answer today? "))
if questions <= len(questionslist) :
break
print("I only have ", len(questions_list), " in my database")
while len(questionslist) > 0 :
I need help after this please
Using python 2.7:
import random
questions_answers = {"Question1?":"answer1","Question2?":"answer2","Question3?":"answer3","Question4?":"answer4","Question5?":"answer5"}
score = 0
while True :
questions = int(raw_input("How many questions do you want to answer today? "))
if questions == 0:
break
if questions > len(questions_answers) :
print("I only have {} in my database".format(len(questions_answers)))
break
for i in range(1, questions+1):
rand_item = random.choice(questions_answers.keys())
print(rand_item)
answer = raw_input("Enter your answer:")
if answer == questions_answers[rand_item]:
print("Correct")
score+=1
else:
print("Wrong")
print ("Your score is {} out of {}".format(score, questions))
Break this problem into steps, then focus on the code for each separate part.
I would retrieve the user input for how many questions he/she desires and create a loop which retrieves questions from this hash map at random for the requested number of questions! In order to retrieve the questions at random you should use a random generator that will return a number between 0 and 1. You should then multiply this number by the length of the quiz and cast this number to an integer. This will then be the index to your array. You must then store the question number in another array and check to see if this question was already asked the next time a random question was picked.
In psuedo code form:
number_of_questions = retrieve_user_input()
questions_asked_thus_far = [] //empty array
question_number = 1
while (question_number<=number_of_questions):
question_number = int(random_number_generator * quiz_array.length)
if question_number is not in questions_asked_thus_ far
questions_asked_thus_far.append(question_number)
question_number ++
print question_number

how come my math code always says that my answer is incorrect? [duplicate]

This question already has an answer here:
why does my math quiz always print incorrect when the answer is correct [closed]
(1 answer)
Closed 7 years ago.
i have just started programming and i am learning on how to make a math code that will tell the user if the answer is correct or not but the problem i am encountering is that even if i put the correct answer it prints my answer is incorrect and i have been trying to tackle the problem for several hours and cant find a solution.
this is my code in python:
print ("what is your username")
name = input () .title()
print (name, "welcome")
import random
score=0
question=0
for i in range(10):
ops = ["+", "-", "*"]
num1 = random.randint (0,10)
num2 = random.randint (0,10)
oparator = random.choice(ops)
Q=(str(num1)+(oparator)+(str(num2)))
print (Q)
guess = int(input())
if oparator =='+':
answer = (int(num1-num2))
elif oparator =='-':
answer = (int(num1-num2))
else:
oparator =='*'
answer = (int
(num1*num2))
if guess == Q:
print ("correct")
score + 1
else:
print ("incorrect")
im am really puzzled honestly, and help would be greatly appreciated
regards, kurt
You are comparing your guess (which is int) to the question Q (which is a str)
if guess == Q:
You want to compare
if guess == answer:
Also when you select '+' you have a mistake
if oparator =='+':
answer = (int(num1-num2))
You want to do addition
if oparator =='+':
answer = (int(num1+num2))
You also have indentation problems, among a variety of other issues.

Categories

Resources