Python Tutorial: Calculate Number of Days, Weeks, or Months to Reach Specific Goals
25:07

Python Tutorial: Calculate Number of Days, Weeks, or Months to Reach Specific Goals

Corey Schafer 18.01.2018 74 844 просмотров 1 257 лайков

Machine-readable: Markdown · JSON API · Site index

Поделиться Telegram VK Бот
Транскрипт Скачать .md
Анализ с AI
Описание видео
In this Python Programming Tutorial, we will be writing three different scripts to estimate how long it will take to reach certain goals. Our first script will calculate how many months it will take us to pay off a credit card. Our second script will calculate how many weeks it will take to lose a certain amount of weight. And our third script will estimate how long it will take to reach a certain number of subscribers. Let's get started... The code from this video can be found at: https://github.com/CoreyMSchafer/code_snippets/tree/master/Python-Future-Date Python Datetime Tutorial: https://youtu.be/eirjjyP2qcQ ✅ Support My Channel Through Patreon: https://www.patreon.com/coreyms ✅ Become a Channel Member: https://www.youtube.com/channel/UCCezIgC97PvUuR4_gbFUs5g/join ✅ One-Time Contribution Through PayPal: https://goo.gl/649HFY ✅ Cryptocurrency Donations: Bitcoin Wallet - 3MPH8oY2EAgbLVy7RBMinwcBntggi7qeG3 Ethereum Wallet - 0x151649418616068fB46C3598083817101d3bCD33 Litecoin Wallet - MPvEBY5fxGkmPQgocfJbxP6EmTo5UUXMot ✅ Corey's Public Amazon Wishlist http://a.co/inIyro1 ✅ Equipment I Use and Books I Recommend: https://www.amazon.com/shop/coreyschafer ▶️ You Can Find Me On: My Website - http://coreyms.com/ My Second Channel - https://www.youtube.com/c/coreymschafer Facebook - https://www.facebook.com/CoreyMSchafer Twitter - https://twitter.com/CoreyMSchafer Instagram - https://www.instagram.com/coreymschafer/ #Python

Оглавление (11 сегментов)

<Untitled Chapter 1>

hey there how's it going everybody in this video I wanted to walk through some real-world examples for how we can calculate the number of days or months that it will take to reach certain goals so we just went through the New Year holiday and maybe some people have some goals that they'd like to accomplish so whether that's you know paying off some credit cards or getting in better shape or personally for my youtube channel I'd like to reach a certain number of subscribers and just things like that so I thought it might be fun if we could write a program that will give us an estimate of how long it will take to reach these goals and writing scripts to solve problems like this is a great way to take certain things that you've learned and apply it to real-world examples so in this video we'll write a script for all three of the examples that I just mentioned and all three of these examples will be slightly different so that we can see how we can write quick little scripts to solve three different specific problems so one is going to be a script where we make monthly progress towards a goal one will be a script where we make weekly progress towards a goal and one will be a script where we make daily progress towards a goal so first let's start with writing a script to calculate the number of months that it would take to pay off a credit card and this will actually be the longest script that we write and the other two will be shorter and shorter so let's go ahead and get started so I have a script opened up here and you can see that I've already imported the modulus that we'll be using so I've imported the date time module and the calendar module and we'll see how we use these in just a bit okay so first of all let's figure out what our constants are going to be for paying off a credit card so first we have the credit card balance I'll just set that variable as balance and for now we'll just set that to $5000 for example and we're also going to have the interest rate and I will set that to 13% now you can do this as a decimal where you can just write out 13 and multiply that by point zero one to turn it into a decimal so for example in this instance we want the interest rate of 13 to actually be equal to 0. 1 3 and another constant that we're going to be working with here is the monthly payment that we're going to be making towards our credit card so we'll say monthly payment and for now we'll just set this equal to 500 so these are just all sample values that I'm plugging in right now and we can change this after the script is written to see what different results we get okay so now that we have this information let's think about how we can write a script that uses this information to pay off our credit card well when we pay off a credit card we usually make payments on the first of the month or towards the end of the month so some people do it on different days but you can change it depending on how yours is set up so what I'm thinking is that we can just assume that we'll start making our first monthly payment starting next month and see how long it will take us to pay off our credit card with the interest building up so we're going to need to specify some dates so in this example I'll start from the

start from the current day

current day so I'll set that as a variable just by saying today is equal to and that's going to be equal to date time date dot today so that is how you get the current day and now we need to figure out when it will be the first day of the next month and this is one of those things that seems like it would be easy at first glance but after you think about it for a while it actually is a little tricky now there might be some better ways of doing this but if we want to set a variable that is the first day of the next month then let's just take the remaining days left in the current month and add those to the current day so to do this we'll need to know how many days are in each month and to get

