Exercise #18: Buy 8 Get 1 Free def getCostOfCoffee(numberOfCoffees, pricePerCoffee):
# Track the total price: totalPrice = 0
# Track how many coffees we have until we get a free one: cupsUntilFreeCoffee = 8
# Loop until the number of coffees to buy reaches 0: while numberOfCoffees > 0:
# Decrement the number of coffees left to buy: numberOfCoffees -= 1
# If this cup of coffee is free, reset the number to buy until # a free cup back to 8: if cupsUntilFreeCoffee == 0:
Python Programming Exercises, Gently Explained
141
cupsUntilFreeCoffee = 8
# Otherwise, pay for a cup of coffee: else:
# Increase the total price: totalPrice += pricePerCoffee
# Decrement the coffees left until we get a free coffee: cupsUntilFreeCoffee -= 1
# Return the total price: return totalPrice
Alternate Solution:
def getCostOfCoffee(numberOfCoffees, pricePerCoffee):
# Calculate the number of free coffees we get in this order: numberOfFreeCoffees = numberOfCoffees // 9
# Calculate the number of coffees we will have to pay for in this order: numberOfPaidCoffees = numberOfCoffees - numberOfFreeCoffees
# Calculate and return the price: return numberOfPaidCoffees * pricePerCoffee
Exercise #19: Password Generator # Import the random module for its randint() function. import random
# Create string constants that for each type of character: LOWER_LETTERS = 'abcdefghijklmnopqrstuvwxyz'
UPPER_LETTERS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
NUMBERS = '1234567890'
SPECIAL = '~!@#$%^&*()_+'
# Create a string with all of these strings combined: ALL_CHARS = LOWER_LETTERS + UPPER_LETTERS + NUMBERS + SPECIAL
def generatePassword(length):
# 12 is the minimum length for passwords: if length < 12:
length = 12
# Create a password variable that starts as an empty list: password = []
# Add a random character from the lowercase, uppercase, digits, and # punctuation character strings: password.append(LOWER_LETTERS[random.randint(0, 25)])
password.append(UPPER_LETTERS[random.randint(0, 25)])
password.append(NUMBERS[random.randint(0, 9)])
password.append(SPECIAL[random.randint(0, 12)])
# Keep adding random characters from the combined string until the # password meets the length: while len(password) < length:
password.append(ALL_CHARS[random.randint(0, 74)])
# Randomly shuffle the password list:
Python Programming Exercises, Gently Explained
142
random.shuffle(password)
# Join all the strings in the password list into one string to return: return ''.join(password)