Why does this code not work? I think it's something to do with x1 being already defined because I get the error "UnboundLocalError: local variable 'x1' referenced before assignment" whenever I click b1. Please I've searched the entire Internet with no luck.... Sorry I'm relatively new to Python and programming.
import calendar
import datetime
from kivy.app import App
from kivy.uix.label import Label
from kivy.uix.button import Button
from kivy.uix.gridlayout import GridLayout
from kivy.uix.label import Label
now = datetime.datetime.now()
h = now.hour
m = now.minute
s = now.second
year = now.year
month = now.month
day = now.day
home = 'home.'
weekday1 = calendar.weekday(year, month, day)
if len(str(m)) == 1:
zero = '0'
else:
zero = ''
if len(str(s)) == 1:
zero1 = '0'
else:
zero1 = ''
if weekday1 == 0:
day = 'Monday'
time = '''Period 1/2/3/4 = History
Period 5/6 = Japanese'''
if h == 8 and m >= 40:
current = 'Homeroom.'
elif h == 9 or (h == 10 and m <= 40):
current = 'History.'
elif h == 10 and m > 40:
current = 'recess.'
elif h == 11 or (h == 12 and m <= 40):
current = 'History.'
elif (h == 12 and m > 40) or (h == 13 and m <= 20):
current = 'lunch.'
elif (h == 13 and m > 20) or h == 14:
current = 'Japanese.'
else:
current = home
elif weekday1 == 1:
day = 'Tuesday'
time = '''Period 1 = English
Period 2 = Maths
Period 3/4 = English
Period 5/6 = ICT'''
if h == 8 and m>= 40:
current = 'Homeroom.'
elif h == 9 and m <= 50:
current = 'English.'
elif (h == 9 and m > 50) or (h == 10 and m <= 40):
current = 'Maths.'
elif h == 10 and m > 40:
current = 'recess.'
elif h == 11 or (h == 12 and m <= 40):
current = 'English.'
elif (h == 12 and m > 40) or (h == 13 and m <= 20):
current = 'lunch.'
elif (h == 13 and m > 20) or h == 14:
current = 'ICT.'
else:
current = home
elif weekday1 == 2:
day = 'Wednesday'
time = '''Period 1/2 = Science Extended
Period 3 = English
Period 4 = Maths
Period 5/6 = Science'''
if h == 8 and m >= 40:
current = 'Homeroom.'
elif h == 9 or (h == 10 and m <= 40):
current = 'Science Extended.'
elif h == 10 and m > 40:
current = 'recess.'
elif h == 11 and m <= 50:
current = 'English.'
elif (h== 11 and m > 50) or (h == 12 and m <= 40):
current = 'Maths.'
elif (h == 12 and m > 40) or (h == 13 and m <= 20):
current = 'lunch.'
elif (h == 13 and m > 20) or h == 14:
current = 'Science.'
else:
current = home
elif weekday1 == 3:
day = 'Thursday'
time = '''Period 1/2 = Art
Period 3 = Science
Period 4 = Wellbeing
Period 5 = English
Period 6 = Maths'''
if h == 8 and m >= 40:
current = 'Homeroom.'
elif (h == 10 and m <= 40) or h == 9:
current = 'Art.'
elif h == 10 and m > 40:
current = 'recess.'
elif h == 11 and m <= 50:
current = 'Science.'
elif (h == 11 and m > 50) or (h == 12 and m <= 40):
current = 'Wellbeing.'
elif (h == 12 and m > 40) or (h == 13 and m < 20):
current = 'lunch.'
elif (h == 13 and m >= 20) or (h == 14 and m <= 10):
current = 'English.'
elif h == 14 and m > 10:
current = 'Maths.'
else:
current = home
elif weekday1 == 4:
day = 'Friday'
time = '''Period 1/2 = PE
Period 3 = English
Period 4 = Maths
Period 5/6 = Music'''
if h == 8 and m >= 40:
current = 'Homeroom.'
elif h == 9 or (h == 10 and m <= 40):
current = 'PE.'
elif h == 10 and m > 40:
current = 'recess.'
elif h == 11 and m <= 50:
current = 'English.'
elif (h == 11 and m > 50) or (h == 12 and m <= 40):
current = 'Maths.'
elif (h == 12 and m > 40) or (h == 13 and m < 20):
current = 'lunch.'
elif (h == 13 and m >= 20) or h == 14:
current = 'Music.'
else:
current = home
else:
day = 'a weekend'
time = 'You have none.'
if day == 'a weekend':
a = "You don't have to be anywhere."
else:
a = ('You should be at ' + current)
a1 = ('Today is ' + day + '.')
a2 = ('''Today your timetable is:
''' + time)
a3 = ('The current time is ' + str(h) + ':' + zero + str(m) + ':' + zero1 + str(s) + '.')
t1 = 'What is the day today?'
t2 = 'What is the current time?'
t3 = 'What is my timetable today?'
t4 = 'Where should I be?'
x1, x2, x3, x4 = '', '', '', ''
def callback1(object):
del x1
x1 = a1
def callback2(object):
x2 = a3
def callback3(object):
x3 = a2
def callback4(object):
x4 = a
b1 = Button(text = t1)
b1.bind(on_press = callback1)
layout = GridLayout(cols = 2)
layout.add_widget(b1)
layout.add_widget(Label(text = x1))
layout.add_widget(Button(text = t2))
layout.add_widget(Label(text = x2))
layout.add_widget(Button(text = t3))
layout.add_widget(Label(text = x3))
layout.add_widget(Button(text = t4))
layout.add_widget(Label(text = x4))
class TimeTable(App):
def build(self):
return layout
if __name__ == '__main__':
TimeTable().run()
Your error is because you try to delete a global variable (x1) in a local context (callback1), without declaring it as global before.
You could do:
global x1
del x1
But there is a more general issue with what you are trying to accomplish, when you say text = x1, it just passes the current value of x1 to the text property of the Label you create, and changing the value of x1 later has no effect on this, what you want is to change widget.text to the new value (and you should rename object to widget in these callbacks, object is the name of the base class in python, so you shouldn't use it as a parameter or anything).
Also, the way you structure your code won't work well in the long term, you should do more things in methods of your class (most of what you do before could be done in build).
Related
I need to get all roots of a scalar equation. But fsolve can only return 1 root for each call. So I design a self-call function find_root_recursively of fsolve. This function will call itself until the new root is equal the previous root, which means fsovle has found all roots and no more new roots will be added. I use this logic to end self calling. But in some cases fsolve will return a root which is exactly the same as starting point. one_root = start always. Obviously this start is not a root. So the list_root is always adding new roots, it never ends.
min_value = df_group['strike'].min()
start_point = int(float(min_value) * 0.8)
def find_root_by_small_step(function, start_0, increment):
start = start_0
one_root = fsolve(function, start)
def get_transaction_data(self, expiry_date, df_group):
return df_group[df_group['expiration_date'] == expiry_date].loc[(df_group['type'] == 1) & (df_group['position'] == 1)], \
df_group[df_group['expiration_date'] == expiry_date].loc[(df_group['type'] == 1) & (df_group['position'] == 0)], \
df_group[df_group['expiration_date'] == expiry_date].loc[(df_group['type'] == 0) & (df_group['position'] == 1)], \
df_group[df_group['expiration_date'] == expiry_date].loc[(df_group['type'] == 0) & (df_group['position'] == 0)]
def calculate_one_payoff(self, stock_price, df_long_call, df_short_call, df_long_put, df_short_put):
# buy call
df_buy_call_executed = df_long_call[stock_price >= df_long_call['strike']]
if len(df_buy_call_executed) > 0:
buy_call_executed_sum = ((stock_price - df_buy_call_executed['breakeven_price']) * df_buy_call_executed['option_amount']).sum()
else:
buy_call_executed_sum = 0
df_buy_call_noExec = df_long_call[stock_price < df_long_call['strike']]
if len(df_buy_call_noExec) > 0:
buy_call_noExec_sum = (-1 * df_buy_call_noExec['option_price'] * df_buy_call_noExec['option_amount']).sum()
else:
buy_call_noExec_sum = 0
# sell call
df_sell_call_executed = df_short_call[stock_price >= df_short_call['strike']]
if len(df_sell_call_executed) > 0:
sell_call_executed_sum = ((df_sell_call_executed['breakeven_price'] - stock_price) * df_sell_call_executed['option_amount']).sum()
else:
sell_call_executed_sum = 0
df_sell_call_noExec = df_short_call[stock_price < df_short_call['strike']]
if len(df_sell_call_noExec) > 0:
sell_call_noExec_sum = (df_sell_call_noExec['option_price'] * df_sell_call_noExec['option_amount']).sum()
else:
sell_call_noExec_sum = 0
# buy put
df_buy_put_executed = df_long_put[stock_price < df_long_put['strike']]
if len(df_buy_put_executed) > 0:
buy_put_executed_sum = ((df_buy_put_executed['breakeven_price'] - stock_price) * df_buy_put_executed['option_amount']).sum()
else:
buy_put_executed_sum = 0
df_buy_put_noExec = df_long_put[stock_price >= df_long_put['strike']]
if len(df_buy_put_noExec) > 0:
buy_put_noExec_sum = (-1 * df_buy_put_noExec['option_price'] * df_buy_put_noExec['option_amount']).sum()
else:
buy_put_noExec_sum = 0
# sell put
df_sell_put_executed = df_short_put[stock_price < df_short_put['strike']]
if len(df_sell_put_executed) > 0:
sell_put_executed_sum = ((stock_price - df_sell_put_executed['breakeven_price']) * df_sell_put_executed['option_amount']).sum()
else:
sell_put_executed_sum = 0
df_sell_put_noExec = df_short_put[stock_price >= df_short_put['strike']]
if len(df_sell_put_noExec) > 0:
sell_put_noExec_sum = (df_sell_put_noExec['option_price'] * df_sell_put_noExec['option_amount']).sum()
else:
sell_put_noExec_sum = 0
one_stock_price_sum = buy_call_executed_sum + buy_call_noExec_sum + sell_call_executed_sum + sell_call_noExec_sum + \
buy_put_executed_sum + buy_put_noExec_sum + sell_put_executed_sum + sell_put_noExec_sum
one_stock_price_sum = float(one_stock_price_sum)
return one_stock_price_sum
df_long_call, df_short_call, df_long_put, df_short_put = self.get_transaction_data(expiry_date, df_group)
find_root_by_small_step(function=calculate_one_payoff, start=start_point, increment=increment)
ticker type position expiration_date strike option_price option_amount breakeven_price
AAPL 1 0 2021-11-19 145.0000 5.1700 2500.0000 150.1700
AAPL 0 1 2021-11-19 145.0000 2.9700 2500.0000 142.0300
AAPL 0 1 2021-11-19 145.0000 2.7000 5000.0000 142.3000
AAPL 1 1 2021-11-19 145.0000 5.8500 5000.0000 150.8500
AAPL 1 1 2021-11-19 155.0000 1.6000 1050.0000 156.6000
True root = 139.9 and 159.0
When trying to launch the program, I get the "IndexError: string index out of range" error on line 19. Is it because I forgot to terminate the string or turn it back to int? Very new to python, so any help or trivia would be appreciated.
I tried doing something like thisdoubleCheck = int(strNumber[i] * 2) , but it did not solve the problem. Am I doing it wrong?
Here is the full code just in case of later errors.
from cs50 import get_int
import sys
ccNumber = get_int("Number: ")
strNumber = str(ccNumber)
Numlen = len(str(ccNumber))
if Numlen != 13 and Numlen != 15 and Numlen != 16:
sys.exit()
firstSum = 0
secondSum = 0
doubleCheck = 0
for i in range(Numlen, -1, -1):
if i % 2 == 0:
secondSum = secondSum + strNumber[i]
if i % 2 == 1:
doubleCheck = strNumber[i] * 2
if doubleCheck >= 10:
firstSum = firstSum + (doubleCheck % 10)
firstSum = firstSum + (doubleCheck / 10)
else:
firstSum += doubleCheck;
totalChecksum = firstSum + secondSum
if totalChecksum % 10 == 0:
if strNumber[0] == 3 and Numlen == 15:
if strNumber[1] == 4 or strNumber[1] == 7:
print("AMEX", end="");
elif strNumber[0] == 4:
if Numlen == 13 or Numlen == 16:
print("VISA", end="")
elif strNumber[0] == 5 and Numlen == 16:
if strNumber[1] == 1 or strNumber[1] == 2 or strNumber[1] == 4 or strNumber[1] == 5:
print("MASTERCARD", end="")
else:
print("INVALID", end="")
Python string indexing starts at 0. For an N-length string, valid indexes are 0 through N-1. Index N is out of range.
In the for loop, you're accessing strNumber[i]. On the first iteration, i is equal to Numlen, which is out of range.
Perhaps you intended to start the loop at Numlen - 1?
hello I try to make an app- personality test, but i have a problem with evaluation,..
there is a dificult evaluation of test but in short in theese reduce version you just write some values into a given variable, and i want to delete every 0 value from list as a result.. I tried it (programe after # but there is an error), could anybody please help me?
error
File "C:/Users/Stanko/PycharmProjects/pythonProjectDISK/main.py", line 73, in dele
self._data[self.item.key]= list(filter(lambda num: num != 0, self._data[self.item.key]))
AttributeError: 'Test' object has no attribute 'item'
here is a reduce program
class Empty(Exception):
pass
class PriorityVal(ABC):
class _Item:
def __init__(self, key, value):
self.key, self.value = key, value
def __lt__(self, other):
return self.key < other.key
def __repr__(self):
return str((self.key, self.value))
#abstractmethod
def add(self, key, value):
pass
#abstractmethod
def max(self):
pass
#abstractmethod
def min(self):
pass
#abstractmethod
def remove_min(self):
pass
class Test(PriorityVal):
def __init__(self):
self._data = []
def add(self, key, value):
self._data.append(self._Item(key, value))
def max(self):
index = self.find_max()
item = self._data[index]
return item.key, item.value
def find_max(self):
index = 0
for i in range(1, len(self._data)):
if self._data[index] < self._data[i]:
index = i
return index
def _find_min(self):
index = 0
for i in range(1, len(self._data)):
if self._data[i] < self._data[index]:
index = i
return index
def min(self):
index = self._find_min()
item = self._data[index]
return item.key, item.value
def remove_min(self):
index = self._find_min()
item = self._data.pop(index)
return item.key, item.value
def dele(self):
self._data[self.item.key]= list(filter(lambda num: num != 0, self._data[self.item.key]))
test = str(input("test name"))
test = Test()
dzadane = int(input("input d"))
if dzadane <= 0:
dh = 0
elif 0 < dzadane <= 4:
dh = 60
elif 4 < dzadane <= 7:
dh = 70
elif 7 < dzadane <= 12:
dh = 80
elif 12 < dzadane <= 15:
dh = 90
else:
dh = 100
test.add(dh, "d")
izadane = int(input("input i"))
if izadane <= -1:
ih = 0
elif -1 < izadane <= 1:
ih = 60
elif 1 < izadane <= 3:
ih = 70
elif izadane == 4:
ih = 75
elif 4 < izadane <= 6:
ih = 80
elif izadane == 7:
ih = 85
elif 7 < izadane <= 9:
ih = 90
else:
dh = 100
test.add(ih, "i")
szadane = int(input("input s"))
if szadane <= -2:
sh = 0
elif -2 < szadane <= 0:
sh = 60
elif 0 < szadane <= 3:
sh = 70
elif 4 < szadane <= 7:
sh = 80
elif szadane == 8:
sh = 85
elif 8 < szadane <= 10:
sh = 90
else:
sh = 100
test.add(sh, "s")
kzadane = int(input("input k"))
if kzadane <= -3:
kh = 0
elif -3 < kzadane <= 1:
kh = 60
elif -1 < kzadane <= 1:
kh = 70
elif 1 < kzadane <= 4:
kh = 80
elif 4 < kzadane <= 7:
kh = 90
else:
kh = 100
test.add(kh, "k")
nzadane = int(input("input n"))
nh = 0
test.add(nh, "n")
print(dzadane, izadane, szadane, kzadane, nzadane, )
print("test", test._data)
print('max=', test.max())
print( "del all 0", test.dele())
print("test", test._data)
You could try
self._data = [value for value in self._data if value.key != 0]
I'm trying to make a factoring program, but it doesn't seem to work with negative number a-, b- and c-inputs.
from fractions import gcd
factor = -1
opp = 0
number = 1
success = 0
a = int(input("a-value: "))
b = int(input("b-value: "))
c = int(input("c-value: "))
factors = []
d = 0
e = 0
while number <= abs(a*c):
#Checking for multiples
if abs(a*c) % number == 0:
factor += 1
factors.append(number)
number += 1
while (factor-opp) >= 0:
#Checking for actual factors
d = int(factors[factor])
e = int(factors[opp])
if (abs(d+e) or abs(d-e)) == abs(b):
success += 1
break
else:
factor -= 1
opp += 1
if success > 0:
if (d+e) == b:
e = e
elif (d-e) == b:
e -= 2*e
elif (e-d) == b:
d -= 2*d
elif (-d-e) == b:
d -= 2*d
e -= 2*e
#Figuring out the equation
if d % a == 0:
d /= a
f = 1
else:
f = a/gcd(d,a)
d /= gcd(d,a)
if e % a == 0:
e /= a
g = 1
else:
g = a/gcd(e,a)
e /= gcd(e,a)
#Displaying the answer
if d >= 0:
d = str("+" + str(int(d)))
if e >= 0:
e = str("+" + str(int(e)))
elif e < 0:
e = str(int(e))
else:
d = str(int(d))
if e >= 0:
e = str("+" + str(int(e)))
elif e < 0:
e = str(int(e))
if f == 1:
if g == 1:
print ("(x" + d + ")(x" + e + ")")
else:
g = str(int(g))
print ("(x" + d + ")(" + g + "x" + e + ")")
elif g == 1:
f = str(int(f))
print ("(" + f + "x" + d + ")(x" + e + ")")
else:
f = str(int(f))
g = str(int(g))
print ("(" + f + "x" + d + ")(" + g + "x" + e + ")")
else:
print("This equation cannot be factored into integers.")
More specifically, the problem is somewhere within this block, I think. I've tested it out with print statements:
while (factor-opp) >= 0:
#Checking for actual factors
d = int(factors[factor])
e = int(factors[opp])
if (abs(d+e) or abs(d-e)) == abs(b):
success += 1
break
else:
factor -= 1
opp += 1
I've searched everywhere: my programming textbook, online searches about inputting negatives, everything. What am I doing wrong here?
Ok I am able to reproduce your issue for a simple testcase like - a=1 , b=0, c=-4 .
The issue is in the line -
if (abs(d+e) or abs(d-e)) == abs(b):
This does not check whether abs(b) is equal to abs(d+e) or abs(d-e) , instead it first evaluates the result of (abs(d+e) or abs(d-e)) , which would return the first non-zero result , and then compare that against abs(b) , so for negative numbers this does not evaluate the result correctly. Change that condition to -
if abs(d+e) == abs(b) or abs(d-e) == abs(b):
or you can also use a set -
if abs(b) in {abs(d+e), abs(d-e)}: #Though I doubt if using set would give any performance improvement because of the overhead of creating a set.
Demo after changes -
a-value: 1
b-value: 0
c-value: -4
(x+2)(x-2)
a-value: 1
b-value: -1
c-value: -6
(x-3)(x+2)
One more thing, there is something you have not considered , when a=-1 , b=-4 , c=-4 , the result should come to -(x+2)(x+2) , but the current program results in (x+2)(x+2) .
I'm just starting out with python and I'm trying to make a little archery game. However, it creates an error at this point: d = math.sqrt(x*x + y*y) (i.e. the distance between the new point and the original center of the cirlce) Any ideas on why this doesn't work?
def archery():
win = GraphWin("Archery Game", 500,500)
win.setCoords(-50, -50, 50, 50)
circle1 = Circle(Point(0,0), 40)
circle1.setFill("white")
circle1.draw(win)
circle2 = Circle(Point(0,0), 35)
circle2.setFill("black")
circle2.draw(win)
circle3 = Circle(Point(0,0), 30)
circle3.setFill("blue")
circle3.draw(win)
circle4 = Circle(Point(0,0), 25)
circle4.setFill("red")
circle4.draw(win)
circle5 = Circle(Point(0,0), 20)
circle5.setFill("yellow")
circle5.draw(win)
score = 0
for i in range(5):
p = win.getMouse()
p.draw(win)
x = p.getX
y = p.getY
d = math.sqrt(x*x + y*y)
if 40 >= d > 35:
score = score + 1
elif 35 >= d > 30:
score = score + 3
elif 30 >= d > 25:
score = score + 5
elif 25 >= d > 20:
score = score + 7
elif 20 >= d >= 0:
score = score + 9
else:
score = score + 0
print("Your current score is:", score)
win.getMouse()
win.close()
x = p.getX
y = p.getY
will return the function getX and getY instead of executing it. As Mike Steder said, try getX(), that should return a value.
First, you probably need to do:
x = p.getX()
y = p.getY()
i.e. call the functions and use the return value, instead of using the functions themselves.
Second, you can change the math.sqrt(x*x + y*y) call to:
d = math.hypot(x, y)