python error get object value - python

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.

Related

if, elif & !=, == boolean operations only return "false" with inputs

I am creating an Among Us ripoff (for fun!) and the while True & if/elif/else statements will only return false (not An Impostor) with the inputs. I had created a list for the names and 2 random elements from the list will be chosen as An Impostor. However, whenever I input a name that is The Impostor, it will only return
(player) was not An Impostor.
Here is my code;
import sys, time, random
names = ["player1", "player2", "player3", "player4", "player5", "player6", "player7", "player8", "player9", "player10"]
print("Players: ")
for x in names:
print(x)
print('—————————————————————————')
impostor1 = random.choice(names)
impostor2 = random.choice(names)
crewmates = 8
impostors = 2
tries = 6
while True:
talk = input("Guess who The Impostor(s) are. " + str(crewmates) + " Crewmates are left. " + str(impostors) + " Impostors are left. You have " + str(tries) + " tries left.")
if talk in names:
print(talk + " was voted for.")
time.sleep(0.1)
if talk != impostor1 or talk != impostor2:
notimp = talk + " was not An Impostor. "
names.remove(talk)
for y in notimp:
sys.stdout.write(y)
sys.stdout.flush()
time.sleep(0.05)
crewmates -= 1
tries -= 1
elif talk == impostor1 or talk == impostor2:
wasimp = talk + " was An Impostor. "
names.remove(talk)
for v in wasimp:
sys.stdout.write(v)
sys.stdout.flush()
time.sleep(0.1)
impostors -= 1
else:
print("That player was either ejected or is not a valid player.")
However, whenever I put the Impostor in the input, it says it isn't An Impostor?
I think this line is the source of the problem:
if talk != impostor1 or talk != impostor2:
Let's say impostor1 is player1 and impostor2 is player2 and someone input in player1, according to Python Boolean expression operator or that if statement will evaluate like this:
if player1 != impostor1 evaluated to False because player1 is indeed equals to impostor1.
So far so good, but because the first test is a False, Python simply evaluates and returns the right side operand which may be either True or False. In your case Python will evaluate if talk != impostor2 and return True, thereafter executes the nested block.

Python else block doesn't print anything

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.

Python Can't find string in file

I started working on my game few days ago. I made system for loading(on start) and saving(on exit). On first loging in everything is fine but on second error(NameError: name 'strange' is not defined) showed up. Can someone help me to solve it please? I know that problem is in finding name in file becouse I tryed to put else statment after everything under
elif ab.read().find(a) != -1:
and that what I put under else worked but it was just print so other required didn't worked under else.
Here's my program:
import sys, random, time, re
print("Welcome to game Special Travel Adventure!")
def con(a, b):
return a.lower() == b.lower()
a = str(input("If you want to continue with game type your name here: "))
ab = open("STAPlayers.txt", "r+")
if ab.read().find(a) == -1:
if ab.read() == "":
ac = "Name:" + a + ":Strange:" + "0" + ":Courage:" + "0" + ":Skills:" + "0" + ":Money:" + "0" + ":Level:" + "0" + ":Deaths:" + "0"
ab.write(ac)
strange = 0
courage = 0
skills = 0
money = 0
level = 0
deaths = 0
else:
ac = "\nName:" + a + ":Strange:" + "0" + ":Courage:" + "0" + ":Skills:" + "0" + ":Money:" + "0" + ":Level:" + "0" + ":Deaths:" + "0"
ab.write(ac)
strange = 0
courage = 0
skills = 0
money = 0
level = 0
deaths = 0
elif ab.read().find(a) != -1:
readdd = ab.readlines()
for line in readdd:
if line.find(a) != -1:
zm = line.split(":")
zm.remove("Name")
zm.remove("Strange")
zm.remove("Courage")
zm.remove("Skills")
zm.remove("Money")
zm.remove("Level")
zm.remove("Deaths")
strange = int(zm[1])
courage = int(zm[2])
skills = int(zm[3])
money = int(zm[4])
level = int(zm[5])
deaths = int(zm[6])
ab.close()
def levelc():
if courage and strange and skills == 1:
level += 1
return True
if courage and strange and skills == 2:
level += 1
return True
if courage and strange and skills == 3:
level += 1
return True
if courage and strange and skills == 4:
level += 1
return True
if courage and strange and skills == 5:
level += 1
return True
else:
return False
b = input("Start Menu\nSelect: Start, Upgrades, Exit. ")
while b != "dont save":
if con(b, "Exit"):
aj = open("STAPlayers.txt", "r")
lines = aj.readlines()
aj.close()
aj = open("STAPlayers.txt", "w")
jmj = "Name:" + a + ":Strange:" + str(strange) + ":Courage:" + str(courage) + ":Skills:" + str(skills) + ":Money:" + str(money) + ":Level:" + str(level) + ":Deaths:" + str(deaths)
for linee in lines:
if str(a) not in linee:
aj.write(linee)
elif str(a) in linee:
jmjm = jmj + "\n"
aj.write(jmjm)
aj.close()
sys.exit()
break
I know that problem is in finding name in file becouse I tryed to put else statment after everything under
elif ab.read().find(a) != -1:
and that what I put under else worked but it was just print so other required didn't worked under else. Please help.
Your problem is you are trying to read the file twice. You can only read a file once (without resetting to the beginning of the file). Try this:
ab_read = ab.read()
if ab_read.find(a) == -1:
...
elif ab_read.find(a) != -1:
...
Although, you might be better off using if a in ab_read: and then an else. Also, you might consider more meaningful variable names than ab or a.
To answer the next question you will have: your call to readdd = ab.readlines() will fail for the same reason multiple calls to ab.read() fail. You can get the same information with readdd = ab_read.splitlines()
In general, you are reading files way too often. Reading from files is a slow and resource consuming operation in any language. You chould consider reading the same file multiple times a very poor programming practice. You should refactor your code to only read each file once, and that should fix most of your issues.

Python: Why does it keep saying invalid syntax?

I wrote this program in order to be able to find the number of A/U and C/G pairs from the users input. When I run it, it keeps saying "Invalid Syntax" while highlighting the first "else:" after the while loop in red. Anyone know what I need to change to fix it?
def main():
first = input("Please enter the RNA sequence for which you wish to find the number of pairs. \nFirst line:")
second = input("Second String:")
a1base = first.count('A')
u1base = first.count('U')
c1base = first.count('C')
g1base = first.count('G')
a2base = second.count('A')
u2base = second.count('U')
c2base = second.count('C')
g2base = second.count('G')
while (a1base >= 1) and (u1base >= 1) or (a2base >= 1) and (u2base >= 1):
abases = (a1base+ a2base)
ubases = (u1base + u2base)
firstset = min(abases, ubases)
print("You have", firstset,"A/U bases.")
else:
print("You have zero A/U bases.")
while (c1base >= 1) and (g1base >= 1) or (c2base >= 1) and (g2base >= 1):
cbases = (c1base + c2base)
gbases = (g1base + g2base)
secondset = min(cbases, gbases)
print("You have", secondset,"C/G bases.")
else:
print("You have zero C/G bases.")
main()
You have an else: that isn't attached to any if, for, while, or try statement, which is illegal.
If you meant for the else to be attached to the while, the solution is simple: Change the indentation to attach it:
while (a1base >= 1) and (u1base >= 1) or (a2base >= 1) and (u2base >= 1):
abases = (a1base+ a2base)
ubases = (u1base + u2base)
firstset = min(abases, ubases)
print("You have", firstset,"A/U bases.")
else:
print("You have zero A/U bases.")
See break and continue Statements, and else Clauses on Loops in the tutorial (and Compound statements in the language reference for full details).
Your else needs to be indented at the same level as your while, which doesn't really make sense in this case because there's no break in your loop, or you need to add an if on some line before it.
I see two obvious things:
Everything after def main(): should be indented;
Else should be at the same level of indentation as while. It is not a child, but a sibling of while.
Others have already explained the error.
Try changing you while loops to this:
abases = (a1base+ a2base)
ubases = (u1base + u2base)
firstset = min(abases, ubases)
print("You have", firstset if firstset else 'zero',"A/U bases.")
cbases = (c1base + c2base)
gbases = (g1base + g2base)
secondset = min(cbases, gbases)
print("You have", secondset if secondset else 'zero',"C/G bases.")
Without any while or else:.
Also the following snippet should do the same thing:
first = input("Please enter the RNA sequence for which you wish to find the number of pairs. \nFirst line:")
second = input("Second String:")
bases = {k: (first + second).count(k) for k in 'AUCG'}
print('You have', min(bases['A'], bases['U']), 'A/U bases.')
print('You have', min(bases['C'], bases['G']), 'C/G bases.')

variable 'cmd_part_1' referenced before assignment

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.

Categories

Resources