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
So I am coding and when I tried to print out a certain line from a text file , it would keep on giving me an indentation error.But when I indent it , it gives me invalid syntax.EDIT= THE CODE WORKS WHEN I REMOVE IF GTIN == 86947367:, BUT WHY ?
if GTIN == 86947367 :
fp = open("read_it")
for i, line in enumerate(fp):
if i == 0:
elif i == 2:
fp.close()
Correct indentation for your code will be:
if GTIN == 86947367:
fp = open("read_it")
for i, line in enumerate(fp):
if i == 0:
pass
elif i == 2:
pass
fp.close()
Make sure you don't mix TAB with spaces as it will ruin your indentation altogether.
The better indentation for your code I think is :
if GTIN == 86947367:
fp = open("read_it")
for i, line in enumerate(fp):
if i == 0:
pass
elif i == 2:
pass
fp.close()
You always need your for loop, and your file closure indented at the same level as your 'open' statement, so that you loop over the file only if you have opened it
An even better solution would be :
if GTIN == 86947367:
with open("read_it") as fp:
for i, line in enumerate(fp):
if i == 0:
pass
elif i == 2:
pass
Using 'with' ensures that your code will always close the file, even if an error occurs. It is good practice to use the 'with' when opening files or simiar - and you don't need to use 'close' as the 'with statement takes care of it automatically.
Related
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 28 days ago.
Improve this question
was making some code and i ran into the error here is the code
import random
foo = ['sad', 'mad', 'happy ', 'inbetween', 'bored']
print("hello answer 1 or 2 or 3")
e = input(str)
if e == '1' : print("ok give me a sentence and ill tell you how i feel about it") ;a = input("please enter a sentence ") ;a == ('i hate you') :print(" i feel sad and mad that you hate me") ;a == ('I hate you') :print("i feel sad and mad that you hate me")
elif e == '2' :print("ok ill give you advice")
elif e == '3' :print("so you want to have a converstation")
else :print(" thats not an option")
A minimal reproducible example for this:
>>> if True: True: print('x')
...
File "<stdin>", line 1
SyntaxError: illegal target for annotation
The problem is that the second True was intended to be another if condition, but is instead just an expression. The parser treats : print('x') as a type annotation for True; but type annotations have to be applied to individual variable names, not expressions.
The specific error is only possible because print('x') is an expression, and thus a valid type annotation. If it were another kind of statement, this would cause a generic syntax error:
>>> if True: True: pass
File "<stdin>", line 1
if True: True: pass
^
SyntaxError: invalid syntax
Either way, there was a typo here - the second True: was meant to be if True:. However, this does not fix the problem by itself:
>>> if True: if True: pass
File "<stdin>", line 1
if True: if True: pass
^
SyntaxError: invalid syntax
It is not permitted to put multiple ifs on the same line; nor can elif and else be paired with the matching if on the same line:
>>> if True: pass; else: pass
File "<stdin>", line 1
if True: pass; else: pass
^
SyntaxError: invalid syntax
Putting multiple statements on a line - by using semicolons, and/or by putting the "suite" of an if etc. statement on the same line - is strongly discouraged in Python. It has multiple limitations, and makes the code much harder to read.
To make the example work, use indented blocks in the normal way:
if True:
if True:
pass
When I run the following code, I get an error: "IndentationError: unident does not match any outer indentation level".
What am I doing wrong? I've included my code below for reference:
file=open('csquetionseasy.txt','r')
print(file.read(432))
answersinputeasy=input('enter the letter responding to the correct answer for all 3 questions e.g. BBB')
if answersinputeasy==('BAA'):
print('you got 3/3!')
else:
if answersinputeasy==('BAB'):
print('2/3!')
else:
if answersinputeasy==('BBB'):
print('1/3!')
else:
if answersinputeasy==('ABB'):
print('0/3!')
else:
if answersinputeasy==('AAB'):
print('1/3!')
else:
if answersinputeasy==('AAA'):
print('2/3!')
else:
if answersinputeasy==('ABA'):
print('1/3!')
Use elif rather than else. You need else statement to do something when if and elif statements evaluate to false.
if answersinputeasy==('BAA'):
print('you got 3/3!')
elif answersinputeasy==('BAB'):
print('2/3!')
elif answersinputeasy==('BBB'):
print('1/3!')
elif answersinputeasy==('ABB'):
print('1/3!')
elif answersinputeasy==('AAA'):
print('2/3!')
elif answersinputeasy==('ABA'):
print('1/3!')
else:
print('Invalid Input')
Also, if you want to indicate a block of code, you must indent each line of the block by the same amount, which is typically four spaces.
The reason that you are getting the error "IndentationError: unident does not match any other indentation level" is because you are chaining tabs together to create a nested logic statement (in pseudo-code):
if <condition>:
#then do something
else if <condition>:
#then do something else
else if <condition>
#then do something further else
This is not how Python likes to see syntax in a logical block. Additionally, the next error you're going to run into will surround the use of nested if statements inside of else clauses.
To run an else if statement in Python, you will want to use the syntax elif: followed by an indented line with the code that you want to execute if that condition is met (in pseudo-code):
if <condition>:
#then do something
elif <condition>:
#then do something else
elif <condition>:
#then do something further else
One other call out as a best practice, is that you should include an explicit else clause in a conditional block with a bunch of elif statements if you're not going to do any further validation on the string you're getting from the user. Imagine that the user passed in XYZ. They wouldn't meet any of the conditions you've defined, and because of that the code would just continue out of the bottom of this logic block (which may or may not be a good thing). In the following code, I've added an example of what an explicit else clause might look like, but it's up to you to ultimately decide what might make sense for your application:
file=open('csquetionseasy.txt','r')
print(file.read(432))
answersinputeasy=input('enter the letter responding to the correct answer for all 3 questions e.g. BBB')
if answersinputeasy==('BAA'):
# Code to be executed following an if-statement must be indented by 4 spaces:
print('you got 3/3!')
elif answersinputeasy==('BAB'):
# Code to be executed following an elif-statment (else-if) must be indented by 4 spaces:
print('2/3!')
elif answersinputeasy==('BBB'):
print('1/3!')
elif answersinputeasy==('ABB'):
print('0/3!')
elif answersinputeasy==('AAB'):
print('1/3!')
elif answersinputeasy==('AAA'):
print('2/3!')
elif answersinputeasy==('ABA'):
print('1/3!')
# Else clause would provide a default condition that executes if none of the prior cases are met.
else:
# Code following an else statment must be indented by 4 spaces:
#Example of a default Else-block entry:
print('Wasn\'t able to parase your entry into a valid answer!')
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)
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.
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'm learning Python and can't work out why the following doesn't work.
Can anyone advise? code below
thanks
# Make sure that the_flying_circus() returns True
print "What is your number?"
num = input()
print "What is bla?"
bla = input()
def the_flying_circus():
if num ==4 and bla=="bla": # Start coding here!
return True
print "Well done!"
# Don't forget to indent
# the code inside this block!
elif num == 2 or bla== zog:
print "OK"
# Keep going here.
# You'll want to add the else statement, too!
else:
print "Bad luck!"
the_flying_circus()
The return True is probably not what you want to have on the top of the if block. Try removing it.
The only condition that will return True is num==4 and bla=='bla'. Otherwise, the return value is None. However, 'Well done!' will never be printed since the return statement occurs first.
Couple of things...
1) return True should be moved to the end of the function (as mentioned by others)
2) watch how you collect input... use raw_input for your string, use input for the number.
This works for me:
def the_flying_circus():
if a==4 and b=='bla':
print "Well done!"
elif a==2 or b=="zog":
print "OK"
else:
print "Bad luck!"
return 1
a = input("What is your number? ")
b = raw_input("What is bla? ")
the_flying_circus()