To begin, I am new to all of this. I could have done this in excel, but decided this would be a good project to give a try. I used to be quick learning smart cookie, but I am mostly just stupid nowadays. I have no idea what this is caused by. It just doesn't make sense.
Here is what the console outputs:
What is the daily rate? 800
How many deployments in the year? 3
0.0
144000.0
Traceback (most recent call last):
File "<ipython-input-17-fb0f96552601>", line 1, in <module>
runfile('C:/Users/Business Laptop/.spyder-py3/temp.py',
wdir='C:/Users/Business Laptop/.spyder-py3')
File "C:\ProgramData\Anaconda3\lib\site-
packages\spyder\utils\site\sitecustomize.py", line 710, in runfile
execfile(filename, namespace)
File "C:\ProgramData\Anaconda3\lib\site-
packages\spyder\utils\site\sitecustomize.py", line 101, in execfile
exec(compile(f.read(), filename, 'exec'), namespace)
File "C:/Users/Business Laptop/.spyder-py3/temp.py", line 44, in <module>
tax_rate = tax_rate_calc(gross_income)
File "C:/Users/Business Laptop/.spyder-py3/temp.py", line 38, in
tax_rate_calc
return (.1*9525+.12*(gross_income-9525)+.22(gross_income-
38700)+.24(gross_income-82500))/gross_income
TypeError: 'float' object is not callable
When I look at the error, it is coming at a point where the code is identical to the previous code that did not throw the error....
daily_rate = float(input("What is the daily rate? "))
deployment = 60.0
rotations = float(input("How many deployments in the year? "))
def bonus_calc(rotations):
if rotations > 3:
return (rotations - 3) * 10000
else:
return 0.0
bonus = bonus_calc(rotations)
print(bonus)
gross_income = daily_rate * deployment * rotations
print(gross_income)
def tax_rate_calc(gross_income):
if gross_income < 9525:
return .1
elif gross_income >= 9525 and gross_income < 38700:
return (.1*9525+.12*(gross_income-9525))/gross_income
elif gross_income >= 38700 and gross_income < 82500:
return (.1*9525+.12*(gross_income-9525)+.22(gross_income-
38700))/gross_income
elif gross_income >= 82500 and gross_income < 157500:
return (.1*9525+.12*(gross_income-9525)+.22(gross_income-
38700)+.24(gross_income-82500))/gross_income
elif gross_income >= 157500 and gross_income < 200000:
return (.1*9525+.12*(gross_income-9525)+.22(gross_income-
38700)+.24(gross_income-82500)+ .32(gross_income-157500))/gross_income
elif gross_income > 200000:
return (.1*9525+.12*(gross_income-9525)+.22(gross_income-
38700)+.24(gross_income-82500)+ .32(gross_income-
157500)+.35(gross_income-200000))/gross_income
tax_rate = tax_rate_calc(gross_income)
def taxes_owed_calc(tax_rate, gross_income):
return tax_rate * gross_income
taxes_owed = taxes_owed_calc(tax_rate, gross_income)
def net_income_calc(gross_income, taxes_owed):
return gross_income - taxes_owed
net_income = net_income_calc(gross_income, taxes_owed)
def monthly_equivalent_calc(net_income):
return net_income / 12
monthly_equivalent = monthly_equivalent_calc(net_income)
print("Monthly income equivalent" + monthly_equivalent)
any help!?
Related
I am making a function that prime factorises a number. However, instead of doing what it should, it raises a weird TypeError.
def isprime(num):
if num > 1:
# check for factors
for i in range(2,num):
if num%i==0:
return False
break
else:
return True
else:
return False
def primes(no):
nolist=[]
for a in range(1,(no+1)):
if isprime(a)==True:
nolist.append(a)
return nolist
def factors(b):
Lst=[]
while True:
for prime in primes(b):
if b%prime==0:
b=b/prime
Lst.append(b)
if b==1:
break
return Lst
factors(6)
Raises weird TypeError:
Traceback (most recent call last):
File "/data/user/0/ru.iiec.pydroid3/files/accomp_files/iiec_run/iiec_run.py", line 31, in <module>
start(fakepyfile,mainpyfile)
File "/data/user/0/ru.iiec.pydroid3/files/accomp_files/iiec_run/iiec_run.py", line 30, in start
exec (open(mainpyfile).read(), __main__.__dict__)
File "<string>", line 71, in <module>
File "<string>", line 64, in factors
File "<string>", line 58, in primes
TypeError: 'float' object cannot be interpreted as an integer
My (idiotic) logic tells me that 'float' object has nothing to do with my code. I just don't get it. Any correction to my code will be highly appreciated
Problems with your code
Prime number list not including 2. (isprime function is wrong)
You are calling primes function again and again. Not neccessary
When you divide b/prime it is returning float
You are appending b in prime factor list Lst instead of prime
Find Number is prime or not
def isprime(num):
if num > 1:
for i in range(2,num):
if num%i==0:
return False
else:
return False
FUll Code
def isprime(num):
if num > 1:
# check for factors
for i in range(2,num):
if num%i==0:
return False
else:
return True
def primes(no):
nolist=[]
print(type(no))
for a in range(1,(no+1)):
if isprime(a)==True:
nolist.append(a)
return nolist
def factors(b):
Lst=[]
prime_nums = primes(b)
while True:
for prime in prime_nums:
if b%prime==0:
b=b//prime
Lst.append(prime)
break
if b==1:
break
return Lst
print(factors(6))
EDIT: I wonder if you think the issue might be that I'm trying to store an entire dictionary row returned from database in a session variable?
Here's the error (full error printout is at bottom of this post):
TypeError: Object of type User is not JSON serializable
FYI: I'm not using JSON anywhere in my code.
Here's the relevant parts of my code (main.py):
class User():
def __init__(self, t_id_user=None, t_email=None):
self.t_id_user = t_id_user
self.t_email = t_email
def create_or_update(self, t_create_or_edit="Edit"):
#How necessary are the "=None" below?
#self.t_id_user = userCreate(self, t_id_user=None, t_email=None):
#How necessary are the "=None" above?
if t_create_or_edit == "Create":
self.t_id_user = userCreate(
self.t_email
)
else:
self.t_id_user = userUpdate(
self.t_id_user_edit,
self.t_email
)
def get_from_id(self, t_id_user):
# logic to retrieve your user's data from your database of choice
myData = usersGet(
t_id_user="0",
t_email=""
)
self.t_id_user = myData["t_id_user"]
self.t_email = myData["t_email"]
return self
def userClearSession(t_which="user_current"):
logging.debug("Start of userClearSession()")
t_id_user = "0"
t_email = ""
user_instance = User(t_id_user, t_email)
if t_which == "user_current":
session["user_current"] = user_instance
else:
session["user_edit"] = user_instance
return
#app.route('/', methods=['GET', 'POST'])
#app.route('/userRegister', methods=['GET', 'POST'])
def index(t_title="Login or Register", t_message=""):
if "user_current" not in session:
userClearSession(t_which="user_current")
return render_template(
"userRegister.html",
t_message=t_message,
t_js="userRegister.js",
t_title=t_title
)
def userCreate(t_which="current"):
id_user = 0
db_cursor = data_cursor()
q = ""
q += "INSERT INTO tbl_users "
q += " ( "
q += " i_security_level"
q += ", t_email"
q += " ) "
q += " VALUES "
q += " ( "
q += " %(t_security_level)s"
q += ", '%(t_email)s'"
q += " ) "
try:
if t_which == "current":
user_instance = session["user_current"]
else:
user_instance = session["user_edit"]
vars = {
't_security_level': int(session["user_instance"].t_security_level),
't_email': AsIs(session["user_instance"].t_email)
}
db_cursor.execute(q,vars)
except Exception as e:
t_message = "Error"
else:
id_found = userIsInDB(session["user_instance"].t_email)
if id_found >= 1:
t_id_user = id_found
if t_which == "current":
session["user_current"].t_id_user = t_id_user
else:
session["user_edit"].t_id_user = t_id_user
t_message = "User Created"
db_cursor.close()
db_conn.close()
The full error message:
I'm having a hard time getting any meaning out of this error message and need help. It doesn't appear to point to any parts of main.py, though I know the error is somewhere in there and I'm pretty sure I narrowed it down to the code you see above:
File "C:\Python\Python38\Lib\site-packages\flask\app.py", line 2464, in __call__
return self.wsgi_app(environ, start_response)
File "C:\Python\Python38\Lib\site-packages\flask\app.py", line 2450, in wsgi_app
response = self.handle_exception(e)
File "C:\Python\Python38\Lib\site-packages\flask\app.py", line 1867, in handle_exception
reraise(exc_type, exc_value, tb)
File "C:\Python\Python38\Lib\site-packages\flask\_compat.py", line 39, in reraise
raise value
File "C:\Python\Python38\Lib\site-packages\flask\app.py", line 2447, in wsgi_app
response = self.full_dispatch_request()
File "C:\Python\Python38\Lib\site-packages\flask\app.py", line 1953, in full_dispatch_request
return self.finalize_request(rv)
File "C:\Python\Python38\Lib\site-packages\flask\app.py", line 1970, in finalize_request
response = self.process_response(response)
File "C:\Python\Python38\Lib\site-packages\flask\app.py", line 2269, in process_response
self.session_interface.save_session(self, ctx.session, response)
File "C:\Python\Python38\Lib\site-packages\flask\sessions.py", line 378, in save_session
val = self.get_signing_serializer(app).dumps(dict(session))
File "C:\Python\Python38\Lib\site-packages\itsdangerous\serializer.py", line 166, in dumps
payload = want_bytes(self.dump_payload(obj))
File "C:\Python\Python38\Lib\site-packages\itsdangerous\url_safe.py", line 42, in dump_payload
json = super(URLSafeSerializerMixin, self).dump_payload(obj)
File "C:\Python\Python38\Lib\site-packages\itsdangerous\serializer.py", line 133, in dump_payload
return want_bytes(self.serializer.dumps(obj, **self.serializer_kwargs))
File "C:\Python\Python38\Lib\site-packages\flask\json\tag.py", line 305, in dumps
return dumps(self.tag(value), separators=(",", ":"))
File "C:\Python\Python38\Lib\site-packages\flask\json\__init__.py", line 211, in dumps
rv = _json.dumps(obj, **kwargs)
File "C:\Python\Python38\Lib\json\__init__.py", line 234, in dumps
return cls(
File "C:\Python\Python38\Lib\json\encoder.py", line 199, in encode
chunks = self.iterencode(o, _one_shot=True)
File "C:\Python\Python38\Lib\json\encoder.py", line 257, in iterencode
return _iterencode(o, 0)
File "C:\Python\Python38\Lib\site-packages\flask\json\__init__.py", line 100, in default
return _json.JSONEncoder.default(self, o)
File "C:\Python\Python38\Lib\json\encoder.py", line 179, in default
Open an interactive python shell in this frameraise TypeError(f'Object of type {o.__class__.__name__}
I am making a code that makes a map (not visible), and you can move in it.
I have been working on this code for a week now.
It has a TypeError.
import map
def basicRealm():
player=[0,0]#this is you
Home=[0,0]
Shops=[2,7]
Park=[8,2]
locations = [Home, Shops, Park]
desternation=Park
RealmSize = grid(10)
choice = input("Move north, south, east, or west?[north/south/east/west]")
no = int(input("Number of spaces to move: "))
if choice=='north':
axis=y
elif choice=='south':
axis=y
elif choice=='east':
axis==x
elif choice=='west':
axis=x
else:
pass
nothing=''
if choice=='south' or choice=='east':
no = 0 - no
else:
pass
you_are_here = move(no, player, axis)
basicRealm()
And my map module to run it is :
def atDesternation(location):
global desternation
if desternation==location:
return True
else:
return False
def atLocation(Object,locations):
pos = position(Object)
for i in locations:
if pos==i:
return i
else:
return None
def position(Object):
pos = (Object[0], Object[1])
return pos
def grid(size):
size = ListRange(0, size)
return size
def move(spaces, thing, axis):
here= position(thing)
pos = here[axis] + spaces
return pos
The Output is as follows:
Move north, south, east, or west?[north/south/east/west]north
Number of spaces to move: 1
Traceback (most recent call last):
File "C:\Users\lewis\Desktop\Map1.py", line 35, in <module>
basicRealm()
File "C:\Users\lewis\Desktop\Map1.py", line 29, in basicRealm
print(position(you_are_here))
File "C:\Users\lewis\Desktop\map.py", line 13, in position
pos = (Object[0], Object[1])
TypeError: 'int' object is not subscriptable
>>>
How do I solve this error? Please help.
I am newish to Python and find it very hard to slove Errors.
I declared a global variable in python and still i'm facing error saying that variable is not defined. Can someone please please help me.
def _pick_server (self, key, inport):
global scount1
global scount2
global scount3
server1wt = 4
server2wt = 1
server3wt = 2
liveservers = sorted(self.live_servers.keys())
for i in liveservers:
print(i)
if (scount1 < server1wt):
scount1 += scount1
print(scount1)
print (liveservers[0])
return liveservers[0]
elif (scount2 < server3wt):
scount2 += scount2
print (liveservers[1])
return liveservers[1]
elif (scount3 < server3wt):
scount3 += scount3
print (liveservers[2])
return liverservers[2]
else:
scount1 = 1
scount2 = 0
scount3 = 0
liveservers[0]
The error i'm getting is as below:
Traceback (most recent call last):
File "/home/mininet/pox/pox/lib/revent/revent.py", line 231, in
raiseEventNoErrors
return self.raiseEvent(event, *args, **kw)
File "/home/mininet/pox/pox/lib/revent/revent.py", line 278, in raiseEvent
rv = event._invoke(handler, *args, **kw)
File "/home/mininet/pox/pox/lib/revent/revent.py", line 156, in _invoke
return handler(self, *args, **kw)
File "/home/mininet/pox/ext/ents_loadbalancer.py", line 307, in
_handle_PacketIn
server = self._pick_server(key, inport)
File "/home/mininet/pox/ext/ents_loadbalancer.py", line 203, in _pick_server
if (scount1 < server1wt):
NameError: global name 'scount1' is not defined
your using scount1 before defining it
how can you test its value when it is unknown?
Solution
scount1 = 1
before
if (scount1 < server1wt)
I recently got a raspberry pi and a book to go along with it(Raspberry Pi Cookbook). One of the projects is controlling the GPIO pins on the RPi via a webpage. When I first ran the code after typing it out, I received a bunch of errors so, I tried running the code listed on the books github page:
from bottle import route, run
import RPi.GPIO as GPIO
host = '192.168.1.8'
GPIO.setmode(GPIO.BCM)
led_pins = [18, 23, 24]
led_states = [0, 0, 0]
switch_pin = 25
GPIO.setup(led_pins[0], GPIO.OUT)
GPIO.setup(led_pins[1], GPIO.OUT)
GPIO.setup(led_pins[2], GPIO.OUT)
GPIO.setup(switch_pin, GPIO.IN, pull_up_down=GPIO.PUD_UP)
def switch_status():
state = GPIO.input(switch_pin)
if state:
return 'Up'
else:
return 'Down'
def html_for_led(led):
l = str(led)
result = " <input type='button' onClick='changed(" + l + ")' value='LED " + l + "'/>"
return result
def update_leds():
for i, value in enumerate(led_states):
GPIO.output(led_pins[i], value)
#route('/')
#route('/<led>')
def index(led="n"):
print(led)
if led != "n":
led_num = int(led)
led_states[led_num] = not led_states[led_num]
update_leds()
response = "<script>"
response += "function changed(led)"
response += "{"
response += " window.location.href='/' + led"
response += "}"
response += "</script>"
response += '<h1>GPIO Control</h1>'
response += '<h2>Button=' + switch_status() + '</h2>'
response += '<h2>LEDs</h2>'
response += html_for_led(0)
response += html_for_led(1)
response += html_for_led(2)
return response
run(host=host, port=80)
When I run the code(sudo python web_control.py) I get a invalid literal for int() with base 10: 'favicon.ico' error. Here is the traceback:
Traceback (most recent call last):
File "/usr/lib/python2.7/dist-packages/bottle.py", line 744, in _handle
return route.call(**args)
File "/usr/lib/python2.7/dist-packages/bottle.py", line 1480, in wrapper
rv = callback(*a, **ka)
File "web_control.py", line 42, in index
response += " window.location.href='/' + led"
UnboundLocalError: local variable 'response' referenced before assignment
192.168.0.108 - - [29/Dec/2014 21:31:46] "GET / HTTP/1.1" 500 740
Traceback (most recent call last):
File "/usr/lib/python2.7/dist-packages/bottle.py", line 744, in _handle
return route.call(**args)
File "/usr/lib/python2.7/dist-packages/bottle.py", line 1480, in wrapper
rv = callback(*a, **ka)
File "web_control.py", line 36, in index
led_num = int(led)ValueError: invalid literal for int() with base 10: 'favicon.ico'
Any idea what is going on here? Any help is greatly appreciated.
what does your
print led
show ?
they say that led is not an int so the error could be from there