Reputation: 1
points = 0
with open("ComputerScience.txt","r") as f:
for line in f:
y = line.split(",")
question = y[0]
question1 = question
del y[0]
random.shuffle(y)
answer1 = y[0]
answer2 = y[1]
answer3 = y[2]
answer4 = y[3]
print(question1+"\n","(A)",answer1,"\n","(B)",answer2,"\n","(C)",answer3,"\n","(D)",answer4)
correctans = answer1
userans = input("Enter A,B,C,D: ")
while userans == correctans:
points = (points+1)
print(points)
How do I randomize the options and have the user to enter A B C or D and add points for every correct answer
Upvotes: 0
Views: 2579
Reputation: 473
import random
points = 0 with open("lovestory.txt","r") as f: for line in f: z = line.split(",") question = z[0] correctans = z[-1] question1 = question y = z[1:-1] random.shuffle(y) answer1 = y[0] answer2 = y[1] answer3 = y[2] answer4 = y[3] ans = {} k = 0 for choice in 'A B C D'.split(): ans[choice] = y[k] k += 1
print(question1+"\n","(A)",answer1,"\n","(B)",answer2,"\n","(C)",answer3,"\n","
(D)",answer4)
userans = input("Enter A,B,C,D: ")
print('ans', ans[userans], 'act ans', correctans)
if ans[userans] in correctans:
points += 1
print('points:', points)
Upvotes: 0
Reputation: 3282
You need to user correctans = answer1
line before shuffling the array.
After you have shuffled the array the value of variable answer1 has changed and it is not longer storing the correct answer(y[1]), that's why the score you are getting is 0.
Also you should use if
statement, in place of the while
loop because you want the user to input only one option.
Upvotes: 0
Reputation: 32244
LETTERS = ['A', 'B', 'C', 'D']
score = 0
with open("ComputerScience.txt","r") as f:
for line in f:
question, *answers = map(str.strip, s.split(','))
answers_jumbled = random.sample(answers, len(answers))
print(question)
for index, answer in enumerate(answers_jumbled):
print(f' ({LETTERS[index]}) {answer}')
answer = None
while answer not in LETTERS:
answer = input("Enter A,B,C,D: ")
if LETTERS.index(answer) == 0:
print('Correct')
score += 1
else:
print('Wrong')
print('Score:', score)
Upvotes: 0
Reputation: 476
Couple things:
while
with if
. while
tells your code to loop as long as the userans
variable is equal to the correctans
variable which since neither is changed in the body of the loop will be forever. An if statement checks the condition once.question1
= y[0]
instead of using two assignments)Bonus: Comment your code.
Hope this helps.
Upvotes: 1