I noticed that when i posted programs on here people gave me their versions, and had

import *

def somethng_here():
    while True:
        Try:
            pass
    except ValueError #or some other types of things liek that

I don't understand how a function can be FALSE, as well as how these except errors...if you will, work. Can someone explain or link me to a clear tutorial :)

Dani AI

Generated

Quick summary and where the thread is headed — exceptions are runtime “signals” Python raises when something goes wrong (division by zero, bad conversions, missing names, etc.). Use try/except to catch those signals and handle them instead of letting the interpreter print a traceback and exit. ’s walkthrough is a good start; for a concise conceptual reference see Real Python’s exception glossary. (realpython.com)

Practical rules and a small pattern to follow: catch the specific exception(s) you expect, not everything. Avoid a bare except: because it will also catch system‑level interrupts; prefer except ValueError:, except ZeroDivisionError:, or, when you need a catch‑all for application errors, except Exception as e: and then decide whether to handle, log, or re‑raise. Use else for code that should run only when no exception happened and finally for cleanup. Example pattern (Python 3):

def parse_and_divide(a_str, b_str):
    a = float(a_str)
    b = float(b_str)
    return a / b

try:
    result = parse_and_divide(user_a, user_b)
except ValueError as e:
    print("Bad number:", e)
except ZeroDivisionError:
    print("Cannot divide by zero")
except Exception as e:
    # unexpected — log and re-raise so bugs aren't hidden
    import traceback; traceback.print_exc()
    raise
else:
    print("Result:", result)
finally:
    # cleanup if needed
    pass

For why bare except is discouraged and how linters/PEPs treat it, see the discussion in the linting docs. (pylint.pycqa.org)

A note on input and Python versions: Python 2’s input() evaluated user text (unsafe); Python 3’s input() always returns a string and you must convert it (e.g., float() or int()), which avoids the evaluation pitfall. ’s reminder about Py2/Py3 differences is important when reading older examples. (docs.python.org)

Short troubleshooting checklist (ties back to the original question from ): functions aren’t “false” unless they return False (or a falsy value); exceptions interrupt flow — handle them or let them propagate; add logging/tracebacks for unexpected errors; write small tests for edge cases and prefer explicit exception handling over silent catches. ’s nudge to make a tutorial was right — these patterns are stable and worth practicing.

Recommended Answers

All 5 Replies

What Is an Exception?

Python uses exception objects.
When it encounters an error, it raises an exception.
If such an exception object is not handled (or caught), the program
terminates with a so-called traceback (an error message)

>>> b

Traceback (most recent call last):
  File "<pyshell#8>", line 1, in <module>
    b
NameError: name 'b' is not defined
>>>
import exceptions
>>> dir(exceptions)
<list method in exception class>

So let try it out. Version 1

x = input('Enter the first number: ')
y = input('Enter the second number: ')
print x/y 
'''
Enter the first number: 10
Enter the second number: 5
2
'''

Work just fine. Version 2

x = input('Enter the first number: ')
y = input('Enter the second number: ')
print x/y
'''
Enter the first number: 10
Enter the second number: 0
Traceback (most recent call last):
  File "E:\1py\Div\dffddd.py", line 3, in <module>
    print x/y
ZeroDivisionError: integer division or modulo by zero
'''

Here we got an problem,user did divided 10/0.
So what to do now?
We have to catch that exceptions.
You do this with the try/except statement. Version 3

try:
    x = input('Enter the first number: ')
    y = input('Enter the second number: ')
    print x/y
except ZeroDivisionError:
    print "Dont divid by zero!"
'''
Enter the first number: 10
Enter the second number: 0
Dont divid by zero!
'''

Look we used ZeroDivisionError from error message,and now we dont get and error message.
A new problem now the program exit after the print statement.
we have to use a loop. Version 4

while True:    
    try:        
        x = input('Enter the first number: ')
        y = input('Enter the second number: ')
        print x/y
        break  #we break out when no problem
    except ZeroDivisionError:
        print "Dont divid by zero,try again"
'''
Enter the first number: 10
Enter the second number: 0
Dont divid by zero,try again
Enter the first number: 10
Enter the second number: 5
2
'''

Work just fine.

So a user that are not so bright or let say a type error.
Hi/she type a as first number.
Enter the first number: a Version 5

while True:    
    try:        
        x = input('Enter the first number: ')
        y = input('Enter the second number: ')
        print x/y
        break  #we break out when no problem
    except ZeroDivisionError:
        print "Dont divid by zero,try again"
'''
Enter the first number: a
Traceback (most recent call last):
  File "E:\1py\Div\hjj.py", line 3, in <module>
    x = input('Enter the first number: ')
  File "<string>", line 0, in <module>
NameError: name 'a' is not defined
'''

Now a new error to catch(NameError)
Now just place it behind ZeroDivisionError. Version 5

while True:    
    try:        
        x = input('Enter the first number: ')
        y = input('Enter the second number: ')
        print x/y
        break  #we break out when no problem
    except (ZeroDivisionError,NameError):
        print "Your input was wrong,try again"
'''
Enter the first number: a
Your input was wrong,try again
Enter the first number: 10
Enter the second number: 5
2
'''

Works just fine.

So they last one, we make fuction with a new error that i catch.
And fix divided with float so it calulate correct.
And a new output %.2f (means float 2 decimal number after .) Version 6

def num_divid():
    '''Function to divided two number'''
    while True:    
        try:        
            x = float(input('Enter the first number: '))
            y = float(input('Enter the second number: '))
            return '%s divided by %s is %.2f ' % (x, y, x/y)           
        except (ZeroDivisionError,NameError,SyntaxError):
            print "Your input was wrong,try again"            

print num_divid()
'''
Enter the first number: 10.7
Enter the second number: 5.478
10.7 divided by 5.478 is 1.95 
'''

More on this.
http://docs.python.org/tutorial/errors.html

ooh thats so cool, one question. where can i get a list of all the error exceptions and what they do because this can come in handy a lot to me.

http://docs.python.org/library/exceptions.html

Use python shell as postet on top.

>>> import exceptions
>>> dir(exceptions)
['ArithmeticError', 'AssertionError', 'AttributeError', 'BaseException', 'BufferError', 'BytesWarning', 'DeprecationWarning', 'EOFError', 'EnvironmentError', 'Exception', 'FloatingPointError', 'FutureWarning', 'GeneratorExit', 'IOError', 'ImportError', 'ImportWarning', 'IndentationError', 'IndexError', 'KeyError', 'KeyboardInterrupt', 'LookupError', 'MemoryError', 'NameError', 'NotImplementedError', 'OSError', 'OverflowError', 'PendingDeprecationWarning', 'ReferenceError', 'RuntimeError', 'RuntimeWarning', 'StandardError', 'StopIteration', 'SyntaxError', 'SyntaxWarning', 'SystemError', 'SystemExit', 'TabError', 'TypeError', 'UnboundLocalError', 'UnicodeDecodeError', 'UnicodeEncodeError', 'UnicodeError', 'UnicodeTranslateError', 'UnicodeWarning', 'UserWarning', 'ValueError', 'Warning', 'WindowsError', 'ZeroDivisionError', '__doc__', '__name__', '__package__']
>>>

snippsat, you should post that as a tutorial :)

Be aware that there are a number of differences between Python2 and Python3 versions.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.