Exercise #23: 99 Bottles of Beer
# Loop from 99 to 2, displaying the lyrics to each stanza.
for numberOfBottles in range(99, 1, -1):
print(numberOfBottles, 'bottles of beer on the wall,')
print(numberOfBottles, 'bottles of beer,')
print('Take one down,')
print('Pass it around,')
# If there is only one, print "bottle" instead of "bottles".
if (numberOfBottles - 1) == 1:
print('1 bottle of beer on the wall,')
else:
print(numberOfBottles - 1, ' bottles of beer on the wall,')
# The last stanza has singular "bottle" and a different final line:
print('1 bottle of beer on the wall,')
print('1 bottle of beer,')
print('Take one down,')
print('Pass it around,')
print('No more bottles of beer on the wall!')
Exercise #24: Every 15 Minutes
# Loop over am and pm:
for meridiem in ['am', 'pm']:
# Loop over every hour:
for hour in ['12', '1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11']:
# Loop over every 15 minutes:
for minutes in ['00', '15', '30', '45']:
# Print the time:
print(hour + ':' + minutes + ' ' + meridiem)
Exercise #25: Multiplication Table
# Print the heading of each column:
print(' | 1 2 3 4 5 6 7 8 9 10')
print('--+------------------------------')
# Loop over all numbers from 1 to 10:
Python Programming Exercises, Gently Explained
144
for column in range(1, 11):
# Print the number label on the right side:
print(str(column).rjust(2) + '|', end='')
# Loop over all numbers from 1 to 10:
for row in range(1, 11):
# Print the product, padded to two digits, followed by a space:
print(str(column * row).rjust(2) + ' ', end='')
# After the loop, print a newline to end the row:
print()
Dostları ilə paylaş: |