#!/usr/bin/env python3
#=====================================================================================
# Catching exceptions
#=====================================================================================
print("Content-Type: text/html \n")     #http header with newline char (required for web)

print('<pre>')                          #to produce better display on the web 

name   = 'Sam'
number = 123

try:
    if name:                            #does the variable exist and has a value other than  
        print('variable name exists')                
except:
    print('variable name does not exist')

try:
    if name2:                            #does the variable exist and has a value other than  
        print('variable name2 exists')                
except:
    print('variable name2 does not exist')

print()


try:
    x = name / number                           #attempting to divide name by number  
except:
    print('Invalid Operation')

print()



try:
    qty_desired = input("Enter quantity desired: ")		    #if the user enters a string
    quantity    = int(qty_desired)				            #this might cause an exception
    print(F"You entered a quantity of {quantity}")		    
except:
    print("Invalid input, substituting quantity of 1")		#print an error message
    quantity = 1						                    #fix the data
    print(F"Substituting quantity of {quantity}")		    
print("Thank you for your order")                           #continue processing
print()


try:
    qty_desired = input("Enter quantity desired: ")		    #if the user enters a string
    quantity    = int(qty_desired)				            #this might cause an exception
    print(F"You entered a quantity of {quantity}")		    
except Exception as e:
    print( F"Invalid input, {e} - substituting 1")		    #print Python error message
    quantity = 1						                    #fix the entered data
    print(F"Substituting quantity of {quantity}")		    
print("Thank you for your order")                           #continue processing
print()


try:
    qty_desired = input("Enter quantity desired: ")		    #if the user enters a string
    quantity    = int(qty_desired)				            #this might cause an exception
    print(F"You entered a quantity of {quantity}")		    
except ValueError as e:
    print( F"Invalid input, {e} - substituting 1")		    #print Python error message
    quantity = 1						                    #fix the entered quantity
    print(F"Substituting quantity of {quantity}")		    
except Exception as e:
    print( F"Unknown error {e} - exiting program")		    #print generic Python error message
    exit()                                                  #exit the program                                              
print("Thank you for your order")                           #continue processing
print()