use the calendar module from the standard library

this we can use the calendar module from the standard library so it has a method called month range that takes a year and a month as arguments and returns the first day of that month and also the number of days in that month and it also works for leap years too so it's good for any year so we can say days in current month and we will set this equal to calendar dot and that is the month range function and now this takes in a year and a day so we want to get the

get the number of days in the current month

number of days in the current month so we'll just say today dot year and the second argument will be today dot month so given this year and month this is going to return a tuple with the day of the week that the first of that month falls on and also how many days are in that month so if we print this out so I will print out the days and the month save that and run it so the first value here is the day of the week that the first of that month falls on so the first of the month is I think zero is Monday so that's going to be a Monday and the second value here is the total days in the month and that's the value that we want so I'm gonna grab that just by getting the first index of that value so here at the end I'm going to tack on and index of one so now if we save that and run it you can see we're just getting the days and the month so now if we wanted to advance to the first of the next month then we could just add the difference of the days that are left so we can create another variable here and we'll just call this days until end of the month and we'll set that equal to the days in the current month - today dot day so now if I print this out really quick then at the time I'm recording this I it is the sixteenth so it should do 31 minus 16 so 15 so that it's saying that there's 15 days until we reach the end of the month okay so now we have the number of days that we need to add the to the current day in order to carry us over into the next

add days to a date

month and to add days to a date we can use a time Delta so let's see what this looks like so I'm going to create a start date variable here because the first of the next month is when we want to start making our payments so we'll say start date is equal to today and plus date time dot time Delta and now we're going to pass in a number of days that we want to add to the current date so we'll say days are equal to days till the end of the month now that is just going to take us to the end of the month but we want to start on the first so now we will just add one day on to that as well and just to make sure that worked let's print out this start date so I will save that and run it and you can see that we do get February first which is the first of next month since I'm recording this in January of 2018 now if any of this is confusing to you so then I do have a video on the date/time module where I go in-depth about all this stuff but for this video we're just applying those concepts and kind of moving through kind of quickly here so I'm not gonna go into as much detail about adding dates and things like that but if you are interested then definitely check out that date time video okay so now we have the first day of the next month now I don't want to change this start date variable because we want to reference that later so I'm gonna create another variable here called end date and for now we're just going to set this equal to the start date but we will be incrementing that end date throughout the script okay so now we're ready to see how long it will take to pay off our balance so let's create a while loop that just says while our balance is greater than zero so every time through this loop will simulate the beginning of a new month so first we need to add the interest that has accumulated from the previous month so since these interest rates are usually annual we need to divide it by 12 to get the monthly value so then we can multiply that with our

get the total interest charge

balance to get the total interest charge so we can say interest charge is equal to and that's going to be equal to our interest rate which is usually annual so we need to divide that by 12 and once we have that interest rate divided by 12 then we can multiply that by our current balance to get the total interest for that month so then that total interest charge is going to be added to our balance so we can say balance is plus equals the interest charge now this plus equals operator here is just the same as saying balance is equal to balance plus the interest charge but it is just cleaner and a little bit better to do it that way so we'll do plus equals interest charge and now since we're simulating the first of the month here we also want to subtract the monthly payment that we're going to be making from our balance so we will also say balance minus equals the monthly payment so what we've done so far here and our simulated first of month we've calculated the interest charge we've added that interest charge to our balance and we've also subtracted our monthly payment from that balance now since we've been modifying this balance sometimes floating points can get a little off and we can have a lot of decimal places and since we're working with you know some simulated

round our balance to two decimal places

money here let's round our balance to two decimal places just so it looks like you know since so we can say balance is equal to and round is just a built in function and we can do round that balance to two and that'll round it to two decimal places and also there's a possibility that we will pay off our balance and if we then we don't want our balance to be in the negative we just want it to hit zero when we pay it all off so let's say if the balance is less than zero then just set that balance equal to zero now we could have actually taken these three lines here and made them into a one liner with a ternary conditional now if you don't know what that is basically allows us to set a value based on a conditional on one line so I could have said instead of these three lines here we could have said that the balance is equal to 0 if balance is less than 0 else balance or else round that balance to two decimal places now some of you may have never seen these before so just again this is sending the balance equal to zero if our balance is less than zero if it's not less than zero then it's just going to set balance equal to our rounded balance to two decimal places now some people really like these but I always like to err on the side of being more clear than writing less code so I'm just going to do mine the way that we had it up here because I think it's a little bit easier to understand exactly what's going on okay so at this point we've done everything that we need to do for this month and are ready to increment to the next month if the balance hasn't reached zero yet so at this point let's go ahead and print out

