Nest IF needed? in Python - python

This is my first Python program where I've used if, while and functions. I've also passed parameters. The problem is the IF. Can you help me? I wanted the program to give the user two tries to answer and then end. If correct then it ends but if not correct it doesn't stop, keeps looping.
"""this is a quiz on computer science"""
q1Answer="c"
def questionOne():
print("Here is a quiz to test your knowledge of computer science...")
print()
print("Question 1")
print("What type of algorithm is insertion?")
print()
print("a....searching algorithm")
print("b....decomposition ")
print("c....sorting algorithm ")
print()
def checkAnswer1(q1Answer): #q1Answer is a global variable and is needed for this function so it goes here as a parameter
attempt=0 #These are local variables
score=0
answer = input("Make your choice >>>> ")
while attempt <1:
if answer==q1Answer:
attempt= attempt+1
print("Correct!")
score =score + 2
break
elif answer != q1Answer:
answer =input("Incorrect response – 1 attempt remaining, please try again: ")
if answer ==q1Answer:
attempt = attempt + 1
print("Correct! On the second attempt")
score =score + 1
break
else:
print("That is not correct\nThe answer is "+q1Answer )
score =0
return score # This is returned so that it can be used in other parts of the program
##def questionTwo():
## print("Question 2\nWhat is abstraction\n\na....looking for problems\nb....removing irrelevant data\nc....solving the problem\n")
def main():
q1answer = questionOne()
score = checkAnswer1(q1Answer)
print ("Your final score is ", score)
main()

The problem is you aren't incrementing the attempt if they get it wrong the second time. You need another attempt = attempt + 1 (Or alternatively attempt += 1) after the break
So your elif block would look like:
elif answer != q1Answer:
answer =input("Incorrect response – 1 attempt remaining, please try again: ")
if answer ==q1Answer:
attempt = attempt + 1
print("Correct! On the second attempt")
score =score + 1
break
attempt = attempt + 1
This allows the attempt counter to increment even if they fail the second time, tiggering the fail and end of loop.

You just add attempt +=1 after the loops.
q1Answer="c"
def questionOne():
print("Here is a quiz to test your knowledge of computer science...")
print()
print("Question 1")
print("What type of algorithm is insertion?")
print()
print("a....searching algorithm")
print("b....decomposition ")
print("c....sorting algorithm ")
print()
def checkAnswer1(q1Answer): #q1Answer is a global variable and is needed for this function so it goes here as a parameter
attempt=0 #These are local variables
score=0
answer = input("Make your choice >>>> ")
while attempt <1:
if answer==q1Answer:
attempt= attempt+1
print("Correct!")
score =score + 2
break
elif answer != q1Answer:
answer =input("Incorrect response – 1 attempt remaining, please try again: ")
if answer ==q1Answer:
attempt = attempt + 1
print("Correct! On the second attempt")
score =score + 1
break
else:
print("That is not correct\nThe answer is "+q1Answer )
score =0
attempt += 1
break
return score # This is returned so that it can be used in other parts of the program
##def questionTwo():
## print("Question 2\nWhat is abstraction\n\na....looking for problems\nb....removing irrelevant data\nc....solving the problem\n")
def main():
q1answer = questionOne()
score = checkAnswer1(q1Answer)
print ("Your final score is ", score)
main()

Related

What is the best way to make a guessing loop in python?

