In questo programma imparerai a verificare se un anno è bisestile o meno. Useremo annidato if … else per risolvere questo problema.
Per comprendere questo esempio, dovresti avere la conoscenza dei seguenti argomenti di programmazione Python:
- Operatori Python
- Istruzione Python if … else
Un anno bisestile è esattamente divisibile per 4 ad eccezione degli anni del secolo (anni che terminano con 00). L'anno del secolo è un anno bisestile solo se è perfettamente divisibile per 400. Ad esempio,
Il 2017 non è un anno bisestile Il 1900 non è un anno bisestile Il 2012 è un anno bisestile Il 2000 è un anno bisestile
Codice sorgente
# Python program to check if year is a leap year or not year = 2000 # To get year (integer input) from the user # year = int(input("Enter a year: ")) if (year % 4) == 0: if (year % 100) == 0: if (year % 400) == 0: print("(0) is a leap year".format(year)) else: print("(0) is not a leap year".format(year)) else: print("(0) is a leap year".format(year)) else: print("(0) is not a leap year".format(year))
Produzione
Il 2000 è un anno bisestile
È possibile modificare il valore dell'anno nel codice sorgente ed eseguirlo di nuovo per testare questo programma.