Trying to make flash cards in Python 3 [closed] - python

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 6 years ago.
Improve this question
I just recently started with python and was trying to make some sort of flash cards. I did this by making a text file inside note pad and just writing some simple math problems. The problems were written like this.
1 + 1 = ???
2
2 + 2 = ???
4
8 x 4 = ???
32
then my code was this.
#!/usr/bin/python3
x = 0
f=open('cardsss.txt').readlines()
while x < 6:
line = f
print(line[x])
answer = input()
if answer == line[x+1]:
print ('Correct')
else:
print ('Wrong')
x = x + 2
print ("Done")
The problem is that when i put the answer in, it always says that what ever i put in is wrong, and i can not figure out why.
Where i would get a screen like this
1 + 1 = ???
2
Wrong
2 + 2 = ???
4
Wrong
8 x 4 = ???
32
Wrong
Done

The lines containing the answers end with a new line character \n. You need to strip the new line character off the lines you're reading from the file to make the items match:
if answer == line[x+1].strip():
...

Solution:
TESTS_NUM = 3
with open('cardsss.txt') as f:
for _ in range(TESTS_NUM):
line = next(f)
print(line)
answer = input("Your answer: ")
right_answer = next(f)
if answer.strip() == right_answer.strip():
print("Correct")
else:
print("Wrong")
print("Done")
This solution works if the file 'cardsss.txt' doesn't contain empty lines.

Related

print down the line and automatically updated continuouslyin [duplicate]

This question already has answers here:
Python 3 Print Update on multiple lines
(2 answers)
Closed 1 year ago.
i have a command
import time
i=0
b=0
while(True):
i=i+1
b=b+1
time.sleep(2)
print('Jack: {} '.format(str(i)) ,end='')
print('Han: {} '.format(str(b)) ,end='\r')
i want print this like
Jack: 1
Han : 1
in the next loop it still prints at that position only the number changes like this
Jack: 2
Han : 2
Note: Do not combine 2 prints into 1 print
I need ideal
If I read what you want correctly, you want to update the number, not print a new line. In which case use blessings and print at the location on the screen instead.
Something like:
from blessings import Terminal
from time import sleep
term = Terminal()
i = 0
while True:
print(term.move(1, 1), f"I am a number: {i}")
i += 1
sleep(1)
Note that there are other terminal control libraries, I just like blessings.

want to print a line and next when match found-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 2 years ago.
Improve this question
I have a variable called message.
that variable has value like below:
:1A:name
:1B:Address
:1C:phone
:2A:/256789422254
TEST VALUE
:2B:/INSTITUTION
from above variable I want to take only :2A: field contains value
which means I wants only below two line
:2A:/256789422254
TEST VALUE
I tried with
lines = message.readlines()
for index,line in enumerate(lines):
if :2A: in line:
print lines [index+2]
which is not working.
Try this:
s = '''
:1A:name
:1B:Address
:1C:phone
:2A:/256789422254
TEST VALUE
:2B:/INSTITUTION
'''
x, y = s[s.index(':2A:') - 1 :].strip().split("\n")[:2]
x = x.split(':')[2]
print(x, y)
Output:
/256789422254 TEST VALUE
message=""":1A:name
:1B:Address
:1C:phone
:2A:/256789422254
TEST VALUE
:2B:/INSTITUTION"""
def solver(lines):
x, y = 0, 0
for i, line in enumerate(lines):
if line.find(':2A:') == 0:
x = i
if line.find(':2B:') == 0:
y = i
break
return lines[x:min(x + 2, y)]
solver(message.split('\n'))
#Output [':2A:/256789422254', 'TEST VALUE']
The solution works by finding the index of ':2A' in the array of lines. It also finds the position of ':2B' in the array. Then it merely returns a slice of the lines in between.

After a while loop has finished, the code doesn't continue after that

I am trying to make a quiz, in python, where I use quite a few while loops, so I can easily leave code, or re run it. The problem is, once one of my nested loops has finished running, the code doesn't continue to run. I will leave some pseudocode incase my logic is incorrect, and the actual code after that.
Pseudocode
i = 0
array = [0]
while i < 1:
while length of array < 11:
do something
print "done something!"
Basically, once the length of array has reached 11, the print doesn't happen.
Here is the actual code also
diff =int(input("Choose a difficulty; 1 2 3"))
diffs = [1, 2, 3]
while diff not in diffs:
diff = int(input("Invalid input; choose a difficulty; 1 2 3"))
data = []#This will hold all of the data in the quiz file
answers = []#This will hold the current answers available to the user
answers2 = []#This will hold the current questions used, so that the answers do appear in a random order
letters = ["A. ","B. ","C. ","D. "]#This is so that each answer has an identifier
Questions = [0]
i = 0
score = 0
with open(filenameq,"r") as quizFile:
fileReader = csv.reader(quizFile)
for row in fileReader:
data.append(row)#This creates a 2D array, so that the program can access specific values in the file
while i < 1:
while len(Questions) < 11:
a = 0
while a in Questions:
a = randint(0,9)
Questions.append(a)
print(data[0][a])#The cell where the question is located in the file
answers = []
answers2 = []
for x in range(0,(diff+1)):
answers.append(data[a+1][x])
x = 0
b = 0
correct = 0
while x <= diff:
b = randint(0,diff)
if b in answers2:
continue
answers2.append(b)
print(letters[x]+answers[b])
if b == 0:#the first item in the CSV file is the correct value
correct = x
x += 1
answer = input("Enter the letter of the answer you think is correct").upper()
if correct == letters.index(str(answer[0]+". ")):#This is the index of the letter that the user entered, in the letters list
score += 1
print("Quiz finished")
with open(filename,"a+") as scoreFile:
fileWriter = csv.writer(scoreFile)
fileReader = csv.reader(scoreFile)
for row in fileReader:
if row[0] == username:
print(row)
row[2] = "y"
print(row)
fileWriter.writerow(row)
Finally, here is the csv file i am trying to manipulate
What is the name of the gorgon in Greek Mythology?,How did a warrior defeat Medusa in Greek Mythology,Who is the God of the Yellow River in Chinese Mythology?,Who is the mother of Hephaestus in Greek Mythology?,Who is the mother of Hephaestus in Greek Mythology?,Which river was Achilles dipped in as a baby?,Where did Zeus cast the Titans after Cronus defeated them?,What does the Helm of Darkness grant to the wearer?,Which is a pantheon of Norse Gods - excluding the Aesir?,What is Yggdrasil?
Perseus,Medusa,Ares,Zeus
A Shield,A Virus,Laceration,Cavalry
He Bo,Yang Zing,Kukulkan Ah Puch
Hera,Aphrodite,Demeter,Persephone
Pomegranate,Orange,Guava,Apple
Styx,Cocytus,Acheron,Phlegethon
Tartarus,The Asphodel Meadows,The Underworld,The Mourning Fields
Invisibility,Invincibility,Immortality,Ignitability
Vanir,Hel,Tyr,Yggdrasil
A Plant,A Person,A Deity,A World
So, each question is at the top, and the possible answers are in the bottom for each question, with the correct answers as row[0], or the first index in each line.
Thank you in advance for helping me :)
EDIT: Added some extra code to my main code, that I forgot to include originally, to clarify what "diff" and "diffs" are
Seems to be due to the fact that you never close your initial while loop: while i < 1. Since the value of i stays at 0, your outermost while loop will never close, causing your program to be stuck in an infinite loop. If you close that loop by setting i = 1 at the end, this particular problem should be resolved.
Alright, I figured it out myself, and it is exactly what I thought it was; the logic in the 1st nested while loop prevented it from ending, as the Questions array was Questions = [0], and the a variable was prevented from being in Questions if a was already in Questions, but a could already be 0-9, when 0 was already in Questions. Basically, It never could end!

ValueError when splitting lines in a text file [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 5 years ago.
Improve this question
I'd like to split each line of a text file into two by " - ", but I keep getting this error:
File "quiz.py", line 21, in Vocab
questions, answers = line.split("-")
ValueError: too many values to unpack (expected 2)
I'm quite new to coding and could use some help. All tips are welcome as well!
import hashlib
testFile = ""
def qSearch():
options = input ("Vocab/Grammar/or Special? (v/g/s)")
if options == "v":
testFile = "Vocabtest"
Vocab()
elif options == "g":
Grammar()
testFile = "Grammartest"
elif options == "s":
Special()
testFile = "Specialtest"
else:
qSearch()
def Vocab():
with open('Vocabtest.txt','r') as f:
for line in f:
questions, answers = line.split("-") ### error
print (questions)
qSearch()
The text in my text file is formatted like so:
Magandang umaga - Good Morning
Magandang hapon - Good Afternoon
Magandang gabi - Good evening
Magandang umaga sa’yo - Good Morning to you
Magandang hapon din sa’yo - Good Afternoon to you to
"Unpacking" is the name for what you're doing when you write
value1, value2 = a_list
When you do an assignment like that, you're implicitly making an assumption about how many values are contained in a_list -- here it's 2. If there's more or less than 2, there's no good way to give value1 and value2 values without doing very surprising and unhelpful things (like leaving one empty, or leaving some elements of the list unassigned).
So too many values to unpack means that there's at least one line in your file where line.split('-') results in more than 2 elements -- that is, there's at least one line with more than one -.
The problem is because on line 21 in your input text (.txt) file you have more than one - but you only expect one.
A safer way to do it would be to only split once:
questions, answers = line.split("-", 1)

Can't return a dictionary from my function [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 8 years ago.
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.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Improve this question
I am getting an invalid syntax error
SyntaxError: invalid syntax
root#collabnet:/home/projects/twitterBot# python twitterBot2.py
File "twitterBot2.py", line 58
return screenNames
when returning a dictionary from this function:
def getUserName(lookupIds):
l = len(lookupIds) # length of list to process
i = 0 #setting up increment for while loop
screenNames = {}#output dictionary
count = 0 #count of total numbers processed
print 'fetching usernames'
while i < l:
toGet = []
toAppend = []
if l - count > 100:#blocks off in chunks of 100
for m in range (0,100):
toGet.append(lookupIds[count])
count = count + 1
print toGet
else:#handles the remainder
print 'last run'
r = l - count
print screenNames
for k in range (0,r):#takes the remainder of the numbers
toGet.append(lookupIds[count])
count = count + 1
i = l # kills loop
toAppend = api.lookup_users(user_ids=toGet)
print toAppend
screenNames.append(zip(toGet, toAppend)
#creates a dictionary screenNames{user_Ids, screen_Names}
#This logic structure breaks up the list of numbers in chunks of 100 or their
#Remainder and addes them into a dictionary with their count number as the
#index value
#print str(len(toGet)), 'screen names correlated'
return screenNames
I am running the function like so:
toPrint = {}#Testing Only
print "users following", userid
toPrint = getUserName(followingids)#Testing Only
I have tried commenting out and just printing screenNamesand I still get the same error except on the print statement instead. I am pretty sure I am running the return right thanks for the look.
You forgot a closing parenthesis on a preceding line:
screenNames.append(zip(toGet, toAppend)
# ^ ^ ^^?
# | \---- closed ---/|
# \----- not closed ---/
You'll have another problem here, as screenNames is a dict object, not a list, and has no .append() method. If you wanted to update the dictionary with key-value pairs, use update() instead:
screenNames.update(zip(toGet, toAppend))

Categories