I am making a calculator (using tkinter) and I need to have a limit so if the user enters an input of more than 999, an error message appears and the numbers are not calculated (it is a school project). When I run the script from below, at school it just appears with a blank GUI and on my home computer it says 'unindent does not match any outer indentation level'. How can I solve this?
Thanks
P.S. I am using Python 3.3.2
def calc(self):
try:
self.display.set(self.validate_result(eval(self.display.get())))
self.need_clr = True
except:
showerror('Operation Error', 'Illegal Operation')
self.display.set('')
self.need_clr = False
def validate_result(self, result):
if result >= 1000:
raise ValueError('result too big!')
else:
return result
Python uses indentation to distinguish levels of scope.
Here all your code seems to be entirely indented, so Python thinks all your code is in an inner scope, and tries to find the outer scope that contains it, but there isn't any.
You should try with this indentation :
def calc(self):
try:
...
def calc(self):
try:
...
Edit : also, you seem to have other indentation problems in the second function. You must align except with try, and there is one space missing before if result >= 1000:.
Related
def search():
try:
option=input("\n\nWhta do you want to search by ('A' for account type, 'B' for balance): ")
if option.lower()=='a':
option_2=input("\n\nWhat type of account do you want to view ('C' for current,'S' for savings): ")
if option_2.upper()=="C":
inFile=open("account.dat","rb")
acc_det=pickle.load(inFile)
for x in acc_det:
if x.rettype()=="C":
print("\n\n\tACCOUNT HOLDER LIST\n\n")
print(60*"=")
print("%-10s"%"A/C No.","%-20s"%"Name","%-10s"%"Type","%-6s"%"Balance")
print(60*"=","\n")
x.report()
except EOFError:
print("Enter Valid Statement")
"""*****************************************************************************
THE MAIN FUNCTION OF PROGRAM
*****************************************************************************"""
intro()
while True:
print(3*"\n",60*"=")
print("""MAIN MENU
1. New Account
2. Deposit Amount
3. Withdraw Amount
4. Balance Enquiry
5. All Account Holder List
6. Close An Account
7. Modify An Account
8. Exit
9. Filter Accounts
""")
The code gives an indentation error right after the last triple quote. I can't figure out why, but the error goes away if I remove the "try" clause. Why is this happening ?
Edit : I have edited in the next part of the code, where I call in the main function
In python, after every ":" and newline, there needs to be an indentation of atleast one space or tab character.
In your above program, you have declared a function search(), and have a semi-colon after it, so in the next line, you need to indent the statements inside the function.
So, you will have to indent try: and except: statements, and recursively keep indenting the code blocks present in the try/except clauses
I can see two critical section in regards of indentation:
try: and except EOFError: have the same indentaion as def search():
Your print statements are indented by 8 spaces
maybe here is a problem :
def search():
try:
try this:
def search():
try:
do def search() and try: have same level of indentation?
Im working on a finger exercise from Guttag Intro to computer science and programming using python, and Im working on the following finger exercise:
Finger Exercise: Implement a function that satisfies the specification
def findAnEven(l):
"""Assumes l is a list of integers
Returns the first even number in l
Raises ValueError if l does not contain an even number"""
This is what I wrote so far, it get's the job done, but is definitely not what Guttag intended as an answer.
def isEven(l):
"""Assumes l is a list of integars
returns the first even number in list
raises an exception if no even number in list"""
for i in l:
if i % 2 == 0:
print i, " is the first even number in the list"
exit()
raise ValueError("No even numbers in list!")
I would highly appreciate any input on how professor Guttag intended the code to look. I'm assuming I should have used the try statement somewhere, and the using the exit statement is very crude in this context. Thanks in advance.
The issue with your code is the usage of exit(). Generally return will exit for you. To fix the code, just remove it:
def isEven(l):
for i in l:
if i % 2 == 0:
return i
raise ValueError("No even numbers in list!")
I'm answering this by using the try-except:
def findEven(L):
try:
for num in L:
if num%2==0:
return num
else:
num/0
except:
raise ValueError
To enter the except block, there needs to be an error in the try block. I intently added a Zero division operation in the try block to get it to produce the ZeroDivisionError in case no even number was found. This error allows the exception block to execute. Hope it helps someone else in the same situation.
I am also working on this part. This is my code:
def findEven(L):
try:
for num in L:
if num%2==0:
return num
else:
num/0
except ZeroDivisionError:
print("No even numbers in list!")
except:
raise ValueError("findEven called with bad arguments")
I found that if I didn't use ZeroDivisionError,the IDLE Shell will show ZeroDivisionError first, and then show this line
During handling of the above exception, another exception occurred:
I'm trying to simplify the following:
if x < 0:
print('we don't do negative numbers')
else:
NORMAL CODE HERE
I recently learned of the assert command, and admire its ability to simplify my previous lines into:
assert x > 0, 'errorText'
NORMAL CODE HERE
I don't want errors to give a traceback, though. I only want that single line like the if/else gives.
Is there a way to get an assertionError to return single line like exceptions do, or do I really need to keep running if/else's everywhere?
The assert statement in Python is intended for debugging or for testing. It serves the purpose of halting execution of the program when the condition is not True. When debugging you can include these statements in your code to help track down errors. Then remove them once the bug is fixed. Using assert in production code is a bad idea.
As you have it written using assert, your program will terminate if x is less than zero and the code that follows will not run.
You should continue to use if/else method to provide the two desired code paths. One path to log that x is less than zero, the other path to execute the code in the block NORMAL CODE HERE.
If x should never be less than 0 at this point, and the remaining code must not be executed then you should raise an Exception that can be caught in the calling code.
def method_using_positive_numbers(x):
if x < 0:
raise ValueError("we don't do negative numbers")
NORMAL CODE HERE
Another option is to return from the method if the condition is not true.
def method_using_positive_numbers(x):
if x < 0:
print("we don't do negative numbers")
return
NORMAL CODE HERE
password = raw_input("Enter password: ")
if password == "1234":
print "You logged in correctly!"
else:
print "GTFO"
Though i give different indentations the code is working fine i'm unable to figure it out.
it will not be flagged as as IndentationError, sine any block of statement has to have at lease 1 space of indent
here your if and else are two different blocks, so it was indented anyway so the interpreter throws no error
if True:
print
elif True:
print
elif True:
print
elif True:
print
else:
print
This will work without any problem
But if I try the following I will get IndendationError
if True:
print ""
print "" # has different Indentation
print ""
The Python documentation explains indentation. Here's a relevant excerpt:
At the beginning of each logical line, the line’s indentation level is
compared to the top of the stack. If it is equal, nothing happens. If
it is larger, it is pushed on the stack, and one INDENT token is
generated. If it is smaller, it must be one of the numbers occurring
on the stack
In your code, since the indentation level is larger than the top of the stack (which is 0), it is treated as a single indent. The else: line popped 2 off of the top of the stack, so the interpreter has no memory of your previous indentation level of 2. It only knows that it's higher than the 0.
Problems arise when you start mixing indentation within a block:
def foo():
if True:
return True
return False # Is this part of the if statement or not?
When the parser reaches return False, the stack contains [4, 8]. The next line has an indent of 6, which is not contained in the stack and therefore generates an IndentationError.
Can someone explain why I am getting an invalid syntax error from Python's interpreter while formulating this simple if/else statement? I don't add any tabs myself I simply type the text then press enter after typing. When I type an enter after "else:" I get the error. else is highlighted by the interpreter. What's wrong?
>>> if 3 > 0:
print("3 greater than 0")
else:
SyntaxError: invalid syntax
Python does not allow empty blocks, unlike many other languages (since it doesn't use braces to indicate a block). The pass keyword must be used any time you want to have an empty block (including in if/else statements and methods).
For example,
if 3 > 0:
print('3 greater then 0')
else:
pass
Or an empty method:
def doNothing():
pass
That's because your else part is empty and also not properly indented with the if.
if 3 > 0:
print "voila"
else:
pass
In python pass is equivalent to {} used in other languages like C.
The else block needs to be at the same indent level as the if:
if 3 > 0:
print('3 greater then 0')
else:
print('3 less than or equal to 0')
The keyword else has to be indented with respect to the if statement respectively
e.g.
a = 2
if a == 2:
print "a=%d", % a
else:
print "mismatched"
The problem is indent only.
You are using IDLE. When you press enter after first print statement indent of else is same as print by default, which is not OK. You need to go to start of else sentence and press back once. Check in attached image what I mean.
it is a obvious mistake we do, when we press enter after the if statement it will come into that intendation,try by keeping the else statement as straight with the if statement.it is a common typographical error
Else needs to be vertically aligned. Identation is playing a key role in Python. I was getting the same syntax error while using else. Make sure you indent your code properly