print out our end date and the remaining balance

our end date and the remaining balance so I'll do a print of the end date and the balance and after that we want to increment our end date variable for another month before we continue on with the next iteration and the loop now to move forward a month we can just add the number of days in the month to our end date because we already know we're on the first day of the month since we took care of that before so there's no need to get the remaining days like we did up at the top of our script so let me scroll up to the top here and we will reuse a lot of this so let's see I will grab these three lines here and paste these in and then let me correct the indentations here okay so like I said there's no need to calculate the days till the end of the month because we already know that we are on the first and now the days and the current month instead of these values that we use before we want to use the end date dot year and month and still get that first index which will give us the rest of the days in the month and now we want to set this end date variable equal to the current end date plus the number of days in that current month and we don't need this plus one anymore so I can save that okay and if you're still not quite sure what this is doing basically let's use February as an example here so after this does all these things here for the month of February then it's going to come in and say okay get the number of days in February so this is going to be equal to 28 and then basically here we're just saying okay now add 28 days and that's going to carry us over into March and then it's going to continue this pattern every time we go through the loop now at this point this should be all that we need to do this while loop will keep looping through and calculating our interest and a balance after we make our payments and then incrementing over to the next month now you have to be careful any time you use a while loop because there's always a chance that you could get stuck in an infinite loop so for example if we were to be making monthly payments that were less than the interest that was being added on every month then we would never pay off our balance and we would never exit this loop so you definitely have to watch out for that okay so now let's save this and run our code and see what we get okay so let's scroll up here to the top of this to see our constants and also let's expand this a little bit okay so that we can see that if we have a balance of five thousand dollars with this interest rate of 13% and started making payments of five hundred dollars every month then our output shows that what our balance new balance would be at the end of each month and our balance hits zero down here on December 1st of 2018 and you can play with these values in any way to see what results you would get so if you want to you know pay off a ten thousand dollar balance with you know making payments of four hundred instead then you can see that doesn't get paid off until 2020 now if you were to make a really low monthly payment so let's say like 110 you have to be careful not to do less than the interest that's added like I said before else you get an infinite loop but if I run that then we can see with payments that small that we don't pay off our balance until 2050 and the reason that is so slow is because our monthly payment barely pays the interest each month so if we scroll up here to the top then you can see that we only paid off you know two dollars from our overall balance in the first month and everything else just went to interest okay so that is a pretty interesting script that you can use to estimate how long it will take to pay off a credit card balance so now let's move on to our next script and so let's say for this script that we want to write a script that will you know if we wanted to get in better shape how many weeks it will take us to lose a certain number of pounds so I have an empty script here where I already have my imports and you can see that here I'm just importing the date/time module and like I said this script is going to be a little bit more simple than the one that we just wrote okay so just like our other script let's start off with a few

start off with a few constants

constants so first let's put the current weight and then the goal weight so for example let's say that someone is 220 pounds you know sorry I'm using pow instead of kilograms if you want to do those conversions you can do that okay so I'm going to say current weight is equal to 220 pounds and let's say that we have a goal weight and let's just set our goal weight equal to 180 pounds and now let's do an average pounds per week that we plan on losing so I'll say average lbs per week and usually people recommend you know to safely if you're losing weight that you can safely do that by losing one to two pounds per week so let's just do right in the middle at one point five one and a half pounds per week okay and now we need a start date for when we plan to start so let's just do this for today so we can do a start date just like before that is date time date dot today and just like our other script we want to keep this start date variable unchanged so let's set an end date variable as well and for now we'll just set this equal to the start date so now we have the information that we need to go ahead and make our loop to simulate losing our average pounds per week until we reach our goal so let's start our loop so our loop can be while our current weight is greater than our goal weight then let's keep going through this loop so within our loop we can simulate seven days going by so to do that we can say that our end date plus equals and now we want to add seven days to our end date so we can do that with date/time dot time Delta and then the number of days we can say days equal to seven and after those seven days have gone by we can say that our current weight - equals so we're going to subtract our average pounds per week so basically what we're saying here each time this goes through this loop it's going to say okay we are adding seven days have gone by and our current weight is now our average pounds per week less and it's going to keep doing that over and over until our current weight is no longer greater than our goal weight okay so outside of the loop let's print some information about how long that hook so for example let's print the number of weeks so I can do a print here and I'm going to use an F string now f strings are only available in Python 3. 6 and above if you're using a lower version then you'll have to use you know a dot format or something like that but within our F string I'm just going to say reached goal in and then we can put in our placeholder here and we will just do an end date - start date now when we that is going to give us a time Delta and time deltas have a days attribute - or we can see the total number of days between these two dates so now we have the total number of days between those two dates but we want to see how many weeks have gone by so now let's do a division by seven now that is a floor division to where it will cut off decimal places and then outside of our placeholder we can just say weeks so let's see if this works so if I save this and run it then we can see here that it prints out that we reached our goal in 27 weeks now if we actually want to know around what time that is in the year then let's