Basically I'm trying to make a guessing game. There are 3 questions and you have 3 guesses for every question. The problem is I'm bad at coding, this is only my first time.
print("Guessing Game")
player_name = input("Hi! What's your name? ")
number_of_guesses1 = 0
number_of_guesses2 = 0
number_of_guesses3 = 0
guess1 = input("What is the most popular car company in America? ")
while number_of_guesses1 < 3:
number_of_guesses1 += 1
if guess1 == ("Ford"):
break
if guess1 == ("Ford"):
print('You guessed the answer in ' + str(number_of_guesses1) + ' tries!')
else:
guess2 = input("Try again:")
if guess2 == ("Ford"):
print('You guessed the answer in ' + str(number_of_guesses1) + ' tries!')
else:
guess3 = input("Try again:")
if guess3 == ("Ford"):
print('You guessed the answer in ' + str(number_of_guesses1) + ' tries!')
else:
print('You did not guess the answer, The answer was Ford')
guess1b = input("What color do you get when you mix red and brown?")
while number_of_guesses2 < 3:
number_of_guesses2 += 1
if guess1 == ("Maroon"):
break
if guess1b == ("Maroon"):
print('You guessed the answer in ' + str(number_of_guesses1) + ' tries!')
else:
guess2b = input("Try again:")
if guess2b == ("Maroon"):
print('You guessed the answer in ' + str(number_of_guesses1) + ' tries!')
else:
guess3b = input("Try again:")
if guess3b == ("Maroon"):
print('You guessed the answer in ' + str(number_of_guesses1) + ' tries!')
else:
print('You did not guess the answer, The answer was Maroon')
This code kind of works, but only if you get the answer wrong 2 times in a row for every question lol. I also haven't thought of a way to implement a score keeper yet (at the end I want it to say how many points you got out of 3.) The code also is obviously not done. Basically, my questions are: How come when I get the answer wrong once and then get it right on the second try it says that it took 3 tries? And if you get the answer right on the first or second try how can I make it so it ignores the remaining tries you have left? This is the error code for example if I get it right on the second try:
Traceback (most recent call last):
File "main.py", line 20, in <module>
if guess3 == ("Ford"):
NameError: name 'guess3' is not defined
By utilizing the data structures within Python and a couple of functions, you can simplify your code considerably as shown below:
from collections import namedtuple
# Create a tuyple containing the Question, number of allowed tries and the answer
Question = namedtuple("Question", ["quest", 'maxTries', 'ans'])
def askQuestion(quest: str, mxTry: int, ans: str) -> int:
""" Ask the question, process answer, keep track of tries, return score"""
score = mxTry
while score > 0:
resp = input(quest)
if resp.lower() == ans:
print('Yes, you got it')
break
else:
score -= 1
print(f'Sorry {resp} is incorrect, try again')
if score == 0:
print("Too Bad, you didn't get the correct answer.")
print(f"The correct answer is {ans}")
return score
def playGame():
# Create a list of questions defiend using the Question structure defined above
question_list =[Question('What is the most popular car company in America? ' , 3, 'ford'),
Question("What color do you get when you mix red and brown?", 3, 'maroon')]
plyr_score = 0
for q in question_list:
plyr_score += askQuestion(q.quest, q.maxTries, q.ans)
print(f'Your final score is {plyr_score}')
The above approach allows you to extend the question repertoire as well as provide a different number of max tries by question.
simply execute playGame() to run the game
Don't use a different variable to keep track of each guess, instead just use one variable, and continually update it using input(). Then you can check it over and over again, without writing a whole mess of if-else statements. For keeping track of the number correct, you can use a variable, and increment it every time a correct answer is entered.
print("Guessing Game")
player_name = input("Hi! What's your name? ")
score = 0
answer1 = "Ford"
answer2 = "Maroon"
guess = input("What is the most popular car company in America? ")
number_of_guesses = 1
while guess != answer1 and number_of_guesses < 3:
guess = input("Try again: ")
number_of_guesses += 1
if guess == answer1:
print('You guessed the answer in ' + str(number_of_guesses) + ' tries!')
score += 1
else:
print('You did not guess the answer, The answer was Ford')
guess = input("What color do you get when you mix red and brown? ")
number_of_guesses = 1
while guess != answer2 and number_of_guesses < 3:
guess = input("Try again: ")
number_of_guesses += 1
if guess == answer2:
print('You guessed the answer in ' + str(number_of_guesses) + ' tries!')
score += 1
else:
print('You did not guess the answer, The answer was Maroon')
print('You got ' + str(score) + ' out of 2 questions.')

How can I avoid the output "0 tries left"?

My program asks the user to input how many tries/attempts they would like for answering each question. When the user runs out of tries, my program prints "0 tries left." How can I prevent this so that my program only prints "You are out of tries"?
Here is the specific function of my code:
def test_student(max_attempts, prob_spec, prob_sol):
counter = 0
print("The problem is:", prob_spec)
while counter < max_attempts:
user_answer = int(input("\t Your answer:"))
if user_answer != int(prob_sol):
counter = counter + 1
print("Try again. You have", (max_attempts - counter), "tries left.")
elif user_answer == int(prob_sol):
print("Correct!")
return True
break
if counter == max_attempts:
print("You are out of tries. The answer was:", prob_sol)
return False
Change this:
print("Try again. You have", (max_attempts - counter), "tries left.")
to this:
if max_attempts - counter != 0:
print("Try again. You have", (max_attempts - counter), "tries left.")
else:
break
Redesigned your code a little:
def test_student(max_attempts, prob_spec, prob_sol):
counter = 0
print("The problem is:", prob_spec)
while True:
user_answer = int(input("\t Your answer:"))
if user_answer == int(prob_sol):
print("Correct!")
return True
counter += 1
if counter == max_attempts:
print("You are out of tries. The answer was:", prob_sol)
return False
print("Try again. You have", (max_attempts - counter), "tries left.")
No need for break after a return.
No need to check equality and then immediately inequality, it's superfluous.
Try exiting a while loop as soon as possible if you're correct, it leads to more readable code.
As you can see, instead of checking the counter as the while condition, I check it later on. This allows you to take care of the last attempt differently.
Keep in mind you can use the max_attempts as a counter by running max_attempts -= 1 and comparing the result to 0. I chose to go with your way as it's completely reasonable.

