python - corrected and improved code