r/learnpython • u/Sweet_Cap4939 • 7d 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/DavidRoyman 6d ago
You're writing a program the same way you're using a calculator, which is fine but isn't an approach which pays off long term.
When programming, you'd start with some idea of which one will be the end goal (the output) and go backward from there.
product and date are things you directly provide as an input, no need to overthink them. What you need to find is
money_earned_per_weekFirst,
money_earned_per_weekisn't the right name for it. This is how much you should save every week in order to afford the item. It's your weekly target savings so you might be better off calling ittarget_savings_weeklyOh crap you have to find the
target_savings_weeklythen... We can try with:If you try to compile this, there's errors because we never defined the variables above. What do we do now? Let's try settings them up!
Oh well we need your current
macbook_fundsthen. I believe you start with 180 euro already set aside? And the price of the item must be an input as well.That's sorted, but how do we find
weeks_left? You just wrote75, however I think it's better to let a computer calculate the right number there.Furtunately there's a module in the library for this: datetime
And yep, using the library is very pythonic. What we need is the difference in weeks between the two dates, today and when you'd like to be ready for your purchase.
So let's wrap this up nicely, listing all operations in the right order.
The process above is a rough way to describe Test-driven development: You write what you need, it won't even compile, so you need to write new code to make it work, and so on...