I am a beginner with python and I wrote a quiz program, how do I repeat a question in my quiz if the answer given is wrong? I'd also like to give the user an option to skip to the next question in the same text box as the answer.
This is my current source code:
score = 0
q1 = input("What is the square root of 64?: ")
if q1 == ("8"):
print("Correct!")
score = score + 1
if q1 == ("skip"):
break
else:
print("Incorrect.")
print("")
q2 = input("Who was president during the year 1970?: ")
if q2 == ("Richard Nixon") or q2 == ("richard nixon"):
print("Correct!")
score = score + 1
else:
print("Incorrect.")
print("")
q3 = input("How many stars are on the American flag?: ")
if q3 == ("50"):
print("Correct!")
score = score + 1
else:
print("Incorrect.")
print("")
q4 = input("In the US, which state has the largest population?: ")
if q4 == ("California") or q4 == ("california"):
print("Correct!")
score = score + 1
else:
print("Incorrect.")
print("")
q5 = input("Who discovered the Americas in 1492?: ")
if q5 == ("Christopher Columbus") or q5 == ("christopher columbus"):
print("Correct!")
score = score + 1
else:
print("Incorrect.")
print("")
if score == 0:
print("Your score is 0. Better luck next time.")
if score == 1:
print("Your score is 1. Better luck next time.")
if score == 2:
print("Your score is 2. Better luck next time.")
if score == 3:
print("Your score is 3. Not bad. Try again soon!")
if score == 4:
print("Your score is 4. Not bad. Try again soon!")
if score == 5:
print("Your score is 5. Awesome! You rock!")
You'll want to make use of functions to call the same code to show the question.
To do the skipping, you can have the program detect a special answer (in the example below it's "skip") and use that to recognize when to skip to the next question).
Here's an example:
QUESTIONS = {'question1' : 'answer', 'question2': 'answer'}
score = 0
def ask_question(question, answer):
global score
while True:
response = input(question + "\n")
if response == 'skip':
return
elif response == answer:
score += 1
break
def question_loop():
for question, answer in QUESTIONS.items():
ask_question(question, answer)
def print_results():
#print results here
pass
question_loop()
print_results()
Related
#This is a for loop to get the score of a player playing a riddle game
#It runs and loops but it's not calculating the score properly. #There're 6 riddles and 3 rounds. #Say I get 4/6 correct my score is 20 but it's displaying 3.0 instead. how do I get a precise answer while importing the math function?
for i in range(6):
print(riddles[i])
#
userchoice = input("Enter A, B, C, or D: ")
if userchoice.upper() == answers[i]:
print("That's Correct")
score += 5
print(f" {score}")
else:
print("That's Incorrect")
score -= 1
print(f"{score}")
total = total + int(score)
highScoreEasy = print(f"Here is your score: {int(total/score)} !!!!!")
print()
Shouldn't it just be a simple sum?
riddles = []
answers = []
riddle_score = 5
total = len(riddles) * riddle_score
score = 0
for i, riddle in enumerate(riddles):
print(riddle)
userchoice = input("Enter A, B, C, or D: ")
if userchoice.upper() == answers[i]:
print("That's Correct")
score += riddle_score
else:
print("That's Incorrect")
print(f"Here is your score: {score}/{total}!")
I am a beginner in python, working on some code, this is the code I have so far and I don't know how to do it on here. so far I made a code about input the students' score from the user and print pass or retake. and now I am trying to print the highest Korean score with the name and index. and I want to know is there any way to print the name who got the highest score with index(ex. if Kira got the highest score than should be printed like: '3: Kira got the highest score on the Korean test.') How can I make this work? I searched up the internet and tried several ways but still doesn't work so I ask here..
students = ['Anna', 'Elsa', 'Kira']
korean = []
math = []
for i, name in enumerate(students,1):
print('{}: {}'.format(i, name))
for stu in students:
for y in range(1):
kscore = int(input("Enter {}'s korean score: ".format(stu)))
for x in range(1):
mscore = int(input("Enter {}'s math score: ".format(stu)))
if kscore <= 50 and mscore <= 70:
print("You need to retake both")
elif kscore <= 50:
print("You need to retake Korean")
elif mscore <= 70:
print("You need to retake Math")
else:
print("You are pass")
korean.append(kscore)
math.append(mscore)
print('{}: {} got the highest score on the Korean test.'.format(i, name, max(korean)))
You needed to get the index of the maximum score take that index to get the person's name.
Here is the full code:
P.S: I changed some things because they were not efficient.
students = ['Anna', 'Elsa', 'Kira']
korean = []
math = []
for i, name in enumerate(students, 1):
print('{}: {}'.format(i, name))
for stu in students:
kscore = int(input("Enter {}'s korean score: ".format(stu)))
mscore = int(input("Enter {}'s math score: ".format(stu)))
if kscore <= 50 and mscore <= 70:
print("You need to retake both")
elif kscore <= 50:
print("You need to retake Korean")
elif mscore <= 70:
print("You need to retake Math")
else:
print("You are pass")
korean.append(kscore)
math.append(mscore)
person = students[korean.index(max(korean))]
print('{}: {} got the highest score on the Korean test.'.format(i, person))
I would like to implement error handling so that if the user puts in anything besides an integer they get asked for the correct input. I believe try/except would work but I am wondering how I can get it to check for both a correct number within a range and ensuring there are no other characters. I have pasted my code below for review.
Thanks!
# Rock Paper Scissors
import random as rdm
print("Welcome to Rock/Paper/Scissors, you will be up against the computer in a best of 3")
# game_counter = 0
human_1 = input("Please enter your name: ")
GameOptions = ['Rock', 'Paper', 'Scissors']
hmn_score = 0
cpt_score = 0
rps_running = True
def rps():
global cpt_score, hmn_score
while rps_running:
hmn = int(input("""Please select from the following:
1 - Rock
2 - Paper
3 - Scissors
\n""")) - 1
while not int(hmn) in range(0, 3):
hmn = int(input("""Please select from the following:
1 - Rock
2 - Paper
3 - Scissors
\n""")) - 1
print('You Chose: ' + GameOptions[hmn])
cpt = rdm.randint(0, 2)
print('Computer Chose: ' + GameOptions[cpt] + '\n')
if hmn == cpt:
print('Tie Game!')
elif hmn == 0 and cpt == 3:
print('You Win')
hmn_score += 1
elif hmn == 1 and cpt == 0:
print('You Win')
hmn_score += 1
elif hmn == 2 and cpt == 1:
print('You Win')
hmn_score += 1
else:
print('You Lose')
cpt_score += 1
game_score()
game_running()
def game_score():
global cpt_score, hmn_score
print(f'\n The current score is {hmn_score} for you and {cpt_score} for the computer \n')
def game_running():
global rps_running
if hmn_score == 2:
rps_running = False
print(f"{human_1} Wins!")
elif cpt_score == 2:
rps_running = False
print(f"Computer Wins!")
else:
rps_running = True
rps()
To answer your question, you can do something like the following
options = range(1, 4)
while True:
try:
choice = int(input("Please select ...etc..."))
if(choice in options):
break
raise ValueError
except ValueError:
print(f"Please enter a number {list(options)}")
print(f"You chose {choice}")
As for the a code review, there's a specific stack exchange for that, see Code Review
Does anybody know why the score counter isn't working in this program? The program is designed to run 10 random maths questions and then display the score. However although it asks the questions, it will always display the score as being '0'
name = input('Type in your name')
questioncount = 0
score = 0
import random
for questioncount in range(0,10):
number1 = random.randrange(1,13)
number2 = random.randrange(1,13)
sign = random.randrange(1,4)
if (sign) == 1 :
print('{}x{}'.format(number1, number2))
elif (sign) == 2 :
print ('{}+{}'.format(number1, number2))
elif (sign) == 3 :
print ('{}-{}'.format(number1, number2))
answer = input('What is the answer?')
if (sign) == 1:
if (answer) == number1*number2:
score == score+1
else:
pass
if (sign) == 1:
if (answer) == number1+number2:
score == score+1
else:
pass
if (sign) == 1:
if (answer) == number1-number2:
score == score+1
else:
pass
pass
print('you got {} answers right!'.format(score))
There are some problems:
You forgot to change the numbers in the if statements.
You have to parse the input of the answer into int because input returns a string.
score == score+1 is a comparison and it always returns false. It should be "=". score = score + 1 or in a shorter way score += 1 is exactly the same
2 ifs nested for just one thing could be written in the same if statement.
You wrote this:
if (sign) == 2:
if (answer) == number1+number2:
score += 1
else:
pass
It could be:
if (sign) == 2 and (answer) == number1+number2:
score += 1
You should use if/elif statements instead of else:pass
This way
if (sign) == 1 and (answer) == number1*number2:
score += 1
elif (sign) == 2 and (answer) == number1+number2:
score += 1
elif (sign) == 3 and (answer) == number1-number2:
score += 1
and even better
if (sign == 1 and answer == number1 * number2) or (sign == 2 and answer == number1 + number2) or (sign == 3 and answer == number1 - number2) :
score += 1
That said, I would write this program like this:
import random
name = input('Type in your name\n')
score = 0
for _ in range(10):
number1 = random.randrange(1,13)
number2 = random.randrange(1,13)
sign = random.choice(["*", "+", "-"])
expression = "{0} {1} {2}".format(number1,sign,number2)
print(expression)
answer = int(input('What is the answer?\n'))
print("-------------")
if answer == eval(expression):
score += 1
print('{}, you got {} right answers!'.format(name, score))
Notes:
The use of _ it's because it is not important. You can call it whatever you want and you don't even have to declare it before.
The \n means carriage return.
You should do some more changes to prevent user from writting others characters in the answer, but I think you have work enough to do with this.
**count = 0**
player = input("Player Name: ")
print("WELCOME TO MY QUIZ %s" % player, )
print("Would You like to play the quiz ??")
start = input()
if start == "Yes" or start == "yes":
print("Lets Start %s" % player, )
print("Q1. What is the capital of India ?")
print("A. Delhi")
print("B. Mumbai")
q1 = input()
if q1 == "A":
**count += 1**
else:
print("")
print("Q2. How many states are there in India ?")
print("A. 28")
print("B. 29")
q2 = input()
if q2 == "B":
count += 1
else:
print("")
print("Q3. What is the capital of Maharashtra ?")
print("A. Delhi")
print("B. Mumbai")
q3 = input()
if q3 == "B":
count += 1
else:
print("")
***print("You got"),str(count)+"/3 right!"***
else:
print("Thank You, Goodbye")
I have done this so far but im not getting the proper score any help ?
I dont get any output regarding the score or the count
i only get "You Got:
that's it
You are not using print() correctly.
Print the score with
print("You got {0}/3 right!".format(count))
print("You got"), str(count)+"/3 right!"
is a tuple. print("You got") is a function call in Python3; it prints to the screen but returns None. str(count)+"/3 right!" is a string. The comma between the two expressions makes the combined expression a tuple. You don't see the second part because it was never passed to the print function. Python just evaluates the expression and then leaves it to get garbage collected since it is not assigned to anything.
So to fix your code with minimal changes, move the parenthesis and remove the comma:
print("You got" + str(count) + "/3 right!")
But building strings with + is not recommended.
Matt Bryant shows the preferred way. Or, since you are using a Python version greater than 2.6, you can shorten it a wee little bit:
print("You got {}/3 right!".format(count))
The {} gets replaced by count. See The Format String Syntax for more info.
Also, instead of multiple calls to print:
print("Lets Start %s" % player, )
print("Q1. What is the capital of India ?")
print("A. Delhi")
print("B. Mumbai")
you can print a single multiline string:
print("""Lets Start {}
Q1. What is the capital of India ?
A. Delhi
B. Mumbai""".format(player))
Fewer function calls makes it faster, and it is more readable and requires less typing.
I think you do it like this. (Not Sure)
score = 0
ans = input('What is 2+2')
if ans == '4':
print('Good')
score = +1
else:
print('Wrong')
score = +0
To Show The Score Do This
print(score, 'Out Of 1')