Quiz Program using a Text File - python

Am trying to create a quiz program in Python where the questions are stored in one txt file with the answers in another. The questions are set out in the text file as follows:
Which one of these is a percussion instrument?
A. Trumpet
B. Euphonium
C. Viola
D. Glockenspiel
The program pulls the questions out in random order and keeps score of the number of right answers.
I know how to open files, read from them and display the contents of the file on the screen, I even know now how to randomise the info in the file. However, as there are multiple lines involved AND another file to get the answer from, I have no idea where to start.
I would really appreciate any help you could offer me.
Feel free to ask questions if you need to clarify anything.
EDIT:
Ok, I have decided to change my idea a little, which might make it easier. Using a CSV file might be the better option. Here is what I have so far.
def Trivia():
score=0
myFile = open("farming.csv","r") # opens the CSV file and stores it in the array myFile
players = myFile.readlines() # reads the lines of the CSV file into the variable players
questionno=1
while questionno < 6:
for p in players:
data = p.split(",") #splits each cell of the CSV file into its parts
questions = data[0]
answera = data[1]
answerb = data[2]
answerc = data[3]
CorrectAnswer = data[4]
print("Question #",questionno)
print(questions) #prints the question and the 3 answers
time.sleep(0.5)
print(answera)
time.sleep(0.5)
print(answerb)
time.sleep(0.5)
print(answerc)
time.sleep(0.5)
answer = input("Answer? ") #asks the user for their answer
time.sleep(1)
print(".")
time.sleep(1)
print(".")
time.sleep(1)
print(".")
if answer == CorrectAnswer: #checks if the answer is correct and prints approptiate responses
print("That is the correct answer")
score=score+1
time.sleep(1)
else:
print("That is not the correct answer")
time.sleep(1)
print("Your current score is", score)
print("")
questionno = questionno+1
myFile.close()
My problem now is that I don't know how to get to the next question in the quiz. Using this format it keeps asking the same question. Any idea?
Thanks.

This question is two-fold: what to save, and how to save. Let's answer "how" first.
Seems like what you need is serialization, which is a fancy way of saying "saving data in a particular format". I would learn about pickle or json. This will allow you to save and load objects, so you could for instance save a class that represents a question.
And about what you save and not how you save it, I guess each answer should be saved along with a number of a question, then you can link between them - sort of like foreign keys in a DB.
Good luck!

I am not exactly 100 percent sure as yet I haven't run the program myself to check. But I think it could be the "While" module. It says while questionno is under six, do that question, and so when you add 1 to questionno it is still under 6 running the program over again. Change it too this
If questionno == 1:
.....
.....
.....
for next question in the quiz you'll need to just start it with
If questionno == 2:
.....
.....
.....
now write the 2nd quiz

Related

Python text adventure: Consecutive if-query in while Loops

