I keep having this error on my bot program:
start.py:890 local variable 'cmd_part_1' referenced before assignment
Code:
try:
my_alias = message.body.split(" ", 3)
if len(my_alias) > 2:
cmd_part_1 = my_alias[0]
cmd_part_2 = my_alias[1]
elif len(my_alias) < 2:
cmd_part_1 = ""
cmd_part_2 = ""
except Exception as e:
cmd_part_1 = ""
cmd_part_2 = ""
if self.getAccess(user.name.lower()) >= lvl_config.rank_req_callme and cmd_part_1 == "call" and cmd_part_2 == "me":
whole_body = message.body
whole_body = whole_body.replace("call me ", "");
whole_body = whole_body.replace(",", ",");
chat_message("<font color='#%s' face='%s' size='%s'>%s <b>%s</b></font>" % (font_color, font_face, font_size, random.choice(["Recorded! ^_^ I will now call you", "Registah'd, you are now", "Yo, dis mah big homie, I call dem", "Ye-a-a-ah, I guess I can call you that...", "If I have to.. I suppose I'll call you..", "I decided I will call you"]), whole_body), True)
alias_flag = 0
finished_proc = 1
file = open("storage/flatfile/various/aliases.csv", "r")
for line in file.readlines():
alias_data = line.strip()
alias_username, alias_nickname = alias_data.split(",", 1)
Error Line:
if self.getAccess(user.name.lower()) >= lvl_config.rank_req_callme and cmd_part_1 == "call" and cmd_part_2 == "me":
What am I doing wrong?
You have if and elif statements in the first try block that set cmd_part_1.
What happens if none of the conditions in these if statements is True?
In that case, cmd_part_1 will never be assigned a value. This is what is going on in your code. Fix this and it will work. Maybe add an else clause there and assign a default value to both cmd_part_1 and cmd_part_2. Or make one of them have an =.
For example:
if len(my_alias) >= 2:
instead of:
if len(my_alias) > 2:
After that, as eryksun suggested in the comment below, you can replace the elif with an else.
Related
Hello guys I'm trying to creat a function that works similarly to split() function but I'm unable to make it count " " as an item and seperate it
here is my code:
def mysplit(argstr, delimitor):
A = ""
B = []
for i in argstr, delimitor:
if i != " ":
A += i
elif A != "":
B.append(A)
A = ""
if A != "":
B.append(A)
return B
print(mysplit('abc def',' '))
You problem is that your for loop is ill defined.
What are you looping on? You are trying to look at argstr character by character. The delimitor is a constant.
Result:
def mysplit(argstr, delimitor):
A = ""
B = []
for i in argstr:
if i != " ":
A += i
elif A != "":
B.append(A)
A = ""
if A != "":
B.append(A)
return B
print(mysplit('abc def',' '))
Another problem you have is that you aren't actually using the delimitor at all, instead redefining it to be " " in your code. An improvement would be:
def mysplit(argstr, delimitor):
A = ""
B = []
for i in argstr:
if i != delimitor:
A += i
elif A != "":
B.append(A)
A = ""
if A != "":
B.append(A)
return B
print(mysplit('abc def',' '))
It's possible to make your code even cleaner, but this way it should already work properly.
I see that you are insistent on wanting a ' ' in your result array. First I must warn you that this isn't consistent with what str.split does, so if you want to imitate str.split, you shouldn't do that.
But if you want it, here is a simple solution to it:
def mysplit(argstr, delimitor):
A = ""
B = []
for i in argstr:
if i != delimitor:
A += i
elif i == delimitor:
if A != "":
B.append(A)
A = ""
B.append(delimitor)
if A != "":
B.append(A)
return B
print(mysplit('abc def',' '))
because of this line:
for i in argstr, delimitor:
You're telling the for loop to iterate over those two variables, so it takes the entire string in argstr as the first iteration.
replacing it with:
for i in argstr:
does what you want.
Here in this code else block is not printing the value Treasure locked
def counted(value):
if(value == 5):
return 1
else:
return 0
def numb(value1):
sam = 95
value = 0
stp = 97
h = {}
for i in range(0,26):
h.update({chr(stp) : (ord(chr(stp))-sam)})
sam = sam-1
stp = stp+1
for j in range(0,5):
value = h[value1[j]]+value
if(value > 80):
print('First lock-unlocked')
else:
print('Treasure locked')
string = input()
firstcheck = counted(len(string))
if(firstcheck == 1):
numb(string)
a good idea is to check what the condition is before entering the if statements, possibly check what value is printing before the if statement. the logic in def numb() has very little do with what's in def counted(). as long as one is 1 or 0 is being passed to numb() we know that function will run and seems like it.
else block is working properly. if you want to print Treasure Locked. you have to pass lower character string like 'aaaaa'. if value is > 80. then it always print First lock-unlocked.
I know, it's a noob question..
I have these variables:
pgwdth = 30;
mrgn = 0;
fmt = True
And this function:
def Param(x,pgwdth,mrgn,fmt):
parametros = x.split(" ")
if parametros[0][1] == "p":
numerozinho = int(parametros[1])
print "Changing pgwdth"
pgwdth += numerozinho
print pgwdth
elif parametros[0][1] == "m":
numerozinho = int(parametros[1])
print "Changing mrgn"
mrgn += numerozinho
print mrgn
elif parametros[0][1] == "f":
numerozinho = parametros[1]
print "On/Off"
if numerozinho == "on\n":
fmt = True
elif numerozinho == "off\n":
fmt = False
else:
"Error"
print fmt
else:
print "Error"
I just want it to return the variables that it used as arguments after changing it.
return x,pgwdth,mrgn,fmt
Simple as that.
And where you call it:
val1,val2,val3,val = Param(x,pgwdth,mrgn,fmt)
A function returns exactly one result. The trick is to make that result a tuple containing the multiple values.
return (x, pgwdth, mrgn, fmt)
In Python syntax the braces around the tuple are optional so you'll more often see
return x, pgwdth, mrgn, fmt
Which looks like returning multiple values, but now it's clear there is really just one return value
My task is to define a procedure is_palindrome, that takes as input a string, and returns a boolean indicating if the input string is a palindrome. In this case a single letter should return True, as should an empty string ''.
Unfortunately, I'm not getting the expected results. I appreciate the help.
My code version 1:
def is_palindrome(s):
if s == '':
return True
else:
if (ord(s[0]) - ord(s[len(s)-1])) == 0:
is_palindrome(s[1:len(s)-1])
else:
return False
print is_palindrome('')
#>>> True (expected = True)
print is_palindrome('abab')
#>>> False (expected = False)
print is_palindrome('abba')
#>>> None (expected = True)
print is_palindrome('andrea')
#>>> None (expected = False)
print is_palindrome('abaaba')
#>>> None (expected = True)
I followed my code through the debugger and it seems the logic is correct as the code takes the appropriate path. However, the end result seems to switch to 'None' for some of the cases as highlighted above.
If I change my code to the following:
My code version 2:
def is_palindrome(s):
if s == '':
result = True
else:
if (ord(s[0]) - ord(s[len(s)-1])) == 0:
is_palindrome(s[1:len(s)-1])
else:
result = False
return result
print is_palindrome('')
#>>> True (expected = True)
print is_palindrome('abab')
#>>> False (expected = False)
print is_palindrome('abba')
#>>> Error (expected = True)
UnboundLocalError: local variable 'result' referenced before assignment
print is_palindrome('andrea')
#>>> Error (expected = False)
UnboundLocalError: local variable 'result' referenced before assignment
print is_palindrome('abaaba')
#>>> Error (expected = True)
UnboundLocalError: local variable 'result' referenced before assignment
In your first example, you forgot a return statement:
def is_palindrome(s):
if s == '':
return True
else:
if (ord(s[0]) - ord(s[len(s)-1])) == 0:
# v-- forgot this here
return is_palindrome(s[1:len(s)-1])
else:
return False
is_palindrome(s[1:len(s)-1])
needs to be...
return is_palindrome(s[1:len(s)-1])
in your first version, or
result = is_palindrome(s[1:len(s)-1])
in your second. Otherwise, you never actually propagate the recursive call's return value back to the original caller.
# ask user to enter any string
a = raw_input("Enter the string : ")
#palindrome check
print (a == a[::-1]) and "String is palindrome" or "String is not palindrome"
Let's step through your second example, line by line.:
def is_palindrome(s):
In this case let's let s = "abba", which is the first string you got an error on:
if s == '':
is evaluated as
if 'abba' == '':
Which is False, so we skip ahead to else:
else:
if (ord(s[0]) - ord(s[len(s)-1])) == 0:
This if statement is equivalent to:
if (97 - 97) == 0:
It's True, so recursion happens:
is_palindrome(s[1:len(s)-1])
or
is_palindrome('bb')
Now whatever is the result of this recursion, we ignore it, because the return value is not saved. Thus, when we get to this line:
return result
We never defined what result was, so Python flips out.
Other posters already did an excellent job of answering your question. I'm posting to demonstrate the importance of tracing a program to find/fix bugs.
def is_palindrome(s):
if not s:
return True
else:
return s[0]==s[-1] and is_palindrome(s[1:-1])
or, if you want a one-liner:
def is_palindrome(s):
return (not s) or (s[0]==s[-1] and is_palindrome(s[1:-1]))
Hope that helps
Respuesta en Java
public class Varios {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
System.out.println( pali("anitalavalatina"));
}
static boolean pali(String palabra){
System.out.println(palabra);
if (palabra.length()-1<2)
return true;
if(palabra.charAt(0)!=palabra.charAt(palabra.length()-1)) return false;
return pali(palabra.substring(1,palabra.length()-1));
}
}
I'm a bit new in programming with python, but I have do this code:
dimValue = 0
........
elif event[0] == "control" and body["location"] == location and body["action"] == "on":
auxValue = int(body["dim"])
print("AuxValue = " + str(auxValue))
if auxValue > dimValue:
print("entrou")
dimControl=auxValue-dimValue
print("DimControl = " + str(dimControl))
dimValue = auxValue
os.system("heyu bright A1 "+ str(dimControl))
elif dimValue > auxValue:
print("saiu")
dimControl=dimValue-auxValue
dimValue = auxValue
os.system("heyu dim A1 "+ str(dimControl))
With this code, if int(body["dim"]) is 5, just show the first print, and don't enter in the if else statement. If I comment this line "dimValue = auxValue", it enters in the if else, and do everything well. But I need to put this line. What I'm doing wrong?
Thanks.
Hugo Silva
It sounds like neither the if block nor the elif block are being entered. This probably occurs when auxValue equals dimValue; then neither of the criteria evaluate to true. You could change > to >= or change < to <=, depending on which block you want to run when they are equal.