Quiz from external text file Python - python

I am trying to create a quiz where I have questions and answers from an external text file to import into Python so that the user can input a selection.
The problem is that my code only prints "Correct" at the end of the quiz once, and doesn't say after each question answered if the user got the question correct or incorrect.
The first column (detail[0]) is where the question is and the correct answer is in the fourth column (detail[4]))
Thanks
Here is what is in the text file:
What is 1+1,1,2,2
What is 2+2,4,2,4
Here is the source code below:
def quiz():
file = open("quiz.txt","r")
right = False
for line in file:
detail = line.split(",")
print(detail[0])
select = input("Select 1 or 2: ")
if select == detail[3]:
right = True
break
if right == True:
print("Correct")
else:
print("Incorrect")

Just modify the main for-loop to print the result there and then:
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 :(")

Related

Python code randomly stops, why? (This is for a quiz game)

The following code randomly stops where mentioned in the code.
def playSaved(choiceSaved):
y = open(choiceSaved,'r')
for line in y.readlines():
qna = line.split(" : ")
randQues.append(qna[0])
randAns.append(qna[1])
print("Processing game.....")
time.sleep(2)
savedChoice = input("\nOk! Are you ready to play? (Y/N) ")
# the code stops here, after getting the input
if savedChoice.lower() == 'y':
for num in range(len(y.readlines())):
count = 1
if "?" in randQues[num]:
ansForSaved = input(f"Question {count}:\n{randQues[num]}\n> ")
else:
ansForSaved = input(f"Question {count}:\n{randQues[num]}\n> ")
if ansForSaved == randAns[num]:
print("Correct!")
else:
print("Wrong!")
I tried looking online, but didn't find anything. I figured i could ask here
it reads the line from a text file and the first part is a question the second part is the answer i want to check if the answer input by user matches the answer based on the txt file
some sample data:
name : jd
country : finland
age : 23
colour: red
The for loop:
for num in range(len(y.readlines()))
...will never be entered because the file contents have already been consumed.
Change to:
for num in range(len(randQues))

Export quiz result to a text file in Python

Is it possible to have questions and answers exported to a text file such as result.txt?
I answer all the questions and at the end - all the information is saved in a txt file as a list, that can be viewed later.
Example:
Question 1
Answer 1
Question 2
Answer 2
...
I was wondering about file=open, but would that be right?
And how do I export input questions with file open?
I hope you can help.
from datetime import date
today = date.today()
date = today.strftime("%d.may, %Y.year\n")
print("Today is:", date)
print("Greeting text 1")
print("Greeting text 2\n")
def Vide():
while True:
name = input("Let's see!\nWhat is your name? ")
description = input("Enter a description of the environmental pollution: ")
city = input("In which city is environmental pollution observed? ")
address = input("Enter your residential address: ")
try:
question = int(input("Do you have any additional complaints?\nAnswer with: 1 = Yes, 2 = No\n" ))
except ValueError:
print("Answer with numbers - 1 or 2!")
continue
if question == 1:
print("\nJYou noted that there are additional complaints, fill in the questions again!\n")
continue
elif question == 2:
print("Thank you for your complaint, it will be resolved! 💜")
break
else:
print("Only numbers 1 and 2 are allowed!")
Vide()
As you wanted the file content as a key-value pair, initialize a dictionary and add the corresponding values, instead of using separate variables for names, descriptions, etc. use them as dictionary keys.
First, initialize a global dictionary
global mydict
Initialize it in Vide() function. (use of global keyword because mydict is being modified in a function)
global mydict
mydict = {}
Store question and answer as a key-value pair
mydict["name"] = input("Let's see!\nWhat is your name? ")
mydict["description"] = input("Enter a description of the environmental pollution: ")
mydict["city"] = input("In which city is environmental pollution observed? ")
mydict["address"] = input("Enter your residential address: ")
In try block:
mydict["question"] = int(input("Do you have any additional complaints?\nAnswer with: 1 = Yes, 2 = No\n"))
Now the if-else statements:
if mydict["question"] == 1:
print("\nJYou noted that there are additional complaints, fill in the questions again!\n")
continue
elif mydict["question"] == 2:
print("Thank you for your complaint, it will be resolved! 💜")
break
else:
print("Only numbers 1 and 2 are allowed!")
After calling the function Vide(), write your dictionary to a file
with open("qna.txt", "w") as f:
f.write(str(mydict))
f.close()
Whole code
global mydict
print("Greeting text 1")
print("Greeting text 2\n")
def Vide():
global mydict
mydict = {}
while True:
mydict["name"] = input("Let's see!\nWhat is your name? ")
mydict["description"] = input("Enter a description of the environmental pollution: ")
mydict["city"] = input("In which city is environmental pollution observed? ")
mydict["address"] = input("Enter your residential address: ")
try:
mydict["question"] = int(input("Do you have any additional complaints?\nAnswer with: 1 = Yes, 2 = No\n"))
except ValueError:
print("Answer with numbers - 1 or 2!")
continue
if mydict["question"] == 1:
print("\nJYou noted that there are additional complaints, fill in the questions again!\n")
continue
elif mydict["question"] == 2:
print("Thank you for your complaint, it will be resolved! 💜")
break
else:
print("Only numbers 1 and 2 are allowed!")
Vide()
with open("qna.txt", "w") as f:
f.write(str(mydict))
f.close()
This can be done by writing or appending to a text file. You are correct, we can use the file = open structure to achieve this. I suggest writing something like the following:
file = open('results.txt', 'w')
Then use the following to write to the file once it has been opened.
file.write("Use your variables and questions from before to print user entered data")
Don't forget to close the file once you're done!
file.close()

I'm Having Trouble checking two values are equal in python

finishgame = "n"
counter = 0
#the song randomizer
num = random.randint(0,50)
f = open("songs.txt","r")
lines = f.readlines()
#first letter only system
song = str(lines[num])
firstl = song[0]
print(firstl)
#the artist generator
g = open("artists.txt","r")
line = g.readlines()
print(line[num])
#guess system
while finishgame == "n":
guess = str(input("Enter your guess"))
if guess == song:
counter = counter+5
print("Correct!")
finishgame = "y"
elif counter == 2:
print("Out of guesses, sorry :(")
print("The Correct Answer was:",song)
finishgame = "y"
else:
counter = counter+1
print("Try Again")
First time asking so apologizes for any errors. I have create a song guessing game where it takes a song from an external file, and displays the first letter of the title. It then takes the artist from a separate file (where it is in the same line as the song in the other file) and displays that too. Then you should guess the song. However, my code is having trouble recognizing when a 'guess' is correct, please can anyone tell me why? I've tried using different methods of identification such as the id() function but so far have not got any results. I'm probably missing something simple but any help would be much appreciated.

Splitting a Python Filename [duplicate]

This question already has answers here:
Extract file name from path, no matter what the os/path format
(22 answers)
Closed 4 years ago.
I am trying to create an anagram program quiz. One of the things I have done is having one central method of reading from a specified file dependant on which option the user has chosen rather than having to repeat the code. However, when trying to save the info to file, the variable saved has the pathfile saved inside it. How can I split it so that it will only save the name of the file (i.e, name of the quiz) that has been opened?
def main():
name = input("Please Enter your name to begin")
print("Hi",name,"Welcome to the Computer Science Quiz")
user_choice = menu()
option = choice(user_choice)
option, counter = questions(option)
update_file(name, option, counter)
def menu():
print("Select from the following categories:")
print("1 for System's Architecture, 2 for Memory, 3 for Storage or 4 for Network Topologies")
choice = int(input("choose option"))
if choice >0 and choice<=4: ## range check
print("you have chosen",choice,)
else:
print("This is an invalid number")
menu()
return choice
def choice(user_choice):
if user_choice == 1:
systems = open('systems.csv','r')
return systems
elif user_choice ==2:
memory = open('memory.csv','r')
return memory
else:
storage = open('storage.csv','r')
return storage
def questions(option):
counter = 0
for line in option:
anagrams = (line.rstrip("\n").split(","))
question = anagrams[0]
answer = anagrams[1]
print (question)
print (answer)
guess = input("Enter your guess")
if guess == answer:
print("Well Done")
counter = counter + 1
else:
print("oops")
print("You have scored",counter,"correctly")
return option,counter
def update_file(name, option, counter):
string_counter = (str(counter))
string_option = (str(option))
results = [name,",",string_counter,",",string_option,"\n"]
file = open('results.csv','a')
file.writelines(results)
file.close()
This is what it shows when the file is saved for the option variable:
<_io.TextIOWrapper name='storage.csv' mode='r' encoding='cp1252'>
You can remove the path from filename with this function:
import os
print(os.path.basename(file_name_with_path))

Writing to a file using a users input in Python

I'm trying to write a user input to a word file for my troubleshooting system. However it doesn't write to the file and ends the code. I am trying to make it so that if the user inputs 'no' twice, then it should follow the following code:
if count == 2:
f = open('problems.txt', 'w')
ui = ("What is the problem?")
f.write(ui)
Instead the code ends.
Here's the code:
count = 0
while count != 2:
a = input("Is your phone broken?")
if a == "no":
count = count + 1
if count == 2:
f = open('problems.txt', 'w')
ui = ("What is the problem?")
f.write(ui)
But the code doesn't open the file and write to the file, the program just ends after the user inputs no. I don't understand what I'm doing wrong? Could anyone help me please.
If you are using Python 2.x, use raw_input.
count = 0
while count != 2:
a = raw_input("Is your phone broken?")
print a
if a == "no":
count = count + 1
if count == 2:
f = open('problems.txt', 'w')
ui = ("What is the problem?")
f.write(ui)

Categories

Resources