can we create a quiz in python using only functions and also keep track of scores

I wanted to create a function which can keep track of the scores from each of the questions and then use it in another function which returns the final result to the user. I have no idea of how to do so.
# Function for question 1
def ask_question_one(difficulty):
score = 0
print("What is the capital city of Canada?")
answer = input()
if difficulty <= 3:
if answer == "Ottawa" or answer == "ottawa":
score = score + 10
print("Your score is:", score)
else:
print(score)
elif difficulty > 3 and difficulty <= 7:
if answer == "Ottawa" or answer == "ottawa":
score = score + 30
print ("your score is:", score)
else:
print("You have given an incorrect answer. You lose 5 points.")
score = score - 5
print("Your score is:", score)
else:
count = 1
while count < 3:
answer = input()
if answer != "Ottawa" or answer != "ottawa":
score = score - 5
print("Your score is:", score)
score = score + 50
print("Your score after two tries is:", score)
def display_result(difficulty, score):
if difficulty <= 3 and score > 30:
print("Your difficulty level is", str(difficulty) + " and your score is", str(score))
# Top-level code.
set_difficulty = int(input("Please enter a difficuty level between 1 and 10: "))
if set_difficulty == "":
print("You did not enter a difficulty level. Try again! Exiting quiz.")
exit()
elif set_difficulty == 0:
print("0(zero) is not a valid difficulty. Exiting quiz.")
exit()
elif set_difficulty > 10:
print("Select a difficulty level less than 10.")
exit()
else:
print("....Let's begin the quiz....")
ask_question_one(set_difficulty)
here is what i have done so far
Please explain the comment correctly. Then maybe I can answer (I am putting this here because I don't have enough reputation for posting comments :'( ).

Need quiz scoring function

I have to create a basic 3 question quiz on farming. It needs to ask the 3 questions, output whether you got it correct or incorrect and if you got it incorrect you can try again. It also needs to have a score function. I have completed the questions and the incorrect/correct part of the specification but no matter what I try I cannot get the score function to work. I have tried:
score = 0
def counter(score)
score = score + 1
def counter(score)
score = 0
score = score + 1
def counter(score)
global score
score = 0
score = score + 1
and then following that once the answer was correct the line read :
counter(score)
I have also tried
score = 0
then
score = score + 1
but nothing is working and I cannot figure out what is going wrong. It also needs to print how many the user got right at the end.
CODE:
score = 0
def quiz():
print("Here is a quiz to test your knowledge of farming...")
print()
print()
print("Question 1")
print("What percentage of the land is used for farming?")
print()
print("a. 25%")
print("b. 50%")
print("c. 75%")
answer = input("Make your choice: ")
if answer == "c":
print("Correct!")
score = score + 1
else:
print("Incorrect.")
answer = input("Try again! ")
if answer == "c":
print("Correct")
score = score + 1
else:
print("Incorrect! Sorry the answer was C.")
print()
print()
print("Question 2")
print("Roughly how much did farming contribute to the UK economy in 2014.")
print()
print("a. £8 Billion.")
print("b. £10 Billion.")
print("c. £12 Billion.")
answer = input("Make your choice: ")
if answer == "b":
print("Correct!")
score = score + 1
else:
print("Incorrect.")
answer = input("Try again! ")
if answer == "b":
print("Ccrrect!")
score = score + 1
else:
print("Incorrect! Sorry the answer was B.")
print()
print()
print("Question 3.")
print("This device, which was invented in 1882 has revolutionised farming. What is it called?")
print()
print("a. Tractor")
print("b. Wagon.")
print("c. Combine.")
answer == input("Make your choice. ")
if answer == "a":
print("Correct!")
score = score + 1
else:
print("Incorrect.")
answer == input("Try again! ")
if answer == "a":
print("Correct!")
score = score + 1
else:
print("Incorrect! Sorry the answer was A.")
print("You got {0}/3 right!".format(score))
A n00b (and working) way would be to do something like
score = 0
def quiz():
global score
The global keyword makes use of the global variable (which you declared outside your function quiz). Since you've not indented your code properly it's unclear if you're printing the last statement inside or outside the quiz function, but that doesn't matter. If you place both score and printing inside the quiz function or both outside you'll be fine. Good luck with homework!
So python scope is defined by indents (as mentioned by the comment above). So any statement that creates a layer of scope is seperated by an indent. Examples include classes, functions, loops, and boolean statements. Here is an example of this.
Class A:
def __init__(self, msg):
self.message = msg
def print_msg(self): # prints your message
print self.message
def is_hi(self):
if self.message == "hi":
return true
else:
return false
This shows the different layers of scope that can exist.
Your code is not working right now because you are defining a function and then putting nothing in its scope. You would have to put anything within the scope of the function for that error to go away but that is probably not what you are looking for.
Operators in any programming language are your bread and butter for transforming data from one state to another or for comparing data. We have three types: Arithmetic operators, Relational operators and Logical operators. It is crucial you understand them well and I would advise you to visit https://www.geeksforgeeks.org/basic-operators-python/ for reference. I can see from your answer above that there is some confusion between the assignment operator and the comparison operator:
This is the comparison operator:
answer == input("Make your choice. ")
What you expect to happen is that an input is read from the keyboard and set into the answer variable, but what's actually happening is your testing for a conditional comparison, in this case between an empty variable (called answer) and a python built-in function. What will happen is python will silently return a boolean describing the outcome of the conditional statement but will never set your variable to the new value because you didn't use the assignment operator.
This is the assignment operator:
answer = input("Make your choice. ")
A single equal symbol can make a big difference!
Now your code will correctly set the value a user types from their keyboard into the answer variable thanks to the power of the assignment operator.
I've refactored your code below to demonstrate the difference between assignment and comparison operations. I've also demonstrated using the newline character (\n) to create spaces between your text blocks.
import sys
def quiz():
score = 0
print("Here is a quiz to test your knowledge of farming...\n\n")
print("Question 1")
print("What percentage of the land is used for farming?")
print("a. 25%")
print("b. 50%")
print("c. 75%")
answer = input("Make your choice: ")
if answer == "c":
print("Correct!\n\n")
score = score + 1
else:
print("Incorrect! Sorry the answer was C.\n\n")
print("Question 2")
print("Roughly how much did farming contribute to the UK economy in 2014.\n")
print("a. £8 Billion.")
print("b. £10 Billion.")
print("c. £12 Billion.")
answer = input("Make your choice: ")
if answer == "b":
print("Correct!\n\n")
score = score + 1
else:
print("Incorrect! Sorry the answer was B.\n\n")
print("Question 3.")
print("This device, which was invented in 1882 has revolutionised farming. What is it called?\n")
print("a. Tractor")
print("b. Wagon.")
print("c. Combine.")
answer = input("Make your choice: ")
if answer == "a":
print("Correct!")
score = score + 1
else:
print("Incorrect! Sorry the answer was A.")
print("You got {}/3 right!".format(score))
if __name__ == "__main__":
quiz()

Need Solution for incorrect guess loop

Ok, I am creating a memory game. I have developed where the programme asks the user what word was removed, and have successfully developed the part that moves on if they get it right. However, I am struggling to find how to get it to only fail the user if they get it wrong three times. Here's what I have so far:
def q1():
qone + 1
print("\n"*2)
while qone <= 3:
question1 = input("Which word has been removed? ")
if question1 == removed:
print("\n"*1)
print("Correct")
print("\n"*2)
q2()
else:
print("Incorrect")
q1()
else:
print("You're all out of guesses!")
input("Press enter to return to the menu")
menu()
return
`
My approach is to remove recursion and simply increase the counter of failed tries.
def q1():
qone = 0
print("\n"*2)
while qone < 3:
question1 = input("Which word has been removed? ")
if question1 == removed:
print("\n"*1)
print("Correct")
print("\n"*2)
q2()
return
else:
print("Incorrect")
qone += 1
print("You're all out of guesses!")
input("Press enter to return to the menu")
menu()
return
When you do qone + 1, you need to assign it to something (so perhaps qone += 1)
What is the else outside the while loop linked to?
You seem to have a recursive definition going. Think carefully about the chain of calls that would be made and what your base case should be. Once you know these things, it would be easier for you to write the code. Also, think about whether you need recursion at all: in this case, it doesn't seem like you would.
You should not have the function calling itself, use range for the loop, if the user gets the question correct go to the next question, if they get it wrong print the output:
def q1(removed):
print("\n"*2)
for i in range(3):
question1 = input("Which word has been removed? ")
if question1 == removed:
print("\nCorrect")
return q2()
print("\n\nIncorrect")
input("You're all out of guesses!\nPress enter to return to the menu")
return menu()
If the user has three bad guesses the loop will end and you will hit the "You're all out of guesses!\nPress enter to return to the menu"

Categories

Resources