P ython p rogramming e xercises



Yüklə 1,51 Mb.
Pdf görüntüsü
səhifə110/124
tarix14.05.2023
ölçüsü1,51 Mb.
#113537
1   ...   106   107   108   109   110   111   112   113   ...   124
PythonProgrammingExercisesGentlyExplained

Exercise #5: Fizz Buzz 
def fizzBuzz(upTo): 
# Loop from 1 up to (and including) the upTo parameter: 
for number in range(1, upTo + 1): 
# If the loop number is divisible by 3 and 5, print 'FizzBuzz': 
if number % 3 == 0 and number % 5 == 0: 
print('FizzBuzz', end=' ') 
# Otherwise the loop number is divisible by only 3, print 'Fizz': 
elif number % 3 == 0: 
print('Fizz', end=' ') 
# Otherwise the loop number is divisible by only 5, print 'Buzz': 
elif number % 5 == 0: 
print('Buzz', end=' ') 
# Otherwise, print the loop number: 
else: 
print(number, end=' ') 
Exercise #6: Ordinal Suffix 
def ordinalSuffix(number): 
numberStr = str(number) 
# 11, 12, and 13 have the suffix th: 
if numberStr[-2:] in ('11', '12', '13'): 
return numberStr + 'th' 
# Numbers that end with 1 have the suffix st: 
if numberStr[-1] == '1': 
return numberStr + 'st' 
# Numbers that end with 2 have the suffix nd: 
if numberStr[-1] == '2': 
return numberStr + 'nd' 
# Numbers that end with 3 have the suffix rd: 
if numberStr[-1] == '3': 
return numberStr + 'rd' 
# All other numbers end with th: 
return numberStr + 'th' 


Python Programming Exercises, Gently Explained 
136 
Alternate Solution: 
def ordinalSuffix(number): 
# 11, 12, and 13 have the suffix th: 
if number % 100 in (11, 12, 13): 
return str(number) + 'th' 
# Numbers that end with 1 have the suffix st: 
if number % 10 == 1: 
return str(number) + 'st' 
# Numbers that end with 2 have the suffix nd: 
if number % 10 == 2: 
return str(number) + 'nd' 
# Numbers that end with 3 have the suffix rd: 
if number % 10 == 3: 
return str(number) + 'rd' 
# All other numbers end with th: 
return str(number) + 'th' 

Yüklə 1,51 Mb.

Dostları ilə paylaş:
1   ...   106   107   108   109   110   111   112   113   ...   124




Verilənlər bazası müəlliflik hüququ ilə müdafiə olunur ©azkurs.org 2024
rəhbərliyinə müraciət

gir | qeydiyyatdan keç
    Ana səhifə


yükləyin