Need help importing a quiz from a text file - python

I need help on using a quiz from an external text file but with the following code below, it only prints "Correct" for the last question in the text file and all other questions are just said as "Incorrect" even when the correct answer is given. Detail[0] is the column with the question and detail[3] is the column with the correct answer. How do I proceed with this?
What's in the text file:
What is 1+1,1,2,2
What is 2+2,4,1,4
Code below:
def quiz():
file = open("quiz.txt","r")
for line in file:
detail = line.split(",")
print(detail[0])
select = input("Select 1 or 2: ")
if select == detail[3]:
print("Correct")
else:
print("Incorrect")
quiz()

!/usr/bin/python3
def quiz():
file = open("quiz.txt","r")
for line in file:
detail = line.split(",")
print(detail[0])
detail[3] = detail[3].strip('\n')
select = input("Select 1 or 2: ")
if select == (detail[3]):
print("Correct")
else:
print("Incorrect")
quiz()
you had a \n at the end of the string and wasnt matching!

The result of input is an int, while the result of line.splitis a string.
You're making that comparison: '2'==2 which return False

Without a few lines of "quiz.txt" it's hard to be sure, but here's a guess: Your input is a csv file with a carriage return separating lines, but the last line doesn't have a carriage return.
If you print detail (i.e. insert a 'print(detail)' you can quickly determine if this is the case.
edit:
After seeing your data, I recognize an additional problem: you're comparing 'select' against the last element of 'detail'. What you want to do is compare 'detail[select]' against 'detail[3]'.
I tested the following and it seems to do what you want:
file = open("quiz.txt","r")
for line in file:
detail = line.split(",")
select = input("Select 1 or 2: ")
if detail[select] == detail[3].strip():
print("Correct")
else:
print("Incorrect")
In the future when you are getting unexpected behavior, try printing the values you are comparing to see they are what you expect. inserting 'print(detail)' and 'print(select)' statements would have made your problem immediately obvious.

Related

Reading from and printing records from a file

I need to be able to read from a file and print records if a variable entered is pre-existent in the file. I have tried to open the file as 'f' however that would only read the first line in the file, heres my code:
problem = input("Please select from one of these: sink, faucet, toilet, shower, heater, other: \n")
temporaryFile = open("plumberInfo.txt" , "r")
for row in temporaryFile:
record = row.split(",")
if record[6] == problem:
Pforename = record[1]
Psurname = record[2]
Pfee = record[3]
Pexperience = record[4]
Prate = record[5]
print("You have selected", Pforename, Psurname, "they have", Pexperience , "years of experience and they specialise in", problem, "\n")
else:
print("Invalid input")
plumberSearch() #This part isn't relevant
Also below I have attached some contents of the file:
743,Auryn,Smith,42.00,6,44.50,faucet,extra
583,Michael,Lanlow,25.00,8,75.00,sink,extra
731,Hanna,Taylor,42.00,14,55.00,heater,extra
981,Tomie,Agen,32.00,6,44.50,toilet,extra
I don't understand the problem as it worked fine for when I was searching by the ID ([record0]). There is no traceback error, it just states invalid input which means record[6] != problem, however it is equal.
When I try the code on my machine, printing record shows me that the last item contains a new line character at the end. Thus when you search for sink, you're essentially doing the search sink == sink\n, hence why you get invalid input.
Reading in the file also reads in the new line, and you need to be aware. You would need to remove it before doing the comparison.

Generating quiz questions randomly from a file in Python

I'm just practising in Python and have an issue, I'm trying to generate a quiz from a text file which will ask a random question from the file.
It is supposed to read the question then list the answers, separating them with the commas in the file which did work before trying to randomise.
At the moment it is just reading the first character of the line then display error "list index out of range" when trying to print "detail[1]". For example if it picks line 3 in the text file, will read "C" then when inputting will come up with the error.
Text file is below:
A,What is 1+1?,1,2,3,4,b,
B,What is 2+2?,1,2,3,4,d,
C,What is 3+3?,2,4,6,8,c,
D,What is 4+4?,4,8,12,18,b,
E,What is 6+6?,18,12,10,9,b,
F,What is 1+2?,1,2,3,4,c,
G,What is 5+5?,5,6,7,10,d,
H,What is 2*2?,2,4,6,8,b,
Code is below:
import random
class question:
def rand_line(fname):
lines = open(fname).read().splitlines()
return random.choice(lines)
file = rand_line("questions.txt")
for line in file:
detail = line.split(",")
print(detail[0])
input()
print(detail[1])
print("a: ", detail[2])
print("b: ", detail[3])
print("c: ", detail[4])
print("d: ", detail[5])
print("Select A, B, C or D: ")
select = input()
if select == detail[6]:
print("correct!")
else:
print("incorrect")
I think this is a line that is throwing you off:
file = rand_line("questions.txt")
You call it file, but really its just a random line in the file that looks like this:
C,What is 3+3?,2,4,6,8,c,
And when you do a split(',') your detail is only
['C']
I think you are wanting to have that line be a list/array. To do that, surround your rand_line with square brackets []
file = [rand_line("questions.txt")]
Which changes the above output to:
['C,What is 3+3?,2,4,6,8,c,']
Now when you do a split(',') your detail is
['C', 'What is 3+3?', '2', '4', '6', '8', 'c', '']
Not sure what the input() is doing between print(detail[0]) and print(detail[1])
Also, to avoid mixed inputs for your letter selection, It may be beneficial to change the case to what you know the answer is in the questions file:
print("Select A, B, C or D: ")
select = input().lower()
if select == detail[6]:
Example:
The answer is in the file is c but you are prompting to enter C
Another thing to do would be to to remove the for loop. Since file is really just a single line:
line = rand_line("questions.txt")
detail = line.split(",")
print(detail[0])
print(detail[1])
print("a: ", detail[2])
print("b: ", detail[3])
print("c: ", detail[4])
After testing it on my side, it seems that "input()" alone might not work. You are using "input" to store as a variable what the user writes, so you have to put it on a variable, which is not done automatically.
x = input('Write your answer : a, b, c or d')
I'm not sure at all the issue is actually here, this is just some try to help

Passwords/username from a file

I've recently been having trouble writing a program that involves taking the password and username from a .txt file. So far I have written:
username_file = open("usernameTest1.txt","rt")
name = username_file.readlines()
username_file.close()
print(username_file)
print(name)
print(name[0])
print()
print(name[1])
Player1Name = name[0]
print(Player1Name)
nametry = ""
while nametry != (name[0]):
while True:
try:
nametry = input("What is your Username player1?: ")
break
except ValueError:
print("Not a valid input")
(The various prints are to help me to see what the error is)
The password is successfully extracted from the file however when it is put into a variable and put through an if statement, it doesn't work!
Any help would be much appreciated!
Hopefully this is a simple fix!
Your problem is that readlines() function lets the \n character remain in your text lines and that causes the texts to not match. You can use this instead when opening the file:
name = username_file.read().splitlines()
give it a try.
the readlines function doen't strip the newline character from the end of the lines, so eventough you wrote "samplename" as input, it won't equal "samplename\n".
You can try this:
name = [x.rstrip() for x in username_file.readlines()]

How to call back to files in an if statement in python

I'm trying to make a code that takes a line from the file and prints it and then you type in an answer and if it matches another line it says 'correct'. that part is working but when we get to the 4th question it just keeps repeating and then gives an error.
In the text file the lines are separated by a '/'.
def Q():
a = 1
b = 2
while True:
file = open("AA.txt", "r")
for line in file:
sec=line.split("/")
print(sec[a])
answer = input("Type your answer: ").strip()
if answer == sec[b].strip() and b >8:
print ("Correct!")
a = a + 2
b = b + 2
elif answer == sec[b].strip() and b ==8:
print ("Done.")
break
else:
print ("Wrong it's " + sec[b])
a = a + 2
b = b + 2
file.close()
Q ()
This is the text file:
Slash separates stuff./When was the Battle of Hastings? 1066, 1078 or 1088/1066/When was the Great Fire of London? 1777 or 1666/1666/How many wives does Henry the VIII have? 8 or 6/6/When was the Wall Street Crash? 1929 or 1933/1929/
I had a hard time finding the bug in your code. I'd say that the problem is that you wrote a while-loop and had to include some confusing control mechanisms that yielded strange results. I think you would be much better served writing your code in a way that the outer loop just iterates over the lines in your textfile - you will very rarely see while loops in python programs, for the simple reason that they are tricky, and a for-loop is usually what you want to do anyways.
So, if I understood your description correctly, this code here should more or less do the job, right? I assume a textfile with one question per line in the way you have specified they would look:
def ask_questions(filename):
for line in open(filename, "r"):
question, answer = line.strip().split("/")
print(question)
user_answer = input("Type your answer: ").strip()
if user_answer == answer:
print ("Correct!")
else:
print("Wrong, the correct answer is " + answer)

My program is printing value following the order of my .txt file and I don't want that to happen

I want to prompt the user to input specific data from a text file(keys) so my dictionary can give the value for each of them.
It works like this:
fin=open('\\python34\\lib\\toys.txt')
toys = {}
for word in fin:
x=fin.readline()
x = word.replace("\n",",").split(",")
a = x[0]
b=x[1]
toys[a]=str(b)
i = input("Please enter the code:")
if i in toys:
print(i," is the code for a= ", toys[i],)
else:
print('Try again')
if i == 'quit':
break
but it prints 'try again' if I input a random key from my list. (which is the following:
D1,Tyrannasaurous
D2,Apatasauros
D3,Velociraptor
D4,Tricerotops
D5,Pterodactyl
T1,Diesel-Electric
T2,Steam Engine
T3,Box Car
T4,Tanker Car
T5,Caboose
B1,Baseball
B2,Basketball
B3,Football
B4,Softball
B5,Tennis Ball
B6,Vollyeball
B7,Rugby Ball
B8,Cricket Ball
B9,Medicine Ball
but if I do it in order it works. How can I fix this program so I can input any key at any time and it will still print its corresponding value?
You need to read in the whole file before prompting for your search term. So you'll need two loops -- one to get the whole data in, and a second loop to search through he data.
Here's what your updated code will look like. I replaced the file input with an array so that I could run it using a web tool:
fin=['D1,Tyrannasaurous','D2,Apatasauros','D3,Velociraptor' ]
toys = {}
for word in fin:
x = word.replace("\n",",").split(",")
a = x[0]
b=x[1]
toys[a]=str(b)
while 1:
i = input("\nPlease enter the code:")
if i in toys:
print(i," is the code for a= ", toys[i],)
else:
print('\nTry again')
if i == 'quit':
break
Output here: https://repl.it/BVxh
To read the file into dictionary:
with open('toys.txt') as file:
toys = dict(line.strip().split(',') for line in file)
To print values corresponding to the input keys provided by a user from a command-line interactively until quit key is received:
for code in iter(lambda: input("Please enter the code:"), 'quit'):
if code in toys:
print(code, "is the code for toy:", toys[code])
else:
print(code, 'is not found. Try again')
It uses two-argument iter(func, sentinel).

Categories