In: Computer Science
Please attach the output screenshots, narrative descriptions, or paste the Python codes when requested.
Task 2
We are producing two types of products, product A and product B. Product A is defective if the weight is greater than 10 lbs. Product B is defective if the weight is greater than 15 lbs. For a given product, we know its product_type and its weight. Design a program to screen out defective products. Starting the program with variable definition:
product_type = 'xxx'
weight = xxx
Hint: You need to figure out the product type first, and then check if the product is defective based on the weight. You may use a nested if statement like the following:
if product is A:
if product weight > 10:
the product is defective
else:
if product weight >15:
the product is defective
But you need to translate the English into Python codes.
As a challenge, you may also try a one-step if statement. such as :
if some condition is met:
the product is defective
else:
the product is normal
And the key is the bolded “some condition”.
Answer:
Approach 1:
Program:
product_type = input("Enter the product type (A or B): ") #
taking product type from the keyboard (a string value)
weight = float(input("Enter the weight of the product: ")) # taking
weight from the keyboard (string value is converted to float)
if product_type is 'A' : # if 'product_type' is 'A'
if weight > 10: # if weight is greater than 10
print("The product is defective") # prints "product is
defective"
else: # if weight is less than or equal to 10
print("The product is normal") # prints "product is normal"
elif product_type is 'B': # if 'product_type' is 'B'
if weight > 15: # if weight is greater than 15
print("The product is defective") # prints "product is
defective"
else: # if weight is less than or equal to 15
print("Product is normal") # prints "product is normal"
Program
screenshot:
Output:
Approach 2:
Program:
product_type = input("Enter the product type (A or B): ") #
taking product type from the keyboard (a string value)
weight = float(input("Enter the weight of the product: ")) # taking
weight from the keyboard (string value is converted to float)
# if the product_type is 'A' and weight > 10 or if the
product_type is 'B' and weight > 15
if ((product_type is 'A') and (weight > 10)) or ((product_type
is 'B') and (weight > 15)) :
print("The product is defective") # prints "product is
defective"
else: # if the product_type is 'A' and weight <= 10 or if the
product_type is 'B' and weight <= 15
print("The product is normal") # prints "product is normal"
Program screenshot:
Output: