try and except:
In Python, "try" and "except" are used for error handling. The primary purpose is to make your programs more robust by preventing them from crashing when unexpected errors occur. Instead of abruptly terminating, your program can gracefully handle errors and continue running.
- try & except:
# show the results for non-errors only
x = [1, 'Jack', 5, 'hello', 3]
for i, item in enumerate(x):
try:
result = item ** 2
print(result)
except TypeError:
pass # 1
# 25
# 9
# show the results for errors only
for i, item in enumerate(x):
try:
result = item ** 2
#print(result)
except TypeError:
print(f"{i}: {item} is not a number") # 1: Jack is not a number
# 3: hello is not a number
# using "else" and "finally"
try:
result = 10 / 0 # This will cause a ZeroDivisionError
except ZeroDivisionError:
print("Error: Division by zero is not allowed.")
else:
print("This will print if there is no error.")
finally:
print("This will always execute.")
rawstr = input("Enter a number: ")
try:
ival = int(rawstr)
except:
ival = -1
if ival > 0:
print("Nice work!")
else:
print("Not a number!")
# calculating the salary
while True:
hours = input("Enter Hours: ")
try:
hours = float(hours)
break
except ValueError:
print('"{}" is not a number. Try again'.format(hours))
# .format(hours) part takes the value of the hours variable (the invalid input the user entered) and inserts it into the curly braces {} within the string:
while True:
rate = input("Enter Rate: ")
try:
rate = float(rate)
break
except ValueError:
print('"{}" is not a number. Try again'.format(rate))
if hours <= 40:
pay = hours * rate
else:
base = 40 * rate
overtime = (hours - 40) * (rate * 1.5)
pay = base + overtime
print(pay)