I'm coding a text adventure in python.
In general: I want people to be able to make mistakes for putting in the wrong answers. If they not write a valid answer like "1" or "2" they should get send back with a loop until they put in a viable answer without breaking the whole code and to start all over again.
As mentioned in the title: I have a problem with consecutive if-query-loops (with elif else etc.) I do found a nice while-function for just one query. (here on stack overflow. THX for that so far)
But trying to implement it for consecutive if-querys leading to the next one is not working.
The first if-query works fine, but after going to the second one, when writing gibberish for example, instead of looping back to the second question I get send to the first(!) one again...
I tried to put "else: -continue..." to every(!) if-query, even with multiple "while True:" after each query.. but that resulting in infinty loops...
I'm a beginner with python, but heard that maybe switch / case -functions might be working?
Still, is there maybe a more efficient way?
Thanks a lot for your time and effort! :-)
while True:
question1 = input("question1")
if question1 =="1":
print("Wrong")
break
elif question1 == "2":
print("Right, go on!!")
question2 = input("question2")
if question2 == "1":
print("Wrong")
break
elif question2 == "2":
print("Right, go on!!")
question3 = input("question3")
if question3 == "1":
print("wrong")
break
elif question3 == "2":
print("Right, go on!!")
quit()
else:
print("Use a valid answer!")
continue
Here's an idea of how I'd structure your program and what things you should look at and learn to properly implement what you want to do.
I'd recommend you use a state machine and putting all your logic into a dictionary (which later you could read from a json file, so you can create different adventures without having to modify the code at all)
The logic of your adventure is:
You are in question 1 and you have 3 possible answers:
1 -> Correct: Go to next question
2 -> Incorrect: Go back to first question
Anything else -> Repeat current question
Then you can mount each question with a nested dictionary structure, like this:
states = {
1: {
"Question": "The text of question 1",
"Answers": {
"1": 2, # Answer "1" will go to state 2
"2": 1, # Answer "2" will go to state 1
"Default": 1 # Anything else will stay in state 1
}
},
2: {
"Question": "The text of question 2",
"Answers": {
"2": 3, # Answer "2" will go to state 3
"1": 1, # Answer "1" will go to state 1
"Default": 2 # Anything else will stay in state 2
}
}
}
You can add more options to your dictionary, maybe you want the user to allow more answer for each question, and you can then put to which state each answer goes (maybe you don't want sequential questions, but more a graph with complex paths)
Now your main code will have a variable state that you can initialize to 1
state = 1
You can then access the information of this state by doing
states[state]
For example the question of the current state is
states[state]["Question"]
And the answers dictionary are in
states[state]["Answers"]
So if the user inputs an answer answer, you can get the appropriate response doing
states[state]["Answers"][answer]
This might look a bit complicated now for you, but try understanding dictionaries and how to structure your question and answers in them and you will see that your code then simplifies a lot, you just need to print the Question for the current state, read the answer and update the state according to the dictionary.
so you want something like
state = 1
while True:
# print current question
print(states[state]["Question"])
# ask the user an answer
answer = input("What is your answer? ")
# check if answer exist for the current state
if answer in states[state]["Answers"].keys():
# if it exist go to the state pointed by that answer
state = states[state]["Answers"][answer]
else:
# if it doesn't exist, go to the state pointed by default
state = states[state]["Answers"]["Default"]
You maybe want a final state that gives you a victory, so you can get a special state that when reached will print "You won" and exit the game
Try to understand the logic of this program and you will find that a combination of state machines and dictionaries will make your code very flexible and very easy to understand.

How can I work around a KeyError in Python? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 3 years ago.
Improve this question
I am trying to create a Forecasting tool, which analyses historical passenger traffic at a given airport. The anylysis will be based on a linear regression with various GDPs (Gross Domestic Product) of countries related to the airport.
A person can type in the name of the independant variable, which then gets selected from the Excel file.
Once a person gets the question "Which Country's GDP would you like to set as the independant variable for the Regression Analysis?", there is the possibility of typing a country wrong. In that case I receive a KeyError.
I am trying to work around that with "try / except", but I still receive a KeyError (See lines 36-49). I would really appreciate some help!
Thank you!
If it helps, here is the GitHub Link: https://github.com/DR7777/snowflake
(See lines 36-49 of main_file.py)
Here is my code:
Ive tried with while loops, for / except, but it seems I am too new to understand.
# This part saves the first row of the Excel as a list,
# so I can give the user a list of all the countries,
# if the person types in a country, that's not on the list.
loc = ("IMF_Country_GDP_Data.xlsx")
wb = xlrd.open_workbook(loc)
sheet = wb.sheet_by_index(0)
sheet.cell_value(0, 0)
list_of_countries = sheet.row_values(0)
possible_selection = (list_of_countries[1:]) #This is the list with all the possible countries, without the Excel cell A1
#Introduction
print("Hello, welcome to the Air Traffic Forecasting Tool V0.1!")
print("Which Country's GDP would you like to set as the independant variable for the Regression Analysis?")
Country_GDP = input("Please type your answer here: ")
#here we check, if the typed Country is in the list
try:
possible_selection == Country_GDP
print("Your country is on the list.")
except KeyError:
print("Oh no! You typed a country, which is not in our database!")
print("Please select one of the countries listed below and try again")
print(possible_selection)
#now continuing with the previous code
print("Ok, I will conduct the analysis based on the GDP of " + str(Country_GDP) + "!")
print("Here are your results: ")
#here is the rest of the code
What I want to achieve is:
If a person types a name, which is on the list of countries, the program runs the regression.
If the country is not on the list, I dont want to receive a KeyError. I would like the program to say:
Oh no! You typed a country, which is not in our database!
Please select one of the countries listed below and try again
And then print the possible_selection variable, so the user can see which selection he has.
Thank you very much!
No need to get a key error at all. Just use in.
while True:
selection = input('Which country?')
if selection in list_of_countries:
print('Your country is on the list')
break
else:
print('You typed an invalid entry, lets try again')

Python overwriting variable in script 1 with user input from script2

I've been struggling with this for several days now, and I cant find any answers that actually relate to what I'm trying to do, at least none that I can find.
I am trying to create a basic system for keeping track of my finances (i.e. cash, whats in the bank, etc). I have two scripts: display.py and edit.py.
The idea is that I can easily pull up display.py and see how much I have and where it is, and use edit.py to change the amounts shown in display.py, without having to open Vi or entering the numbers every time i run display.py.
In theory, edit.py would take user input, and then overwrite the value in display with that new input, so that display is independent of edit and saves those values
display.py:
cash1 = "5.14"
bank1 = "none"
print "you have", cash1, "in your pocket"
print ""
print ""you have", bank1, "in the bank"
and using this in edit.py
f = open("display.py", "r")
contents = f.readlines()
f.close()
cashinput1 = "cash1"
cashinput2 = raw_input("enter the new coin amount: ")
cashtransfer = ("=".join((cashinput1,cashinput2,)))
contents.insert(5, cashtransfer)
f = open("display.py", "w")
contents = "".join(contents)
f.write(contents)
f.close()
I know edit.py isn't very clean, but the problem is that it's adding the input to the end of a line, pushing it to the next one. The goal is overwrite cash1, not add another. I've tried simply importing, but that doesn't work as the changes aren't saved.
tl;dr How do I overwrite a variable in one script with user input from another script?
I'm using Python 2.7.12
thanks in advance.
EDIT: Sqlite3 looks designed for this type of thing, so this question is answered. Not sure how to close this without any answers though.
As I've been pointed toward Sqlite3, I will use that. Thanks again, question answered :)

Building a ranking list in Python: how to assign scores to contestants?

(I posted this on the wrong section of Stackexchange before, sorry)
I'm working on a assignment which is way above my head. I've tried for days on end figuring out how to do this, but I just can't get it right...
I have to make a ranking list in which I can enter a user, alter the users score, register if he/she payed and display all users in sequence of who has the most score.
The first part I got to work with CSV, I've put only the basic part in here to save space. The menu and import csv have been done: (I had to translate a lot from my native language, sorry if there is a mistake, I know it's a bad habit).
more = True
while more:
print("-" * 40)
firstname = raw_input("What is the first name of the user?: ")
with open("user.txt", "a") as scoreFile:
scoreWrite = csv.writer(scoreFile)
scoreWrite.writerow([firstname, "0", "no"])
scoreFile.close()
mr_dnr = raw_input("Need to enter more people? If so, enter 'yes' \n")
more = mr_dnr in "yes \n"
This way I can enter the name. Now I need a second part (other option in the menu of course) to:
let the user enter the name of the person
after that enter the (new) score of that person.
So it needs to alter the second value in any entry in the csv file ("0") to something the user enters without erasing the name already in the csv file.
Is this even possible? A kind user suggested using SQlite3, but this basic CSV stuff is already stretching it far over my capabilities...
Your friend is right that SQlite3 would be a much better approach to this. If this is stretching your knowledge too far, I suggest having a directory called users and having one file per user. Use JSON (or pickle) to write the user information and overwrite the entire file each time you need to update it.

