Script works in CodeCademy but not at command line - python

I am a novice programmer teaching myself Python using CodeCademy. I wrote a script on my own in order to check the knowledge that I have learned thus far. The intention of this script is to print the names of people that are available on a certain weekend, based on a user-input date and cross-referenced with lists of dates that I wrote in the script.
The strange part is that this script functions exactly as intended in CodeCademy's Python environment, with no errors. It returns exactly the results I expect every single time. However, this is not the case when I try to run the script manually using Python 3.6.1 on my computer via the command line. Rather, it returns the same result every single time no matter what. Here is my code:
#script to tell who is free on a certain weekend
input_date = input("Please input the weekend on which you are looking for in
the format mm.dd (ex. weekend of June 30th is 06.30): ")
ben_dates = [06.16,06.23,06.30,07.07,07.14,08.04,08.11]
david_dates = [06.16,06.23,06.30,07.14,07.28,08.04,08.11]
danyall_dates = [06.30,07.07,07.14,07.21,07.28,08.04,08.11]
kevin_dates= [06.16,06.23,06.30,07.07,07.14,07.21,07.28,08.04,08.11,08.18]
manan_dates=[06.16,07.14,07.21,07.28,08.04]
jack_dates=[06.30,07.07,07.14,07.21,07.28,08.04]
free_people = "The people free on this date are: "
free_people_orig = free_people
for date in ben_dates:
if input_date == date:
free_people = free_people + "Ben, "
for date in david_dates:
if input_date == date:
free_people = free_people + "David, "
for date in danyall_dates:
if input_date == date:
free_people = free_people + "Danyall, "
for date in kevin_dates:
if input_date == date:
free_people = free_people + "Kevin, "
for date in manan_dates:
if input_date == date:
free_people = free_people + "Manan, "
for date in jack_dates:
if input_date == date:
free_people = free_people + "Jack, "
if len(free_people) == len(free_people_orig):
free_people = "No one is free on this weekend."
print(free_people)
So, for example, if the user inputs '06.30' on CodeCademy, the program will print 'The people free on this date are: Ben, David, Danyall, Kevin, Jack,' and this would be the correct result.
However, if run in command line, the same input will print 'No one is free on this weekend' and I have absolutely no idea why this is happening.
I have tried several different variations of while and for loops, using if, elif, and else statements, changing the conditions and format of the free_people string and what triggers it to be modified, as well as many other tactics for going about this specific solution, yet none have been able to make the script run properly. What am I doing wrong here that it works in CodeCademy but not on my computer?
Also, I am aware that this is far from the best way to create a script for this task, and even then my implementation could certainly be better. However, I am a beginner, and am writing this script with the primary concern of testing specific skills that I have learned by writing a script that could have some modicum of basic use for myself. I am only interested in figuring out why this specific version of this specific script does not work.
P.S. This is my first post on StackOverflow, my apologies if I formatted this post incorrectly.

The issue is that you are inputting a string, when it needs to be a float. Every element in your lists are floats, and you are trying to see if an element of type string exists in any of those lists, which is False.
Try this:
input_date = float(input("Please input the weekend on which you are looking for in the "
"format mm.dd (ex. weekend of June 30th is 06.30): "))

Related

Python MAPI Outlook read emails for a particular year

This func is for Year alone. (Doesn't work)
def daterange(args):
user_inp = datetime.strptime(args,'%Y')
rmail = object.Restrict("[ReceivedTime] == '" + user_inp.strftime('%Y')+"'")
return rmail
The Restrict code doesn't work with = , throws error with == and only works with >=
My requirement is all mails from user_inp(2020) or 2019 etc
Please Help !!!
The Restrict code doesn't work with = , throws error with == and only works with >=
Using the equal operator is not really a good idea. Instead, you need to specify the time and date range. The difference can be a minute, but not equal.
Read more about the date and time comparisons in Outlook on the Filtering Items Using a Date-time Comparison page.

Refining a Python finance tracking program

I am trying to create a basic program that tracks retirement finances. What I have got so far below takes input for ONE entry and stores it. The next time I run it, the previous values get wiped out. Ideally what I would like is a program that appends indefinitely to a list, if I open it up 2 weeks from now I'd like to be able to see current data in dict format, plus add to it. I envision running the script, entering account names and balances then closing it, and doing it again at a later point
Few questions:
How do I achieve that? I think I need some loop concept to get there
Is there a more elegant way to enter the Account Name and Balance, rather than hardcoding it in the parameters like I have below? I tried input() but it only runs for the Account Name, not Balance (again, maybe loop related)
I'd like to add some error checking, so if the user doesn't enter a valid account, say (HSA, 401k or Roth) they are prompted to re-enter. Where should that input/check occur?
Thanks!
from datetime import datetime
Account = {
"name": [],
"month": [],
"day": [],
"year": [],
"balance": []
}
finance = [Account]
def finance_data(name, month, day, year, balance):
Account['name'].append(name)
Account['month'].append(month)
Account['day'].append(day)
Account['year'].append(year)
Account['balance'].append(balance)
print(finance)
finance_data('HSA',
datetime.now().month,
datetime.now().day,
datetime.now().year,
500)
When you run a script and put values in variables defined in the code, the values only last for however long the program runs. Each time you run the script, it will start over from the initial state defined in the code and, thus, not save state from the last time you ran the script.
What you need is persistent data that lasts beyond the runtime of the script. Normally, we accomplish this by create a database, using the script to write new data to the database, and then, when the script runs next, read the old values from the database to remember what happened in the past. However, since your use case is smaller, it probably doesn't need a full blown database system. Instead, I would recommend writing the data to a text file and then reading from the text file to get the old data. You could do that as follows:
# read about file io in python here: https://docs.python.org/2/tutorial/inputoutput.html#reading-and-writing-files
dataStore = open("dataFile.txt", "r+") # r+ is the read and write mode
def loadDataToAccount(dataStore):
Account = {
"name": [],
"month": [],
"day": [],
"year": [],
"balance": []
}
for line in dataStore.read().splitlines():
(name, month, day, year, balance) = line.split("|")
Account['name'].append(name)
Account['month'].append(month)
Account['day'].append(day)
Account['year'].append(year)
Account['balance'].append(balance)
return Account
Account = loadDataToAccount(dataStore)
Here I am assuming that we organize the text file so that each line is an entry and the entry is "|" separated such as:
bob|12|30|1994|500
rob|11|29|1993|499
Thus, we can parse the text into the Account dictionary. Now, lets look at entering the data into the text file:
def addData(Account, dataStore):
name = raw_input("Enter the account name: ")
balance = raw_input("Enter the account balance: ")
# put name and balance validation here!
month = datetime.now().month
day = datetime.now().day
year = datetime.now().year
# add to Account
Account['name'].append(name)
Account['month'].append(month)
Account['day'].append(day)
Account['year'].append(year)
Account['balance'].append(balance)
# also add to our dataStore
dataStore.write(name + "|" + month + "|" + day + "|" + year + "|" + balance + "\n")
addData(Account, dataStore)
Notice here how I wrote it to the dataStore with the expected format that I defined to read it in. Without writing it to the text file, it will not save the data and be available for the next time you run.
Also, I used input to get the name and balance so that it is more dynamic. After collecting the input, you can put an if statement to make sure it is a valid name and then use some sort of while loop structure to keep asking for the name until they enter a valid one.
You would probably want to extract the code that adds the values to Account and put that in a helper function since we use the same code twice.
Good luck!

Get time since comment was posted [Praw]

Is there a way to get the time since a comment was posted using Praw?
I've looked over the docs but couldn't find any mention of it, if there isn't, are there any workarounds to get the time?
I don't know, if you're still looking for an answer. In any case, someone might find this via search engine, so here's an idea:
import praw
import datetime
reddit = praw.Reddit(...)
comment = reddit.comment(id="ctu29cb")
now = int(datetime.datetime.timestamp(datetime.datetime.today()))
then = int(comment.created)
delta = now - then
print("comment has been created with timestamp", then)
print("which means on", datetime.datetime.fromtimestamp(then).strftime('%Y-%m-%d %H:%M:%S'))
print("that was", delta, "seconds or", str(datetime.timedelta(seconds=delta)), "hours ago")
which returns
comment has been created with timestamp 1438924830
which means on 2015-08-07 05:20:30
that was 69533363 seconds or 804 days, 18:49:23 hours ago

python - Parsing data from binary file using structs

I have a save game file that I am trying to parse out all of the characters attributes by reading the file using hex offsets. I'm able to get all strings out properly since that plain text but I am having issues with parsing the binary portions that I am working with.
I'm pretty sure that I'm reading in the right data but when I unpack the string I am getting unexpected (incorrect) output
The file I'm working with is www.retro-gaming-world.com/SAVE.DAT
import struct
infile = open('SAVE.DAT','rb')
try:
buff = infile.read()
finally:
infile.close
infile.seek(0x00,0)
print "Save Signature: " + infile.read(0x18)
print "Save Version: " + str(struct.unpack('>i',buff[0x18:0x18+4])[0])
infile.seek(0x1C,0)
print "The letter R: " + infile.read(0x01)
infile.seek(0x1D,0)
print "Character Name: " + infile.read(0x20)
infile.seek(0x3D,0)
print "Save Game Name: " + infile.read(0x1E)
print "Save game day: " + str(struct.unpack('>i',buff[0x5B:0x5B+4])[0])
print "Save game month: " + str(struct.unpack('>i',buff[0x5D:0x5D+4])[0])
print "Save game year: " + str(struct.unpack('>i', buff[0x5F:0x5F+4])[0])
I'm having two different issues, either the wrong data is returned or when I try to unpack some of the fields I get an error that the string isn't long enough, I can read in more but the day month and year are only 2 and 4 bytes respectively and are integers, I'm not sure I'm going about this the right way, I believe I'm fetching the right fields but think I am unpacking or handling the data incorrectly some where if not completely.
version should return 0100
day should return 21
month should return 09
year should return 2013
What exactly am I getting wrong hrere, is there another way or a better way to go about parsing the fields from the binary?
The error is, that although the values are of integer type, they only have the length of 2, being an unsigned short in C. Thus, you have to read them as
struct.unpack('>H',buff[0x5B:0x5B+2])[0])
and so on. signed or unsigned does not seem to make a difference here. If available, check the documentation of the save file, it should be denoted there which is appropriate. If not, good luck trying (itertools can be helpful).
For more details of types, check the table on the Python documentation for structs
As a big fan of Fallout 1 and 2 I do wish you good luck and lots of success with the project (-;

Getting a count of action from today's date from filtered results in Python

I have an action that a user can do many times a day. I'm trying to get a count of how many times the user has taken that action, but only for today's date. Here's the way I'm currently solving this, but is there an easier way? I feel like I should be able to fit this in one line. :)
today_slaps = 0
slaps = Slap.objects.filter(from_user=request.user.id)
for slap in slaps:
if slap.date.date() == datetime.now().date():
today_slaps += 1
The logic I'm looking for is:
slaps = Slap.objects.filter(from_user=2, date.date()=datetime.now().date()).count()
But that's obviously throwing an error that a keyword can't be an expression. Sorry if this is a basic one, but thoughts?
slap_count = Slap.objects.filter(from_user=request.user, \
date__gte=datetime.date.today()).count()
# specifically setting datetimefield=datetime.date.today() won't work
# gte = will work for datetimefield vs datetime object starting at that date
# it's also assumed there will never be a slap from the future.
Generates the following SQL:
SELECT ... FROM ... WHERE ... date >= 2011-02-26 00:00:00
So it's safe to say you will only get today's slaps, again, unless you have slaps from the future. If you do, I'd set every date__day, date__year, date__month explicitly.
Thanks to Yuji (below) we came up with this answer:
slap_count = Slap.objects.filter(from_user=request.user.id, date__gte=datetime.today().date()).count()

Categories

Resources