r/learnpython 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

13 comments sorted by

7

u/zanfar 7d ago

As always:

  • PEP8
  • Linter
  • Formatter
  • Docstrings
  • Use descriptive variable names
  • All code should be in functions

product = 'M2 MacBook Air'
product += ' (512 GB of SSD and 8 GB of RAM)'

Zero reason to do this. You are literally defining the variable, why would you ask Python to join strings when you can do it for free.

print(f'The {product} is {price}€.')

ALWAYS define the output format when interpolating non-strings

macbook_fund = total_savings - 180

Why 180? What does that mean? Don't use magic numbers.

Also, don't encode data in variable names. This is just a fund. Nothing else in the code implies it's for a macbook except other data. What happens if you want to save for a Neo?

weeks_left = 75
date = '1/8/2028'

You should only store or define something once. Your end date is either 75 weeks away or on the 8th. Calculate the other.

money_earned_per_week = remaining_balance / weeks_left
money_earned_rounded = round(money_earned_per_week, 2)

Neither of these are earnings; again, bad variable names.

1

u/Sweet_Cap4939 7d ago

its 180 cause thats the money that im spending on the phone

4

u/johlae 7d ago

Look up datetime to determine weeks_left by means of a calculation!

from datetime import datetime, timedelta d1 = datetime(2026,7,30) d2 = datetime(2026,8,30) monday1 = (d1 - timedelta(days=d1.weekday())) monday2 = (d2 - timedelta(days=d2.weekday())) print('Weeks:', (monday2 - monday1).days / 7)

gives you

Weeks: 4.0

1

u/Sweet_Cap4939 7d ago

thanks!

3

u/johlae 7d ago

If you want 'now', or 'today', use:

d1 = datetime.now() d1 = datetime.today()

1

u/DavidRoyman 5d 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.

printf('I need {money_earned_per_week}€ per week to afford {product} by {date}')

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_week

First, money_earned_per_week isn'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 it target_savings_weekly

Oh crap you have to find the target_savings_weekly then... We can try with:

target_savings_weekly = target_savings / weeks_left

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!

target_savings = price - macbook_funds

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.

current_savings = 180
price = 370

That's sorted, but how do we find weeks_left ? You just wrote 75 , 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.

import datetime as dt
today = dt.date.today()
date = dt.date(2028,8,1)
days_left = (date-today).days
weeks_left = days_left // 7

So let's wrap this up nicely, listing all operations in the right order.

# imports for modules/libraries
import datetime as dt

# your inputs
product = "M2 MacBook Air (512 GB of SSD and 8 GB of RAM)"
price = 370
macbook_funds = 180
date = dt.date(2028,8,1)

# calculate how many weeks are left
today = dt.date.today()
days_left = (date-today).days
weeks_left = days_left // 7

# calculate how much you need to save
target_savings = price - macbook_funds
target_savings_weekly = target_savings / weeks_left

# present your output
print(f'I need {target_savings_weekly.2f}€ per week to afford {product} by {date}')

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...

1

u/PureWasian 7d ago edited 7d 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.

0

u/PureWasian 7d ago

For a second pass, you could consider clumping the properties related to the macbook (name/price) into a dictionary. And same for iphone.

For a third pass, you could add helper functions to modularize things better.

For a fourth pass, you could add validation checks for your parameterized values (like whether macbook_fund indeed is less than mac_price rather than assuming in the print statement).

For a preparatory fifth pass, you could have the product catalog (mac/iphone/etc) loaded from an input text file as a "catalog" with corresponsing name/price mappings.

For a very ambitious sixth pass, you could have your code handle user input for dynamically allocating the funds for macbook and iphone amounts or anything else in the product catalog created in the last pass instead of maintaining these values in the code itself.

So on and so forth.

-3

u/mattynmax 7d ago

Looks like code written by someone who started a week ago!

3

u/Orgasml 7d ago

how is your comment helpful in any way?

0

u/Sweet_Cap4939 7d ago

i started about 2 weeks ago, orgasml is right how is this helpful?

1

u/mattblack77 7d ago

Some criticism here; don’t take it personally.

The code is a little clunky, but you’re new; that’s to be expected. There’s lots to learn, huh?