Because of a special sale that has just started if the price of the item is

# Because of a special sale that has just started if

• Notes
• 50

This preview shows page 14 - 21 out of 50 pages.

Because of a special sale that has just started, if the price of the item is greater than 100 dollars, the customer receives a 10% discount. The program will then print out the final price of the item. The program must make a decision before it can make the proper calculation. The decision is based on the price of the item. WRITING THE CODE
IF EXAMPLE 2-1 price = 150.00 discount = .1 if price > 100: finalPrice = price - (price*discount) else: finalPrice = price print('Your final price is ' + str(finalPrice)) Your final price is 135.0 results in Because the value of price is greater than 100, the code contained in the if block is executed The str() function converts the number to a string.
IF EXAMPLE 2-2 price = 90.00 discount = .1 if price > 100: finalPrice = price - (price*discount) else: finalPrice = price print('Your final price is ' + str(finalPrice)) Your final price is 90.0 results in Because the value of price is not greater than 100, the code contained in the else block is executed The str() function converts the number to a string.
You can create code than can make decisions based on multiple conditions by using elif statements. This could also be done using nested if statements. Lets continue with the 10% discount problem in the last example. But in this cause, in order to obtain the 10% discount the customer must buy an item that is greater than 100 dollars and the customer must pay in cash. We will also add some complexity to the code by providing more useful messages to the customer and formatting the final price as currency. ELIF STATEMENTS
ELIF EXAMPLE 3-1 price = 150.00 discount = .1 paymentType = 'cash' if price <= 100: finalPrice = '\${0:.2f}'.format(price) message = 'Your item price must be greater than 100 dollars to get a discount.' elif paymentType == 'cash': finalPrice = '\${0:.2f}'.format(price - (price * discount)) message = 'Congratulations, you get a discount!' else: finalPrice = '\${0:.2f}'.format(price) message = 'You must pay cash to get a discount.' print(message + ' Your final price is ' + str(finalPrice) + '.') Congratulations, you get a discount! Your final price is \$135.00. results in