Indentation error on line 32 with my if statement [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 2 years ago.
Improve this question
I'm struggling to find out why I get an indent error in my code. I've tried getting rid of tabs, and adding them. I've only used tabs: no spaces were used.
Here is a link:
https://repl.it/#OwenLagger1/SameReflectingCoderesource#main.py
Thanks for any help
P.S.
Sorry I have a link instead of code

Just copied and pasted into my editor and the if on line 32 is indented for no reason:
def main():
process_file("good_data.txt")
process_file("bad_data.txt")
process_file("empty_file.txt")
process_file("does_not_exist.txt")
def process_file(param_str_file_name):
#Variables
num_rec = 0
total = 0
average = 0
try:
file_name = open(param_str_file_name, 'r')
print("Processing file", param_str_file_name)
one_score = file_name.readline()
while one_score != "":
one_score_int = int(one_score)
num_rec = num_rec + 1
one_score = file_name.readline()
total += one_score_int
average = total / num_rec
file_name.close()
if num_rec == 0:
print("\tError!", param_str_file_name,
" is empty. Cannot calculate average\n")
else:
print("\tRecord count = ", num_rec)
print("\tTotal = ", total)
print("\tAverage = ", f"{average:.2f}", "\n")
except FileNotFoundError:
print("\tError!", param_str_file_name, " File not found\n")
except ValueError:
print("\tError!", param_str_file_name, "contains non-numeric data\n")
if __name__ == "__main__":
main()
It should work now. The output I get is:
Processing file good_data.txt
Record count = 6
Total = 281
Average = 46.83
Processing file bad_data.txt
Error! bad_data.txt contains non-numeric data
Processing file empty_file.txt
Error! empty_file.txt is empty. Cannot calculate average
Error! does_not_exist.txt File not found

From what i saw in your code the "if" on line 32 is not indented well, and the rest of the lines aswell cause of the error on the "if".
If you are using Visual Studio code and other programs they usually have a shortcut to format the code, per example on Visual Studio code if you press "Alt+Shift+F" it formats the code.
U should search for "Format Code Shortcut for ...." for the software you are using.

Related

Improper center() alignment of Python strings

I'm working on a projects that shows basic user details.
Here's the respective code that I'm having problem with.
#wrap
def show(self, *ids):
for id in ids:
try:
user = self.api.get_user(id)
print(user.name.center(80, '~'))
print('%d Followers %d Following'.center(80, '~') %
(user.followers_count, user.friends_count))
except Exception:
print('Error')
finally:
print()
The code shows both the lines with the max-width of 80 chars.
At this point it should only print maximum of 80 chars on each line.
But I'm getting this output :
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~Twitter~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
~~~~~~~~~~~~~~~~~~~~~~~~~~~58312564 Followers 1 Following~~~~~~~~~~~~~~~~~~~~~~~~~~~
The first line is seems perfect but the second line is really not looking at the center.
I read the docs and I also tried using .format() inside the print statement but I'm getting the same problem.
How can I print both the line contents at the center?
(One character difference is considerable)
Please help.
Does This work for you?
followers_count= 5831256
friends_count = 1
var = f" {followers_count} Followers {friends_count} Following "
print(f"{' Twitter ':~^80}")
print(f"{var:~^80}")
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Twitter ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
~~~~~~~~~~~~~~~~~~~~~~~~ 5831256 Followers 1 Following ~~~~~~~~~~~~~~~~~~~~~~~~
Adapt it to your method definition.
Note: var is unnecessary

How to call back to files in an if statement in python

I'm trying to make a code that takes a line from the file and prints it and then you type in an answer and if it matches another line it says 'correct'. that part is working but when we get to the 4th question it just keeps repeating and then gives an error.
In the text file the lines are separated by a '/'.
def Q():
a = 1
b = 2
while True:
file = open("AA.txt", "r")
for line in file:
sec=line.split("/")
print(sec[a])
answer = input("Type your answer: ").strip()
if answer == sec[b].strip() and b >8:
print ("Correct!")
a = a + 2
b = b + 2
elif answer == sec[b].strip() and b ==8:
print ("Done.")
break
else:
print ("Wrong it's " + sec[b])
a = a + 2
b = b + 2
file.close()
Q ()
This is the text file:
Slash separates stuff./When was the Battle of Hastings? 1066, 1078 or 1088/1066/When was the Great Fire of London? 1777 or 1666/1666/How many wives does Henry the VIII have? 8 or 6/6/When was the Wall Street Crash? 1929 or 1933/1929/
I had a hard time finding the bug in your code. I'd say that the problem is that you wrote a while-loop and had to include some confusing control mechanisms that yielded strange results. I think you would be much better served writing your code in a way that the outer loop just iterates over the lines in your textfile - you will very rarely see while loops in python programs, for the simple reason that they are tricky, and a for-loop is usually what you want to do anyways.
So, if I understood your description correctly, this code here should more or less do the job, right? I assume a textfile with one question per line in the way you have specified they would look:
def ask_questions(filename):
for line in open(filename, "r"):
question, answer = line.strip().split("/")
print(question)
user_answer = input("Type your answer: ").strip()
if user_answer == answer:
print ("Correct!")
else:
print("Wrong, the correct answer is " + answer)

Trouble with initializing first project

I'm a newbie here. I'm trying to print a list out in a doc, and I can't get my python to initialize. It's my first python project, so I'm thinking that I am missing a line of code at the top -- though I cannot figure out what that is. Here is my code:
num = input('--')
month = input('--')
crimes = ['_TOT_CLR_MURDER ','_TOT_CLR_MANSLGHTR ','_TOT_CLR_RAPE_TOTAL','_TOT_CLR_FORC_RAPE ','_TOT_CLR_ATMPTD_RAPE ','_TOT_CLR_TOTL_ROBERY ','_TOT_CLR_GUN_ROBBERY ','_TOT_CLR_KNIFE_ROBRY ','_TOT_CLR_OTH_WPN_ROB ','_TOT_CLR_STR_ARM_ROB ','_TOT_CLR_ASSLT_TOTAL ','_TOT_CLR_GUN_ASSAULT ','_TOT_CLR_KNIFE_ASSLT ','_TOT_CLR_OTH_WPN_ASLT ','_TOT_CLR_HND_FT_ASLT ','_TOT_CLR_SIMPLE_ASLT ','_TOT_CLR_BRGLRY_TOTL ','_TOT_CLR_FORC_ENTRY ','_TOT_CLR_ENTR-NO_FRC ','_TOT_CLR_ATT_BURGLRY ','_TOT_CLR_LARCNY_TOTL ','_TOT_CLR_VHC_THFT_TOT ','_TOT_CLR_AUTO_THEFT ','_TOT_CLR_TRCK_BS_THFT ','_TOT_CLR_OTH_VHC_THFT ','_TOT_CLR_ALL_FIELDS ']
f = open('list.txt','w')
for item in crimes:
f.write(item + num + "-" + num + "\n")
num++
Do you think you could help?
Edit - I made the arguments in open() into strings, and closed the file after writing - unfortunately the file will not run.

Please correct my code Python

I am trying to read from a file and return solutions based on the problem that the user inputs. I have saved the text file in the same location, that is not an issue. At the moment, the program just crashes when I run it and type a problem eg "screen".
Code
file = open("solutions.txt", 'r')
advice = []
read = file.readlines()
file.close()
print (read)
for i in file:
indword = i.strip()
advice.append (indword)
lst = ("screen","unresponsive","frozen","audio")
favcol = input("What is your problem? ")
probs = []
for col in lst:
if col in lst:
probs.append(col)
for line in probs:
for solution in advice:
if line in solution:
print(solution)
The text file called "solutions.txt" holds the following info:
screen: Take the phone to a repair shop where they can replace the damaged screen.
unresponsive: Try to restart the phone by holding the power button for at least 4 seconds.
frozen: Try to restart the phone by holding the power button for at least 4 seconds.
audio: If the audio or sound doesnt work, go to the nearest repair shop to fix it.
Your question reminds me a lot of my learning, so I will try give an answer to expand on your learning with lots of print statements to consider how it works carefully. It's not the most efficient or stable approach but hopefully of some use to you to move forwards.
print "LOADING RAW DATA"
solution_dictionary = {}
with open('solutions.txt', 'r') as infile:
for line in infile:
dict_key, solution = line.split(':')
print "Dictionary 'key' is: ", dict_key
print "Corresponding solution is: ", solution
solution_dictionary[dict_key] = solution.strip('\n')
print '\n'
print 'Final dictionary is:', '\n'
print solution_dictionary
print '\n'
print 'FINISHED LOADING RAW DATA'
solved = False
while not solved: # Will keep looping as long as solved == False
issue = raw_input('What is your problem? ')
solution = solution_dictionary.get(issue)
""" If we can find the 'issue' in the dictionary then 'solution' will have
some kind of value (considered 'True'), otherwise 'None' is returned which
is considered 'False'."""
if solution:
print solution
solved = True
else:
print ("Sorry, no answer found. Valid issues are 'frozen', "
"'screen' 'audio' or 'unresponsive'")
want_to_exit = raw_input('Want to exit? Y or N? ')
if want_to_exit == 'Y':
solved = True
else:
pass
Other points:
- don't use 'file' as a variable name anywhere. It's a python built-in and can cause some weird behaviour that you'll struggle to debug https://docs.python.org/2/library/functions.html
- If you get an error, don't say "crashes", you should provide some form of traceback e.g.:
a = "hello" + 2
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-1-6f5e94f8cf44> in <module>()
----> 1 a = "hello" + 2
TypeError: cannot concatenate 'str' and 'int' objects
your question title will get you down-votes unless you are specific about the problem. "help me do something" is unlikely to get a positive response because the error is ambiguous, there's no sign of Googling the errors (and why the results didn't work) and it's unlikely to be of any help to anyone else in the future.
Best of luck :)
When I change the line "for i in file:" to "for i in read:" everything works well.
To output only the line starting with "screen" just forget the probs variable and change the last for statement to
for line in advice:
if line.startswith( favcol ) :
print line
break
For the startswith() function refer to https://docs.python.org/2/library/stdtypes.html#str.startswith
And: the advices of roganjosh are helpfull. Particularly the one "please don't use python keywords (e.g. file) as variable names". I spent hours of debugging with some bugs like "file = ..." or "dict = ...".

Python Raise Error (to display in shell) , then do rest of the code [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I have a file called dictionary.txt, it contains one word in English, a space and then the Georgian translation for that word in each line.
My task is to raise an error whenever an English word without a corresponding word is found in the dictionary (e.g. if the English word has no translation).
If I raise a ValueError or something like that it stops the code.
Could you provide me with an example(using try if there is no other option).
def extract_word(file_name):
final = open('out_file.txt' ,'w')
uWords = open('untranslated_words.txt', 'w+')
f = open(file_name, 'r')
word = ''
m = []
for line in f:
for i in line:
if not('a'<=i<='z' or 'A' <= i <= 'Z' or i=="'"):
final.write(get_translation(word))
if word == get_translation(word) and word != '' and not(word in m):
m.append(word)
uWords.write(word + '\n')
final.write(get_translation(i))
word=''
else:
word+=i
final.close(), uWords.close()
def get_translation(word):
dictionary = open('dictionary.txt' , 'r')
dictionary.seek(0,0)
for line in dictionary:
for i in range(len(line)):
if line[i] == ' ' and line[:i] == word.lower():
return line[i+1:-1]
dictionary.close()
return word
extract_word('from.txt')
The question is not very clear, but I think you may need this kind of code:
mydict = {}
with open('dictionary.txt') as f:
for i, line in enumerate(f.readlines()):
try:
k, v = line.split()
except ValueError:
print "Warning: Georgian translation not found in line", i
else:
mydict[k] = v
If line.split() doesn't find two values, the unpacking does not take place and a ValueError is raised. We catch the exception and print a simple warning. If no exception is found (the else clause), then the entry is added to the python dictionary.
Note that this won't preserve line ordering in original file.
Raising an error is primarily to allow the program to react or terminate. In your case you should probably just use the Logging API to output a Warning to the Console.
import logging
logging.warning('Failed to find Georgian translation.') # will print a warning to the console.
Will result in the following output:
WARNING:root:Failed to find Georgian translation.
You should probably take a look at this
f = open('dictionary.txt')
s = f.readline()
try:
g = translate(s)
except TranslationError as e:
print "Could not translate" + s
Assuming that translate(word) raises a TranslationError of course.

Categories