Calling a method inside of init function python - python-2.7

I'm having an issue with this code:
import math
class Money(object):
def __init__(self, salary):
self.salary = salary
sal(self.salary)
def sal(self, x):
y = ( x - ( ( (x * 0.22) + 6534) ) - (1900.9408 + ( (x - 37568)*.077) ) )
print '-----------------------------------------------------------'
print 'monthly income before tax will be: ${0:.2f}' .format(x/12)
print 'bi-weekly income before tax will be: ${0:.2f}' .format(x/24)
print 'Hourly after tax: ${0:.2f}' .format(x/24/70)
print '-----------------------------------------------------------'
print 'Income after tax will be: ${0:.2f}' .format(y)
print 'Monthly after tax: ${0:.2f}' .format((y/12))
print 'bi-weekly after tax: ${0:.2f}' .format((y/24))
print 'Hourly after tax: ${0:.2f}' .format(y/24/70)
answer = raw_input('Do you want to do this again?\nType [Y] or [N]: ')
if( answer == 'Y'):
sal(x)
else:
print 'Thank you!'
return
def main():
x = input('Enter your taxable income: ')
salaryLister = Money(x)
main()
The traceback shows this:
Traceback (most recent call last):
File "taxableincome.py", line 35, in <module>
main()
File "taxableincome.py", line 33, in main
salaryLister = Money(x)
File "taxableincome.py", line 7, in __init__
sal(self.salary)
NameError: global name 'sal' is not defined
What does:
global name 'sal' is not defined mean?
Feel free to make comments about my design as well. I'd love to learn.

use self.sal, this is how you call instance methods of classes in python
How this works in python is, If you look at the method signature you have
def sal(self, salary)
basically, it needs the class reference as the first variable. And in python when you do self.sal it translates to
Money.sal(self, salary)
You can also call the method like this, but the recommended way is
self.sal(salary)
As per comments on your code, There definitely aren't any clear red flags. Though the last return statement in the sal function is not required. Its not a problem having it there, just something that caught my eye.
Also since you asked, I'd like to point this out. Please try to keep to a coding standard. let it be your own or someone else's. The important thing is consistency. But PEP-8 is generally the accepted style for python. You even have plugins for your editor which help you stick to it. You might want to read the style guide linked here.

Related

name 'Start()' not defined

