Generating quiz questions randomly from a file in Python - 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

Related

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()]

Need help importing a quiz from a text file

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.

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)

Reading the next line of a file

im new to this site and I know alot of people aren't very happy when somebody asks a question previously asked. However, I wish to ask despite it being previously asked beacause all the answers I found did not make much sense to me (im new to python!), so I was wondering if somebody could dumb it down for me or directly correct my code.
Im writing a code where the user inputs a GTIN-8 code and it searches a csv excel file for that code, it then reads the appropriate information about the product (price,ect...) and prints it out. However I cant search the second line of the file for some reason. Here is my code:
#csv is imported to read/write to the file
import csv
#Each Product is printed alongside it's GTIN-8 code and Price
print("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~")
print("~ Welcome to Toms bits and bobs ~")
print("Pencil, 12346554, £0.40")
print("50 Staples, 12346882, £1.00")
print("50 Paper Clips, 12346875, £1.20")
print("Large Eraser, 12346844, £1.50")
print("100 A4 Sheets, 12346868, £2.00")
print("100 A3 Sheets, 12346837, £2.50")
print("25 Byro Pens, 12346820, £2.20")
print("Handwriting Pen, 12346899, £5.50")
print("50 Split Pins, 12346813, £0.60")
print("Office Chair, 12346912, £25.00")
print("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~")
#The file is opened and the user inputs the code for the product they
#wish to find.
file = open("Product_list.csv", "r")
purchase = input(print("Please enter the GTIN-8 code of the product you wish to purchase e.g 12346554"))
line = file.readline()
data = line.split(",")
if data[0] == purchase:
while(line):
print ("Product: ", data[1])
print ("GTIN-8 code: ", data[0])
print ("Stock: ", data[2])
print ("Description: ", data[3])
print ("Price: ", data[4])
line = file.readline()
break
else:
print("Product not found")
file.close()`
You are reading second line but because of the break, you never get a chance to use it since your code always breaks out of while loop if it enters there. Just remove it and your code should work fine.
Also, assuming your syntax is correct on this line.
purchase = input(print("Please enter the GTIN-8 code of the product you wish to purchase e.g 12346554"))
^^^^^This will cause a syntax error. You should remove this print as well

replacing text in a file, Python

so this piece of code is meant to take a line from a file and replace the certain line from the string with a new word/number, but it doesn't seem to work :(
else:
with open('newfile', 'r+')as myfile:
x=input("what would you like to change: \nname \ncolour \nnumber \nenter option:")
if x == "name":
print("your current name is:")
test_lines = myfile.readlines()
print(test_lines[0])
y=input("change name to:")
content = (y)
myfile.write(str.replace((test_lines[0]), str(content)))
I get the error message TypeError: replace() takes at least 2 arguments (1 given), i don't know why (content) is not accepted as an argument. This also happens for the code below
if x == "number":
print ("your current fav. number is:")
test_lines = myfile.readlines()
print(test_lines[2])
number=(int(input("times fav number by a number to get your new number \ne.g 5*2 = 10 \nnew number:")))
result = (int(test_lines[2])*(number))
print (result)
myfile.write(str.replace((test_lines[2]), str(result)))
f=open('newfile', 'r')
print("now we will print the file:")
for line in f:
print (line)
f.close
replace is a function of a 'str' object.
Sounds like you want to do something like (this is a guess not knowing your inputs)
test_lines[0].replace(test_lines[0],str(content))
I'm not sure what you're attempting to accomplish with the logic in there. looks like you want to remove that line completely and replace it?
also i'm unsure what you are trying to do with
content = (y)
the output of input is a str (which is what you want)
EDIT:
In your specific case (replacing a whole line) i would suggest just reassigning that item in the list. e.g.
test_lines[0] = content
To overwrite the file you will have to truncate it to avoid any race conditions. So once you have made your changes in memory, you should seek to the beginning, and rewrite everything.
# Your logic for replacing the line or desired changes
myfile.seek(0)
for l in test_lines:
myfile.write("%s\n" % l)
myfile.truncate()
Try this:
test_lines = myfile.readlines()
print(test_lines[0])
y = input("change name to:")
content = str(y)
myfile.write(test_lines[0].replace(test_lines[0], content))
You have no object known purely as str. The method replace() must be called on a string object. You can call it on test_lines[0] which refers to a string object.
However, you may need to change your actual program flow. However, this should circumvent the error.
You need to call it as test_lines[0].replace(test_lines[0],str(content))
Calling help(str.replace) at the interpreter.
replace(...)
S.replace(old, new[, count]) -> str
Return a copy of S with all occurrences of substring
old replaced by new. If the optional argument count is
given, only the first count occurrences are replaced.
Couldn't find the docs.

Categories