print out the end date

actually just print out the end date above here to print out that exact date so now if we save that and run it then we can see that with our current weight and goal weight and average pounds per week that we met our goal around the end of July which was 27 weeks now we can come up and change some of these cons constants to see what changes with our script so if we kept the same current wait and go wait but bumped our average pounds per week up to two and then rerun this then we can see that now that is 20 weeks and we got there in early June okay so you can see that this script was only about you know 15 lines pretty easy and just kind of fun to play around with these values and see what you can get okay so now let's look at one more example and this example will be even simpler than our other two scripts so far so let's say that I had a goal on my YouTube channel to hit a certain number of subscribers here on YouTube and would like to see how long it will take to reach that goal so I have another blank script here where I'm importing the date time and the math module and just like with our other two scripts let's start off with some constants so in our credit card example we were writing a script where we were making progress every month and in the wait week and in this example we're gonna see what it looks like to make progress every day and like I said this is going to be the simplest one so first of all let's start out with

start out with some constants

some constants here so let's say our let's set what our goal is so let's say the goal subs is 100,000 and the current subs let's see I think that is around 85,000 right now so now another constant let's just say subs to go is equal to our goal subs - our current subs now these aren't exact numbers we're just kind of using these for this script so now let's set and what our average is per day how much progress are we making per day so let's say that the average subs per day is equal to 200 so now that we know how many we have to go and how many were getting each day now we can just divide how much there is to go by the number that we're getting per day to get how many days that is going to be so we can say days to go is equal to the subs to go divided by our average per day now this is likely going to return a floating-point number but since we want to work with whole days let's just take the ceiling of this value here so that is what I imported the math module for so we'll say math dot seal and pass in those values into the seal function so basically what that does is it just rounds up so if this value was equal to you know 150 point 4 then it's just going to round that up to the next value so with an easy script like this we can just add the days to go to the current day and we'll have our estimate so I can say today is equal to date time date dot today and then we can just print out our answer here so I can print out today plus date time dot time Delta and we want to add the days to go so we'll say days is equal to days to go so this will print out how many days into the future we meet our goal so in less than fifteen lines of code we write something that can estimate something like this so if I save that and run it then we can see with somebody who has 85,000 subscribers trying to reach a hundred thousand subscribers at an average of two hundred per day that they will reach their goal around April first so maybe a better goal if you were going for the entire year would be something like 150 thousand if you save that and run it then you can see that you would meet that goal around the beginning of December so it's kind of fun just to write these short little scripts and be able to play around with the numbers just to see what you can get and you can always make these scripts more complicated if you'd like so maybe with this script you'd like to add in something like you know expected monthly growth or something along those lines to make your estimates more accurate or with our credit card example you could add you know expected monthly charges or something like that but hopefully these three scripts gave you some ideas for how to get started if you'd like to do something like that okay so I think that is going to do it for this video now we didn't really cover any new topics that we haven't seen in other videos but applying what we've learned to quick real-world scripts like this is a great way to take what you've learned and write something that could be useful for yourself or someone else and just taking the time to try to solve these problems is great practice and there are a ton of different ways that we could have written these scripts or added more to them so like I said before we could have added more complexity if you'd like we could have also taken this logic and put them in the function so that we could reuse the code and other modules so there is a lot that you could add to it and if you'd like some additional practice then you can take what we've written here and try to add to it or you could even try to clean it up with but if anyone has any questions about what we covered in this video then feel free to ask in the comment section below and I'll do my best to answer those and if you enjoy these tutorials and would like to support them then there are several ways you can do that these ways is simply like the video and give it a thumbs up and also it's a huge help to share these videos with anyone who you think would find them useful and if you have the means you can contribute through patreon and there's a link to that page in the description section below be sure to subscribe for future videos and thank you all for watching

Другие видео автора — Corey Schafer

Ctrl+V

Экстракт Знаний в Telegram

Экстракты и дистилляты из лучших YouTube-каналов — сразу после публикации.

Подписаться

Дайджест Экстрактов

Лучшие методички за неделю — каждый понедельник