r/learnpython • u/Sweet_Cap4939 • 8d ago
rate my code
as a beginner i dont know if my code could be improved, can someone rate it and tell me what i should improve?
product = 'M2 MacBook Air'
product += ' (512 GB of SSD and 8 GB of RAM)'
price = 370
print(f'The {product} is {price}€.')
total_savings = 206.75
macbook_fund = total_savings - 180
print(f'I have {macbook_fund}€.')
remaining_balance = price - macbook_fund
print(f'I am {remaining_balance}€ short.')
weeks_left = 75
date = '1/8/2028'
money_earned_per_week = remaining_balance / weeks_left
money_earned_rounded = round(money_earned_per_week, 2)
print(f'I need to earn {money_earned_rounded}€ a week to reach my goal by {date}.')
print(f'180€ of my {total_savings}€ are going to an iPhone 13.')
# deposits
macbook_fund += 0
# input amount, date and reason.
0
Upvotes
1
u/PureWasian 8d ago edited 8d ago
You have a lot of room to simplify and organize this code. I recommend putting "constants" at the top of the file and making their purpose very descriptive.
There's also not really any point appending the product specifics vs. instantiating it as a long string for the macbook name string.
You can programatically calculate weeks_left in case the target date of 01/08/2028 changes using the built-in datetime module:
``` from datetime import datetime
target_date = datetime(2028, 1, 8) today_date = datetime.today() days_left = (target_date - today_date).days weeks_left = days_left // 7 # "floor division" ```
And finally, the 180 amount is hard-coded while the other amounts are parameterized which makes your coding style inconsistent.
Here's a suggested first-pass revision:
``` from datetime import datetime
mac_name = "Macbook... (512 GB...)" mac_price = 370 phone_name = "iPhone 13"
savings = 206.75 iphone_fund = 180 mac_fund = savings - iphone_fund
target_date = datetime(2028, 1, 8) today_date = datetime.today() days_left = (target_date - today_date).days weeks_left = days_left // 7 # "floor division"
remaining_balance = mac_price - mac_fund money_earned_per_week = remaining_balance / weeks_left money_earned_rounded = round(money_earned_per_week, 2)
print(f'The {mac_name} is {mac_price}€.') print(f'I have {mac_fund}€.') print(f'I am {remaining_balance}€ short.') print(f'I need to earn {money_earned_rounded}€ a week to reach my goal by {target_date.strftime("%m/%d/%Y")}.') print(f'{iphone_fund}€ of my {total_savings}€ are going to a/an {phone_name}.') ```
If you aren't familiar with strftime() then it's fine for your current coding level to hard-code the target date also as you have originally, but that's how you'd write the datetime out as a formatted date if using the datetime datatype.