P ython p rogramming e xercises



Yüklə 1,51 Mb.
Pdf görüntüsü
səhifə116/124
tarix14.05.2023
ölçüsü1,51 Mb.
#113537
1   ...   112   113   114   115   116   117   118   119   ...   124
PythonProgrammingExercisesGentlyExplained

Exercise #20: Leap Year 
def isLeapYear(year): 
# Years divisible by 400 are leap years: 
if year % 400 == 0: 
return True 
# Otherwise, years divisible by 100 are not leap years: 
elif year % 100 == 0: 
return False 
# Otherwise, years divisible by 4 are leap years: 
elif year % 4 == 0: 
return True 
# Otherwise, every other year is not a leap year: 
else: 
return False 
Exercise #21: Validate Date 
# Import the leapyear module for its isLeapYear() function: 
import leapyear 
def isValidDate(year, month, day): 
# If month is outside the bounds of 1 to 12, return False: 
if not (1 <= month <= 12): 
return False 
# If the year is a leap year and the date is Feb 29th, it is valid: 
if leapyear.isLeapYear(year) and month == 2 and day == 29: 
return True 
# Check for invalid dates in 31-day months: 
if month in (1, 3, 5, 7, 8, 10, 12) and not (1 <= day <= 31): 
return False 
# Check for invalid dates in 30-day months: 
elif month in (4, 6, 9, 11) and not (1 <= day <= 30): 
return False 
# Check for invalid dates in February: 
elif month == 2 and not (1 <= day <= 28): 
return False 
# Date passes all checks and is valid, so return True: 
return True 
Exercise #22: Rock, Paper, Scissors 
def rpsWinner(move1, move2): 
# Check all six possible combinations with a winner and return it: 
if move1 == 'rock' and move2 == 'paper': 
return 'player two' 


Python Programming Exercises, Gently Explained 
143 
elif move1 == 'rock' and move2 == 'scissors': 
return 'player one' 
elif move1 == 'paper' and move2 == 'scissors': 
return 'player two' 
elif move1 == 'paper' and move2 == 'rock': 
return 'player one' 
elif move1 == 'scissors' and move2 == 'rock': 
return 'player two' 
elif move1 == 'scissors' and move2 == 'paper': 
return 'player one' 
# For all other combinations, it is a tie: 
else: 
return 'tie' 

Yüklə 1,51 Mb.

Dostları ilə paylaş:
1   ...   112   113   114   115   116   117   118   119   ...   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