Using a dictionary, practice code

I apologize for my earlier questions as they were vague and difficult to answer. I am still fairly new to programming and am still learning the ins and outs of it all. So please bear with me. Now to the background information. I am using python 3.3.0. I have it loaded onto the Eclipse IDE and that is what I am using to write the code and test it in.
Now to the question: I am trying to learn how to create and use dictionaries. As such my assignment is to create a price matching code that through user interface will not only be able to search through a dictionary for the items (which are the keys and the locations and prices which are the values associated with the keys.) So far I have created a user interface that will run through well enough without any errors however (at least within the IDE) When I run through and input all of the prompts the empty dictionary is not updated and as such I cannot then make a call into the dictionary for the earlier input.
I have the code I have written so far below, and would like if someone could tell me if I am doing things correctly. And if there are any better ways of going about this. I am still learning so more detailed explanations around code jargon would be useful.
print("let's Price match")
decition = input("Are you adding to the price match list?")
if decition == "yes":
pricematchlist = {"Snapple":["Tops",99]}
location = input("Now tell me where you shopped")
item = input("Now what was the item")
price = input("Now how much was the item")
int(price)
pricematchlist[item]=location,price
print(pricematchlist)
else:
pricematchlist = {"Snapple":["Tops",99]}
reply = input("Ok so you want to search up a previous price?")
if reply == "yes":
search = input("What was the item?")
pricematchlist.item(search)
These are a few minor changes. For dictionaries: you are using them correctly.
print("let's Price match")
pricemathlist = {"Snapple":["Tops", 99]} # assign it here
decition = input("Are you adding to the price match list?").lower() #"Yes"-->"yes"
if decition == "yes":
# pricematchlist = {"Snapple":["Tops",99]}
# If this whole code block is called repeatedly, you don't want to reassign it
location = input("Now tell me where you shopped")
item = input("Now what was the item")
price = int(input("Now how much was the item"))
# int(price) does nothing with reassigning price
pricematchlist[item]=location,price
print(pricematchlist)
else:
reply = input("Ok so you want to search up a previous price?").lower()
if reply == "yes":
search = input("What was the item?")
print pricematchlist[search] # easier way of accessing a value

Categories

Resources