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)
Related
So I have to take the numbers from a certain file
containing:
1 5
2 300
3 3
9 155
7 73
7 0
Multiply them and add them to a new file
I used the script under here but for some reason, it now gives a syntax error.
f=open('multiply.txt')
f2=open('resulted.txt','w')
while True:
line=f.readline()
if len(line)==0:
break
line=line.strip()
result=line.split(" ")
multiply=int(result[0])*int(result[1])
multiply=str(multiply)
answer=print(result[0],"*",result[1],"=",multiply)
f2.write(str(multiply))
f.close()
f2.close()
i found out that f2.write(multiply) works
but i get all the answers as 1 string (5600913955110)
how do i get it to be 1 good text file and give the right calculation
Update:
f=open('multiply.txt')
f2=open('result.txt','w')
while True:
line=f.readline()
if len(line)==0:
break
line=line.strip()
result=line.split(" ")
multiply=int(result[0])*int(result[1])
multiply=str(multiply)
answer=print(result[0],"*",result[1],"=",multiply)
answer=str(answer)
f2.write(str(answer))
f2.write(str(multiply))
f.close()
f2.close()
output:
None5None600None9None1395None511None0
at the end of the code you have this line:
f2.write(str(answer)
notice there is not a ) at the end and you have two ( in the line.
try this:
f2.write(str(answer))
Also the name of the post sounds like its provoking opinion response. Try to change it so it doesn't mention your friend but the problem at hand.
In most programming languages, there are escape sequences. Escape sequences allow you to do many things. in your case you need to add the escape sequence
"\n"
this will add a new line onto each thing you append to the file.
like this:
answer=str(result[0])+"*"+str(result[1])+"="+str(multiply)
print(answer)
f2.write(str(answer)+"\n")
I'm making a Music Quiz for a school project.
I've made a working game however I cannot get the leaderboard (which should be text and is saved as leaderboard.txt) to show different names as it overwrites the previous name.
For example, if "Sam" was to get a score of 9 and "Ben" was to get a score of 3, it would show up as "Ben-3-9" which is not what I'm after.
I am trying to get my leaderboard to work like:
Sam - 9
Ben - 3
...
My code looks like this right now:
username = input("What is your username?")
# this will ask for the persons name
password = str(input("What is the password?"))
# this will ask for a password which has been set already
if password == "1234":
print("User Authenticated")
# if the password is incorrect, tell the user so and exit
elif password != "1234":
print("Password Denied")
exit()
# GAME
# Creating a score variable
score=0
x = 0
# Reading song names and artist from the file
read = open("songnames.txt", "r")
songs = read.readlines()
songlist = []
# Removing the 'new line' code
for i in range(len(songs)):
songlist.append(songs[i].strip('\n'))
while x == 0:
# Randomly choosing a song and artist from the list
import random
choice = random.choice(songlist)
artist, song = choice.split('-')
# Splitting the song into the first letters of each word
songs = song.split()
letters = [word[0] for word in songs]
# Loop for guessing the answer
for x in range(0, 2):
print(artist, "".join(letters))
guess = str(input("Guess the song!"))
if guess == song:
if x == 0:
score = score + 3
break
if x == 1:
score = score + 1
break
quit()
# Printing score, Then waiting to start loop again.
import time
print("Your score is", score)
print("Nice Work!")
time.sleep(3)
leaderboard = open("leaderboard.txt", "r+")
leaderboard.write(username + '-' + '{}'.format(score))
leaderboard.close()
leaderboard = open("leaderboard.txt", "r+")
leaderboardlist = leaderboard.readlines()
print(leaderboardlist)
leaderboard.close()
PS: this is not 100% my code I am trying to get help from different places as my school has not taught us how to code yet due to the pandemic closing down schools.
When you do this:
leaderboard = open("leaderboard.txt", "r+")
leaderboard.write(username + '-' + '{}'.format(score))
you open the leaderboard in read-and-write mode, but it will start writing at the beginning of the file, overwriting whatever is there. If you just want to add new scores to the leaderboard, the simplest would be to open the file in "append" mode "a":
with open("leaderboard.txt", "a") as leaderboard:
leaderboard.write(username + '-' + '{}'.format(score))
Alternatively, you could open the file in "r" mode, then first read all the lines (scores) in a list or dictionary, merge / update them with the current player's new score (e.g. adding to the last score, replacing the last score, or getting the max of the new and last score of that player), and then open the file again in "w" mode and write the updated scores. (Left as an exercise to the reader.)
The problem lies within the final few lines of code, where you are writing to the leaderboard.txt file.
Using "r+" indicates that you are updating (reading and writing) the file. Opening a file this way, moves the cursor at the beginning of the file. Therefore any attempt to write to the file will override whatever is already there.
The proper way to do it, is to open the file using "a" (or "a+" if you are planning to read as well). This is append mode and will move the cursor to the end of the file.
Some other general notes:
Use the with-as statement to handle closing the file automatically after you are done.
Use f-strings as opposed to string concatenation to increase readability
With that in mind, here's the code:
with open("leaderboards.txt", "a") as f:
f.write(f"{username}-{score}")
For more on files, check this question.
For more on f-strings, check this quite extensive overview of them.
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
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.
I am trying to read from a file and return solutions based on the problem that the user inputs. I have saved the text file in the same location, that is not an issue. At the moment, the program just crashes when I run it and type a problem eg "screen".
Code
file = open("solutions.txt", 'r')
advice = []
read = file.readlines()
file.close()
print (read)
for i in file:
indword = i.strip()
advice.append (indword)
lst = ("screen","unresponsive","frozen","audio")
favcol = input("What is your problem? ")
probs = []
for col in lst:
if col in lst:
probs.append(col)
for line in probs:
for solution in advice:
if line in solution:
print(solution)
The text file called "solutions.txt" holds the following info:
screen: Take the phone to a repair shop where they can replace the damaged screen.
unresponsive: Try to restart the phone by holding the power button for at least 4 seconds.
frozen: Try to restart the phone by holding the power button for at least 4 seconds.
audio: If the audio or sound doesnt work, go to the nearest repair shop to fix it.
Your question reminds me a lot of my learning, so I will try give an answer to expand on your learning with lots of print statements to consider how it works carefully. It's not the most efficient or stable approach but hopefully of some use to you to move forwards.
print "LOADING RAW DATA"
solution_dictionary = {}
with open('solutions.txt', 'r') as infile:
for line in infile:
dict_key, solution = line.split(':')
print "Dictionary 'key' is: ", dict_key
print "Corresponding solution is: ", solution
solution_dictionary[dict_key] = solution.strip('\n')
print '\n'
print 'Final dictionary is:', '\n'
print solution_dictionary
print '\n'
print 'FINISHED LOADING RAW DATA'
solved = False
while not solved: # Will keep looping as long as solved == False
issue = raw_input('What is your problem? ')
solution = solution_dictionary.get(issue)
""" If we can find the 'issue' in the dictionary then 'solution' will have
some kind of value (considered 'True'), otherwise 'None' is returned which
is considered 'False'."""
if solution:
print solution
solved = True
else:
print ("Sorry, no answer found. Valid issues are 'frozen', "
"'screen' 'audio' or 'unresponsive'")
want_to_exit = raw_input('Want to exit? Y or N? ')
if want_to_exit == 'Y':
solved = True
else:
pass
Other points:
- don't use 'file' as a variable name anywhere. It's a python built-in and can cause some weird behaviour that you'll struggle to debug https://docs.python.org/2/library/functions.html
- If you get an error, don't say "crashes", you should provide some form of traceback e.g.:
a = "hello" + 2
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-1-6f5e94f8cf44> in <module>()
----> 1 a = "hello" + 2
TypeError: cannot concatenate 'str' and 'int' objects
your question title will get you down-votes unless you are specific about the problem. "help me do something" is unlikely to get a positive response because the error is ambiguous, there's no sign of Googling the errors (and why the results didn't work) and it's unlikely to be of any help to anyone else in the future.
Best of luck :)
When I change the line "for i in file:" to "for i in read:" everything works well.
To output only the line starting with "screen" just forget the probs variable and change the last for statement to
for line in advice:
if line.startswith( favcol ) :
print line
break
For the startswith() function refer to https://docs.python.org/2/library/stdtypes.html#str.startswith
And: the advices of roganjosh are helpfull. Particularly the one "please don't use python keywords (e.g. file) as variable names". I spent hours of debugging with some bugs like "file = ..." or "dict = ...".