I’m a noob a coding on VS Studio Code. So basically, I’m wondering why I can’t add the ‘or’ boolean in this code on, like line 17. I get the expected expression error by pylance. Why?
def fair(employee, ceo, ratio):
“”"Decide whether the ratio of CEO to employee pay is fair.
Parameters:
employee: average employee pay
ceo: CEO pay
ratio: the fair ratio
Return:
a Boolean indicating whether ceo / employee is fair
Precondition: employee is a float or integer that is > 0 ceo is a float or integer that is >= 0 ratio is a float or integer that is >= 0 and <= 0
Postcondition: returns a boolean statement- True or False dependent whether or not (ceo / employee) <= ratio
"""
assert isinstance(employee, float) , 'n should be a float or a integer' or assert isinstance(employee, int) , 'n should be a float or an integer'
assert employee > 0, 'employee is not an indentured servant'
assert(ceo, float or int), 'ceo is getting paid $ dumbass'
assert(ratio, float or int), 'What ratio is not a fraction/decimal or integer?'
return (ceo / employee) <= ratio
from your post description and referencing your script, I think that you are referring to these two lines:
assert isinstance(employee, float) # , 'n should be a float or a integer' or assert
isinstance(employee, int) # , 'n should be a float or an integer'
You can do as you have done for both ceo and ratio variables in your script. Alternatively, instead of using the or for checking two assertions, you may use the comma (,), as in:
# These two lines are equivalent:
assert isinstance(employee, int or float)
assert isinstance(employee, float), isinstance(employee, int) # equivalent to using `or` in theory
int or float evaluates to int because int is truthy, so:
assert isinstance(employee, int or float)
is the same as:
assert isinstance(employee, int)
The assert statement evaluates the first expression and raises AssertionError if it’s false, using the value of the second expression, if present, so in:
Since you are purposefully asserting an exception based on the outcome of an isinstance test, you can couple it with a try / except pair to catch the exception. It would help if you tested each case individually to know the source of the exception as opposed to multiple cases tested together where you wouldn’t.
In the following test script, each test case is tested along with a try / except pair. If a test case fails, the exception is caught and a corresponding print statement is generated to alert the source of the exception.
from colorama import Fore
employee = 4.561 # Test variable
try:
assert isinstance(employee, float) # test if type 'float'
except AssertionError:
print(Fore.RED + f"'employee' value {employee} is not a type float.")
try:
assert isinstance(employee, int) # test if type 'int'
except AssertionError:
print(Fore.RED + f"'employee' value {employee} is not a type int.")