I have two files in a game I am currently making (not finished). They are the same directory. When I run either of the two files, the terminal in macos Serria is giving me this error (and yes, I did research, to no avail). BTW, thank you, StackOverFlow, for answering (and downvoting when needed) questions. It truly helped me.:
File "story.py", line 3, in <module>
from engine import *
File "SurvivalAdventureGame/Resources/engine.py", line 2, in <module>
from story import *
File "SurvivalAdventureGame/Resources/story.py", line 5, in <module>
class Start(Scene):
NameError: name 'Scene' is not defined
Here is story.py:
from sys import exit
from random import randint
from engine import *
class Start(Scene):
print """
You are flying to Brussels from Seattle. You *are* glad you received the bonus from work, you think to yourself.
\nUnfortunally, you were only able to put 100$ towards the vacation due to your bastard landlord.
\nYou muttered to yourself, "If this plane got League Pass, though. Warriors-Raptors would be lit."
\nYep, your 14-year old son says as he reads The New Jim Crow. Your 9-year old son is playing Minecraft.
\nThen the speakers boomed, as the crew said, "Hi. My name is Messlia and our pilot is temporarily incapacitated."
\nA strange mixture of curses, crying, yells of terror, and silence filled the cabin.
\n"We will land shortly on a grass clearing near trees."
\nMore panic.
\nYou cried as You told your panicking sons (and secretly myself) to do
"""
print "1. Bring only a blanket, some food and water, some clothing, and every medication needed."
print "2. Bring nothing"
print "3. Bring everything you possibly can."
action = raw_input("> ")
if action == "1":
print "You survived, crawling out the door with a painful leg injury."
print "\n Your older son, a safety-first guy, escaped without ANY injury AT ALL. Your other son, however, has a gaping hole in his wrists."
print "\n He sheds tears, clearly in pain, as you ponder your options."
print "1. Splash with water and cover it with a blanket"
print "2. Cover it with a towel."
print "3. Splash it with water only."
next = raw_input("> ")
if next == "1":
print "Your now have about 50 mL of water left. However, he has calmed down."
Day1()
elif next == "2":
print "You now have to tend to the boy at all times. However, at least he will not get sick, right?"
Day1()
elif next == "3":
print "You now only have 50 mL of water left. At least he calmed down a bit!"
Day1()
else:
Stupid()
elif actions =="2":
print "You survive with no injuries, however, you have nothing and your youngest son just suffered a major wrist injury."
Day1()
elif next == "3":
print "You, your sons, and 12 people die because of you delaying everyone else."
Death()
else:
Stupid()
class Death(Scene):
print "Either you, one or both of your sons or others died. You suck."
class Stupid(Scene):
print "ERROR: OVERWHELMING STUPIDITY."
print "You should enter the numbers without the period, without the words"
Here is engine.py:
from sys import exit
from story import *
class Scene(object):
def __init__(self):
start()
def start(self):
print "DOESNOTEXIST!"
exit(1)
class Engine(object):
def __init__(self, scene_map):
self.scene_map = scene_map
def play(self):
current_scene = self.scene_map.opening_scene()
while True:
print "\n--------"
next_scene_name = current_scene.start()
current_scene = self.scene_map.next_scene(next_scene_name)
class Map(object):
# Won't work now, Gotta finish writing the story!
scenes = {
"Start": Start(),
"Day1": Day1(),
"Day2": Day2(),
"Day3": Day3(),
"Day4": Day4(),
"Day5": Day5(),
"Day6": Day6(),
"Day7": Day7(),
"Day8": Day8(),
"Death": Death(),
"Stupid": Stupid(),
}
def __init__(self, start_scene):
self.start_scene = start_scene()
def next_scene(self, scene_name):
return Map.scenes.get(scene_name)
def opening_scene(self):
return self.next_scene(self.start_scene)
class play(object, Map):
def __init__(self, map):
the_map = Map('Start')
the_map = Engine(the_map)
a_game.play()
Looks like you have a circular dependency: in story you import * (everything) from engine and vice versa. This is not supported in Python.

Print line if any of these words are matched

I have a text file with 1000+ lines, each one representing a news article about a topic that I'm researching. Several hundred lines/articles in this dataset are not about the topic, however, and I need to remove these.
I've used grep to remove many of them (grep -vwE "(wordA|wordB)" test8.txt > test9.txt), but I now need to go through the rest manually.
I have a working code that finds all lines that do not contain a certain word, prints this line to me, and asks if it should be removed or not. It works well, but I'd like to include several other words. E.g. let's say my research topic is meat eating trends. I hope to write a script that prints lines that do not contain 'chicken' or 'pork' or 'beef', so I can manually verify if the lines/articles are about the relevant topic.
I know I can do this with elif, but I wonder if there is a better and simpler way? E.g. I tried if "chicken" or "beef" not in line: but it did not work.
Here's the code I have:
orgfile = 'text9.txt'
newfile = 'test10.txt'
newFile = open(newfile, 'wb')
with open("test9.txt") as f:
for num, line in enumerate(f, 1):
if "chicken" not in line:
print "{} {}".format(line.split(',')[0], num)
testVar = raw_input("1 = delete, enter = skip.")
testVar = testVar.replace('', '0')
testVar = int(testVar)
if testVar == 10:
print ''
os.linesep
else:
f = open(newfile,'ab')
f.write(line)
f.close()
else:
f = open(newfile,'ab')
f.write(line)
f.close()
Edit: I tried Pieter's answer to this question but it does not work here, presumeably because I am not working with integers.
you can use any or all and a generator. For example
>>> key_word={"chicken","beef"}
>>> test_texts=["the price of beef is too high", "the chicken farm now open","tomorrow there is a lunar eclipse","bla"]
>>> for title in test_texts:
if any(key in title for key in key_words):
print title
the price of beef is too high
the chicken farm now open
>>>
>>> for title in test_texts:
if not any(key in title for key in key_words):
print title
tomorrow there is a lunar eclipse
bla
>>>

Python function will cycle through but error on the final iteration

