I am trying to create a multiple choice quiz that takes questions from an external .txt file and prints it in python. The text file is laid out like this:
1,Who was the first man to walk on the moon?,A.Michael Jackson,B.Buzz Lightyear,C.Neil Armstrong,D.Nobody,C
When I run the code and input the right answer it still says incorrect but continues to say the answer I inputted.
In the code I split each line in the text file by a ',' so the correct answer in the text file is always detail[6]. In the code I have put:
if answer.upper() == detail[6]:
print("Well done, that's correct!")
score=score + 1
print(score)
elif answer.upper() != detail[6]:
print("Incorrect, the correct answer is ",detail[6])
print(score)
I thought this would work as it is checking the inputted answer against detail[6] but it always comes out as incorrect.
import random
score=0
with open('space_quiz_test.txt') as f:
quiz = f.readlines()
questions = random.sample(quiz, 10)
for question in questions:
detail = question.split(",")
print(detail[0],detail[1],detail[2],detail[3],detail[4],detail[5])
print(" ")
answer=input("Answer: ")
while True:
if answer.upper() not in ('A','B','C','D'):
print("Answer not valid, try again")
else:
break
if answer.upper() == detail[6]:
print("Well done, that's correct!")
score=score + 1
print(score)
elif answer.upper() != detail[6]:
print("Incorrect, the correct answer is ",detail[6])
print(score)
I would like the code to be able to check if the inputted answer is correct by checking it against detail[6] within the text file, instead of always coming out as incorrect, the correct answer is detail[6].
The problem is that readlines() retains the newline character at the end of each line.
Your detail[6] is something like 'C\n' rather than 'C' itself. To fix that, use
detail = question.strip().split(",")
Related
Using these commands I get the three sentences.
AnyText = driver.find_elements_by_xpath('AnyXpath')
for AnyText1 in AnyText:
print(AnyText1.text)
In the console, I get something like that:
**
1) Hello my name is John
**
2) Hello my name is Mark
**
3) Hello my name is Alex..
How can I check that all three sentences have the word "name"
and print("OK") if the word is in the sentence (element) and print("ERROR") if not.
Im try:
AnyText = driver.find_elements_by_xpath('AnyXpath')
Text = 'name'
if all(Text in AnyText1 for two in AnyText1):
print('OK')
else:
print('ERROR')
but this method only checks the first element (first sentence). I also tried something like this
AnyText = driver.find_elements_by_xpath('AnyXpath')
Text = 'name'
for AnyText1 in AnyText:
if all(Text in AnyText1):
print('OK')
else:
print('ERROR')
but I get many times OK or ERROR
UPD:
With a question on the text, I figured out with your help. Now I want to understand the numbers)
I have a loop that checks the next number more or less. If more, writes ERROR, if less, writes OK
sort_month=driver.find_element_by_xpath('/html/body/div[6]/div[2]/div/div[1]/div/div[13]/table/thead/tr/th[3]/a[4]').click()
month2=driver.find_element_by_xpath('//*[starts-with(#id, "td_")]/td[3]/span[3]')
month2=month2.text.replace("'", "").replace(" ", "")
buffer = 0
if int(month2) > buffer:
print()
buffer = int(month2)
month1=driver.find_elements_by_xpath('//*[starts-with(#id, "td_")]/td[3]/span[3]')
for spisok_month in month1:
spisok_month = spisok_month.text.replace("'", "").replace(" ", "")
if int(spisok_month) > buffer:
print('ERROR')
elif int(spisok_month) < buffer:
print('OK')
else:
print('==')
buffer = int(spisok_month)
here I would also like to see OK or ERROR only once.
Any ideas?
The problem seems to be with the short form for loop in your first snippet. Basically it should look like the below:
AnyText = driver.find_elements_by_xpath('AnyXpath')
Text = 'name'
if all(Text in AnyText1.text for AnyText1 in AnyText):
print('OK')
else:
print('ERROR')
UPDATE:
On the updated part of your question, this is a different implementation as you have to update the condition in each iteration. For readability, it probably makes sense to keep this expanded:
outcome = 'OK'
for spisok_month in month1:
spisok_month = spisok_month.text.replace("'", "").replace(" ", "")
if int(spisok_month) > buffer:
outcome = 'ERROR'
elif outcome == 'OK' and int(spisok_month) == buffer:
outcome = '=='
buffer = int(spisok_month)
print(outcome)
Note: The update is almost a separate question. this means that either your first question was not representative of the actual problem or you should ask in a separate post
In you code AnyText1 is a WebElement, not a text. You should use AnyText1.text to get text and then it will work:
AnyText = driver.find_elements_by_xpath('AnyXpath')
Text = 'name'
# AnyText1 is a WebElement and you should get text
if all(Text in AnyText1.text for AnyText1 in AnyText):
print('OK')
else:
print('ERROR')
Please check coding conventions to improve code style.
In our class we were given the task to basically create a program that re-enacts the US election last year. One of the extra challenges is that when you enter an ID number that is already in the file, it should come up with an error and just stop. However, when I try to execute this code, it comes up with
ValueError: I/O operation on closed file.
This is the code I've done so far...
ID = input("Please input ID code ")
if(len(ID)) == 6:
print("ID length: Valid")
N += 1
else:
print("ID Code: Error")
sys.exit()
with open('ID.txt', 'a') as idc:
idc.write(ID + ' ')
already_seen = set()
for line in idc:
if line not in already_seen:
print("Valid")
else:
print("Error")
sys.exit()
Thanks
You should know the difference between the
with open('ID.txt', 'a') as idc:
do sth
and the
idc = open('ID.txt', 'a')
In the first case, after the do sth finished, the __exit__() of the idc will be called to close the file object.
I advise you to use the second expression that I indicate above. If you are new to Python, this blog will help you to understand the detail reasons.
I am doing a school project and I have to make a voting system that uses a voting code. I need help with the code that opens up the 2 files, checks to see if the code is there and gives a value error if it is.
while True:
Code = input("Enter your 6 digit code: ")
try:
Code = int(Code)
if "0" in str(Code): break
if len(str(Code)) != 6 : raise ValueError
else: break
readt = open("Trump.txt" , "r")
readh = open("Clinton.txt" , "r")
readhh = readh.read()
readtt = readt.read()
if Code in str(readtt) or Code in str(readhh): raise ValueError
else: break
readt.close()
readh.close()
except ValueError:
print("Invalid")
Here are a couple pointers to fix your program:
The if len ... else part seems to leave the while loop either through raise or break. The code that does open is never executed.
Also you call open a lot of times. This will become problematic because leaking file descriptors is a problem. Use the with open(...) statement for this. This way, you cannot leave the file open by accident. Your close statements are behind another if ... else construction that will leave the loop in every case.
Your variable names are a bit opaque, perhaps you want to invent some more telling ones.
Why are there two files? Shouldn't there be only one file that contains all the used codes?
Assuming that you presented all the information in your question this is the solution for your problem:
def code_checker():
codes = []
with open('Trump.txt', 'r') as f1:
for line in f1:
codes.append(line.rstrip())
with open('Clinton.txt', 'r') as f2:
for line in f2:
codes.append(line.rstrip())
code = input('Enter your 6 digit code:\n')
while True:
if '0' in code or len(code) != 6:
print('Invalid code\n')
code = input()
continue
elif code in codes:
raise ValueError
code_checker()
keywords = open("keywords.txt", "r")
problem = input("Please give us a simple description of the problem you are having with your phone, so we can identify the solution and give it to you...")
if "screen" in problem:
print(keywords.readline())
elif "water" in problem:
print(keywords.readline(2))
elif "battery" in problem:
print(keywords.readline(3))
elif "dropped" in problem:
print(keywords.readline(4))
keywords.readlines() is what you are looking for.
keywords.readline() is taking only one line so that if you say keywords.readline(1) It will return second letter in first line
This is the coding that I have so far. The basic concept is that you have a separate file to type in the answers and then the program accesses the separate file and draws information from it.
#!/usr/bin/python3.2
# -*-coding:Utf-8 -*
#Vocabulary/translation quiz
import os
import random
keep_adding=input("Would you like to start a new quiz ? If yes, press \"S\" : ")
with open("data.txt","a") as f: #look for the file data.txt for the questions
while keep_adding=="S": #ongoing action to look for the answer
word=input("Enter a word : ")
translation=input("And its translation : ")
f.write("{0},{1},\n".format(word,translation))
keep_adding=input("To continue, press \"O\" : ")
#in case the file doesn't exist, we create one :
with open("data.txt","a") as f:
pass
os.system('clear')
print("* * * QUIZ STARTS! * * *") #this shows the quiz has started after 'o' input
with open("data.txt","r") as f:
question = [line.split(",") for line in f]
i = 0
score = 0 #variables
while i<len(question):
num = random.randint(0,len(question)-1) #creates random question from the list
print("\nQuestion number", i+1,": \nWhat is the translation for", question[num][0], "?")
answer = input("Answer :")
if (answer == str(question[num][1])):
print("Congratulations! That's the good answer!")
score += 1
else:
print("Wrong. The correct answer was :",question[num][1]) #just tells you the wrong answer
i += 1
if len(question)==0:
print("\nThe file is empty. Please add new words to start the quiz !\n")
else:
if i>1:
qu_pl = "questions"
else:
qu_pl = "question"
if score>1:
sc_pl = "answers"
else:
sc_pl = "answer"
print("\n RESULTS :\n ",i, qu_pl,", ",score,"correct ",sc_pl," \n"\
," --> Your score is : ",score*100/i,"% !\n")
The basic concept is that you have a separate file to type in the answers and then the program accesses the separate file and draws information from it.
My problem; the program accesses this file and successfully gains the information but when you actually try to run the program with multiple answers (in my case a 32 answer German Vocab test), the program doesn't mark the answers as right. Have tried many alternatives and it does work with single answers in a .txt document.
If someone has any knowledge and could help me, it would be much appreciated! :)
My .txt questions and answers are set out like this;
beliebt,popular
eng,narrow
Thanks for any help!! <3
The program listed works for me as is (using Python 3.3.2). If you want it to work with multiple possible answers for one word (not sure if that's what you meant), you can use
if (answer in question[num][1:]):
instad of
if (answer == str(question[num][1])):
you might also want to strip any spaces from your sample answers:
for i in range(len(question)):
for j in range(len(question[i])):
question[i][j] = question[i][j].strip(' ')
use lstrip and rstrip if you want to have spaces inside the answer.
Then you can add multiple answers just like this:
What is the translation for eng?
narrow, tight