Convert Gregorian to Jalali Date in Python: Code Review
This Snippet is coded by a user inOnline python Compiler. You can see and run this code too.
زبان: python
This snippet is an attempt to convert a Gregorian date (year, month, day) into a Jalali (Persian/Shamsi) date in Python, but the logic is incorrect and unusable in practice.
- Wrong input types: year, month and day are read with input() and cast to float, while dates should be integers.
- Ineffective conditionals: expressions such as (month % 12) and (year + 1) are evaluated but never assigned, so the carry-over never happens. Additionally, when month equals 12, month % 12 is 0 (falsy), so year + 1 is short-circuited and never computed.
- Hard-coded offsets: the real conversion is faked with print(year + 621, month + 2, day + 21). These constants only work for a few specific dates and ignore leap years, 30 vs 31-day months and the 29-day Esfand.
- Indentation bug: the print statement sits inside if day >= 30, so nothing is printed for most inputs.
- Typo: the prompt says «enter the dau?» instead of «day».
How to use it: run the file with python script.py and type three numbers; expect wrong or empty output for most dates.
Correct approach: use a ready-made library. After pip install jdatetime you can convert accurately:
import jdatetime
from datetime import date
g = date(2024, 3, 21)
print(jdatetime.date.fromgregorian(date=g))
# output: 1403-01-02
If you prefer no dependency, implement the standard gregorian_to_jalali algorithm with proper leap-year handling.