On the following Python function I am using Python 2.7.6 and SQLAlchemy as the ORM. I am stumped as to why I keep getting the following error even though the function cycles through.
def vacantShelter():
#Used to stay in bounds of the all the entries in the DB
shelterCount = session.query(Shelter).count
shelter_id = 1
print "Here are the Shelter results:"
while(shelter_id<=shelterCount):
shelter = session.query(Shelter).filter(Shelter.id == shelter_id).first()
if(shelter.max_capacity >= getShelterOccupancy(shelter_id)):
print shelter.name + " has available space"
else:
print shelter.name + " is full! :("
shelter_id = shelter_id + 1
What is confusing me is that it is functioning correctly at first considering there are results, I do not understand why on the last iteration it fails or what to do about it.
`Here are the Shelter results:
Oakland Animal Services has available space
San Francisco SPCA Mission Adoption Center is full! :(
Wonder Dog Rescue has available space
Humane Society of Alameda is full! :(
Palo Alto Humane Society is full! :(
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "pup_test.py", line 82, in vacantShelter
if(shelter.max_capacity >= getShelterOccupancy(shelter_id)):
AttributeError: 'NoneType' object has no attribute 'max_capacity'`
The most likely reason for this error is the presence of holes in the Shelter.id values. For example, there the table could contain rows with the id value of [1, 2, 3, 4, 5, 7]. When you reach the last element, you will try to find a Shelter with id of 6, but it does not exist.
In principal, the way your code works now is by making a very bold assumption that all rows in the database have consecutive id values starting from 1. But this is generally not the case. Instead, you could directly iterate over the instances, and not load them one-by-one:
def vacantShelter():
shelters = session.query(Shelter).all()
for shelter in shelters:
if(shelter.max_capacity >= getShelterOccupancy(shelter.id)):
print shelter.name + " has available space"
else:
print shelter.name + " is full! :("
Also, it is much cleaner.

ex 25 LPTHW (global name pop is not defined)

I'm currently learning how to code with python following the exercise at the website 'Learn python the hard way' exercise 25.
The problem is that I can't complete exercise 25 because I have a problem that i can't figure out.
I'm typing into the python console but at the instruction number 8 ex25.print_last_word(words) I have this error:
>>> ex25.print_last_word(words)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "ex25.py", line 19, in print_last_word
word = words.pop(-1)
NameError: global name 'POP' is not defined
this is my code.
def break_words(stuff):
"""This function will break up word for us, praticamente
divide in blank space tra le parole"""
words = stuff.split(' ')
return words
def sort_words(words):
'''sort the words, ordina la parola??'''
return sorted(words)
def print_first_word(words):
'''print the first word after popping it off, ossia trova pop(0) trova
la lettera iniziale della parola..'''
word = words.pop(0)
print word
def print_last_word(words):
'''print the last word after popping it off'''
word = words.pop(-1)
print word
def sort_sentence(sentence):
'''takes in a full sentence and return the sorted words.'''
words = break_words(sentence)
words = break_words(words)
def print_first_and_last(sentence):
'''prints the first and the last words of the sentence.'''
words = break_words(sentence)
print_first_word(words)
print_last_word(words)
def print_first_and_last_sorted(sentence):
'''Sorts the words then prints the first and last one'''
word = sort_sentence(sentence)
print_first_word(words)
print_last_word(words)
The error raised by the Python interpreter does not match the code you posted, since POP is never mentioned in your code.
The error might be an indication that the interpreter has in memory a different definition for the module ex25 than what is in your text file, ex25.py. You can refresh the definition using
>>> reload(ex25)
Note that you must do this every time you modify ex25.py.
For this reason, you may find it easier to modify ex25.py so that it can be run from the command-line by adding
if __name__ == '__main__':
words = ...
print_last_word(words)
to the end of ex25.py, and running the script from the command-line:
python ex25.py

Numerical regression testing

I'm working on a scientific computing code (written in C++), and in addition to performing unit tests for the smaller components, I'd like to do regression testing on some of the numerical output by comparing to a "known-good" answer from previous revisions. There are a few features I'd like:
Allow comparing numbers to a specified tolerance (for both roundoff error and looser expectations)
Ability to distinguish between ints, doubles, etc, and to ignore text if necessary
Well-formatted output to tell what went wrong and where: in a multi-column table of data, only show the column entry that differs
Return EXIT_SUCCESS or EXIT_FAILURE depending on whether the files match
Are there any good scripts or applications out there that do this, or will I have to roll my own in Python to read and compare output files? Surely I'm not the first person with these kind of requirements.
[The following is not strictly relevant, but it may factor into the decision of what to do. I use CMake and its embedded CTest functionality to drive unit tests that use the Google Test framework. I imagine that it shouldn't be hard to add a few add_custom_command statements in my CMakeLists.txt to call whatever regression software I need.]
You should go for PyUnit, which is now part of the standard lib under the name unittest. It supports everything you asked for. The tolerance check, e.g., is done with assertAlmostEqual().
The ndiff utility may be close to what you're looking for: it's like diff, but it will compare text files of numbers to a desired tolerance.
I ended up writing a Python script to do more or less what I wanted.
#!/usr/bin/env python
import sys
import re
from optparse import OptionParser
from math import fabs
splitPattern = re.compile(r',|\s+|;')
class FailObject(object):
def __init__(self, options):
self.options = options
self.failure = False
def fail(self, brief, full = ""):
print ">>>> ", brief
if options.verbose and full != "":
print " ", full
self.failure = True
def exit(self):
if (self.failure):
print "FAILURE"
sys.exit(1)
else:
print "SUCCESS"
sys.exit(0)
def numSplit(line):
list = splitPattern.split(line)
if list[-1] == "":
del list[-1]
numList = [float(a) for a in list]
return numList
def softEquiv(ref, target, tolerance):
if (fabs(target - ref) <= fabs(ref) * tolerance):
return True
#if the reference number is zero, allow tolerance
if (ref == 0.0):
return (fabs(target) <= tolerance)
#if reference is non-zero and it failed the first test
return False
def compareStrings(f, options, expLine, actLine, lineNum):
### check that they're a bunch of numbers
try:
exp = numSplit(expLine)
act = numSplit(actLine)
except ValueError, e:
# print "It looks like line %d is made of strings (exp=%s, act=%s)." \
# % (lineNum, expLine, actLine)
if (expLine != actLine and options.checkText):
f.fail( "Text did not match in line %d" % lineNum )
return
### check the ranges
if len(exp) != len(act):
f.fail( "Wrong number of columns in line %d" % lineNum )
return
### soft equiv on each value
for col in range(0, len(exp)):
expVal = exp[col]
actVal = act[col]
if not softEquiv(expVal, actVal, options.tol):
f.fail( "Non-equivalence in line %d, column %d"
% (lineNum, col) )
return
def run(expectedFileName, actualFileName, options):
# message reporter
f = FailObject(options)
expected = open(expectedFileName)
actual = open(actualFileName)
lineNum = 0
while True:
lineNum += 1
expLine = expected.readline().rstrip()
actLine = actual.readline().rstrip()
## check that the files haven't ended,
# or that they ended at the same time
if expLine == "":
if actLine != "":
f.fail("Tested file ended too late.")
break
if actLine == "":
f.fail("Tested file ended too early.")
break
compareStrings(f, options, expLine, actLine, lineNum)
#print "%3d: %s|%s" % (lineNum, expLine[0:10], actLine[0:10])
f.exit()
################################################################################
if __name__ == '__main__':
parser = OptionParser(usage = "%prog [options] ExpectedFile NewFile")
parser.add_option("-q", "--quiet",
action="store_false", dest="verbose", default=True,
help="Don't print status messages to stdout")
parser.add_option("--check-text",
action="store_true", dest="checkText", default=False,
help="Verify that lines of text match exactly")
parser.add_option("-t", "--tolerance",
action="store", type="float", dest="tol", default=1.e-15,
help="Relative error when comparing doubles")
(options, args) = parser.parse_args()
if len(args) != 2:
print "Usage: numdiff.py EXPECTED ACTUAL"
sys.exit(1)
run(args[0], args[1], options)
I know I'm quite late to the party, but a few months ago I wrote the nrtest utility in an attempt to make this workflow easier. It sounds like it might help you too.
Here's a quick overview. Each test is defined by its input files and its expected output files. Following execution, output files are stored in a portable benchmark directory. A second step then compares this benchmark to a reference benchmark. A recent update has enabled user extensions, so you can define comparison functions for your custom data.
I hope it helps.