I am struggling to understand the following error in the code block below:
if o == None or t == None:
try:
elif o == 1 and t == 1:
c1 = c1 + 1
elif o == -1 and t == -1:
c2 = c2 + 1
elif o == -1 and t == 1:
i1 = i1 + 1
elif o == 1 and t == -1:
i2 = i2 + 1
return (c1, i1, c2, i2)
Error :
elif o == 1 and t == 1:
^
Syntax error : invalid syntax
Can anyone point out what am I doing wrong? I followed correct indentation in the program.
You appear to have a naked try in your code which is very much stuffing up the layout of your program.
You can certainly try within a code block of an if statement, but you need to provide the entire thing, something like:
if somethingOrOther():
try:
xyzzy = 42
except:
pass
elif ...
This is the structure of your code correctly indented, so maybe now it's obvious what the problem is?
if o == None or t == None:
try:
elif o == 1 and t == 1:
c1 = c1 + 1
elif o == -1 and t == -1:
c2 = c2 + 1 elif o == -1 and t == 1:
i1 = i1 + 1
elif o == 1 and t == -1:
i2 = i2 + 1
return (c1, i1, c2, i2)
Once you fix your indentation
if o == None or t == None:
try:
elif o == 1 and t == 1:
c1 = c1 + 1
elif o == -1 and t == -1:
......
your code will still not work. Note how the elif is at a different indentation from the if.
You cannot splice a try into the middle of an if statement. All the elif statements must be at the same nesting/indentation level. Therefore if you open a try block inside an if or elif, you must complete it before completing that if or elif.
You'll need it like this:
try:
if o is None or t is None:
pass
elif o == 1 and t == 1:
c1 = c1 + 1
elif o == -1 and t == -1:
......
Another point to make is not to compare against None using the equality operator. You should use is when comparing against the singleton None:
if o is None or t is None:
Your code is correct just the format is wrong.
Nothing to serious but format is highly effective in python, the wrong amount of whitespaces and it could ruin your entire code. Organization and punctuation with semicolons are also key.
Here is the right format.
if o == None or t == None:
try:
elif o == 1 and t == 1:
c1 = c1 + 1
elif o == -1 and t == -1:
c2 = c2 + 1
elif o == -1 and t == 1:
i1 = i1 + 1
elif o == 1 and t == -1:
i2 = i2 + 1
except:
...
return (c1, i1, c2, i2)
Great question! This will be used throughout all the time stack overflow is around. Keep it up!
Related
My Problem is on line 25 when it says
if conformation == 1:
for i in range(l, len(lines[k]), 1):
if lines[k][i].isdigit() or lines[k][i].istitle():
f += lines[k][i]
if f in var:
print(var[f])
What my issue is is that the "f" string isn't being added to and its value stays as "". For context, I'm trying to make my own sort of mini programming language, and I'm trying to make prints read for variables. Every time it loops to set f to the variable name, nothing happens. The only way I get remotely close to finding the variable name is by doing "print(lines[k][i])" before the "if lines[k][i]" condition.
Note: I was using a debugger, and I'm not sure if the "if f in var" condition is even being checked.
Python code that reads my custom programming language:
⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄
code = open("HelloWorld.sabo", 'r')
lines = code.readlines()
var = {}
for k in range(0, len(lines), 1):
conformation = 0
temp = ""
temp2 = ""
if lines[k][0:5] == "print":
r = 0
l = 0
p = False
f = ""
for i in lines[k]:
r += 1
if not p:
l += 1
if i == "(":
p = True
conformation += 1
if i == "\"" and conformation == 1:
conformation += 1
if conformation == 2:
break
if conformation == 1:
for i in range(l, len(lines[k]), 1):
if lines[k][i].isdigit() or lines[k][i].istitle():
f += lines[k][i]
if f in var:
print(var[f])
if conformation == 2:
for i in range(r, len(lines[k]), 1):
if not lines[k][i] == "\"":
f += lines[k][i]
else:
break
print(f)
elif lines[k][0:4] == "var ":
for i in range(4, len(lines[k]), 1):
if not lines[k][i] == " ":
temp += lines[k][i]
else: break
for i in range(4, len(lines[k])):
if lines[k][i] == "=":
conformation = 1
elif conformation == 1:
if not lines[k][i] == " ":
temp2 += lines[k][i]
elif not temp2 == "":
break
var[temp] = temp2.strip()
Code that is being read by the above script:
⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄
var val = hello
print(val)
So, I was being a bit dumb with this, but I found out that if I just account for Uppercase and Lowercase characters, then it will work.
if lines[k][i].islower() or lines[k][i].isdigit() or lines[k][i].isnumeric() or lines[k][i].istitle():
f += lines[k][i]
I might have gone overboard with the security though I'm just not sure about the difference isdigit and isnumeric.
I'm trying to code a simple calculator.
Below is the Updated code. But still same error.
running = True
while running:
print("1 Addition \
2 Subtraction \
3 Multiplication \
4 Division \
5 remainder \
6 Power of \
7 Quit")
O = int(input('What Operaton you want to do ? '))
F = float(input('Enter first number: '))
S = float(input('Enter Second number: '))
if O == 1:
R = F + S
print(F,'+',S,'=',R)
elif O == 2:
R = F - S
print(F,'-',S,'=',R)
elif O == 3:
R = F * S
print(F,'*',S,'=',R)
elif O == 4:
R = F / S
print(F,'/',S,'=',R)
elif O == 5:
R = F % S
print(F,'%',S,'=',R)
elif O == 6:
R = F ** S
print(F,'**',S,'=',R)
else:
print('Quit')
running = False
And while running I'm facing the Below error.
$/usr/local/bin/python3.7 file1.py
File "file1.py", line 20
R = F - S ^
TabError: inconsistent use of tabs and spaces in indentation
You're indenting your while statement unnecessarily.
running = True
while running:
should be:
running = True
while running:
There is another problem though:
Instead of:
else O == 7:
print('Quit')
running = False
You should write:
else:
print('Quit')
running = False
else doesn't take any argument. It is simple the set of statements chosen when no if or elif condition is true.
I have the following code, which is a code for a connect 4 game, the problem is that the functions seem to break in the user input part of the code. I don't know if I accidentally edited something to break it but I'm almost certain that it isn't as typing the adding this to the code:
addcounter(1,1)
addcounter(1,1)
addcounter(1,1)
addcounter(1,1)
addcounter(2,1)
addcounter(2,1)
addcounter(2,1)
addcounter(3,1)
addcounter(3,1)
addcounter(4,1)
checkdiagonal(4,1,1)
The output of this does return true as expected.
The code is as follows:
# -*- coding: utf-8 -*-
"""
Created on Sun Dec 22 17:24:35 2019
#author: Norbert
"""
import numpy as np
h = 8
w = 9
x = 0
y = 0
playspace = np.zeros((h,w))
playspace[:, [0,-1]] = 8
def addcounter(column,team):
placed = False
while not placed:
for i in range(h-1,0,-1):
if playspace[i,column] > 0:
continue
else:
if team == 1:
playspace[i,column] = 1
if team == 2:
playspace[i,column] = 2
if team != 1 and team != 2:
print("error, invalid team")
placed = True
break
def height(column):
for i in range(h-1,0,-1):
if playspace[i,column] > 0:
continue
else:
return i
def checkhorizontal(y,x,team):
a1 = 0
a2 = 0
a3 = 0
a4 = 0
for i in range(4):
try:
if playspace[h-y,x+i] == team:
a1 += 1
if playspace[h-y,x+i-1] == team:
a2 += 1
if playspace[h-y,x+i-2] ==team:
a3 += 1
if playspace[h-y,x+i-3] ==team:
a4 += 1
except:
pass
if (a1 == 4) or (a2 == 4) or (a3 == 4) or (a4 == 4):
return True
def checkvertical(y,x,team):
a1 = 0
a2 = 0
a3 = 0
a4 = 0
checking = playspace[:,x]
for i in range(4):
try:
if checking[h-(y+i)] == team:
a1 += 1
if checking[h-(y+i-1)] == team:
a2 += 1
if checking[h-(y+i-2)] ==team:
a3 += 1
if checking[h-(y+i-3)] == team:
a4 += 1
except:
pass
if (a1 == 4) or (a2 == 4) or (a3 == 4) or (a4 == 4):
return True
def checkdiagonal(y,x,team):
diag1 = 0
diag2 = 0
if playspace[h-y,x] == team:
diag1 += 1
diag2 += 1
for i in range(1,4):
broken1 = False
try:
if playspace[h-y+i,x+i] == team and not broken1:
diag1 += 1
if playspace[h-y+i,x+i] != team:
broken1 = True
except:
pass
for i in range(1,4):
broken2 = False
try:
if playspace[h-y-i,x-i] == team and not broken2:
diag1 += 1
if playspace[h-y-i,x-i] != team:
broken2 = True
except:
pass
for i in range(1,4):
broken3 = False
try:
if playspace[h-y+i,x-i] == team and not broken3:
diag2 += 1
if playspace[h-y+i,x-i] != team:
broken3 = True
except:
pass
for i in range(1,4):
broken4 = False
try:
if playspace[h-y-i,x+i] == team and not broken4:
diag2 += 1
if playspace[h-y-i,x+i] != team:
broken4 = False
except:
pass
if (diag1 >= 4) or (diag2 >= 4):
return True
finished = False
turn = 0
team_turn = 1
print(playspace)
while not finished:
valid = False
print("turn: {}".format(turn))
print("It is player {}'s turn".format(team_turn))
while not valid:
player_input = int(input("Where would you like to drop a counter?"))
if playspace[0,player_input] != 0:
print("That isn't a valid column")
else:
valid = True
if team_turn == 1:
addcounter(player_input,team_turn)
if checkhorizontal(height(player_input),player_input,team_turn) == True or checkvertical(height(player_input),player_input,team_turn) == True or checkdiagonal(height(player_input),player_input,team_turn) == True:
print("Player {} wins".format(team_turn))
finished = True
if team_turn == 2:
addcounter(player_input,team_turn)
if checkhorizontal(height(player_input),player_input,team_turn) == True or checkvertical(height(player_input),player_input,team_turn) == True or checkdiagonal(height(player_input),player_input,team_turn) == True:
print("Player {} wins".format(team_turn))
finished = True
turn += 1
turn_changed = False
while not turn_changed:
if team_turn == 1:
team_turn = 2
turn_changed = True
break
if team_turn == 2:
team_turn = 1
turn_changed = True
break
print(playspace)
any help in trying to solve the bugs in the code would be grately appreciated. The connect 4 game uses simple 2-d arrays to display and store the game board. I have plans to use this array to create a pygame later on.
EDIT:
To clarify, the checks don't run to execute a victory message and end the game. despite the if statements being True. Only the vertical win seems to end the game.
I managed to correct the horizontal part, the code correction is as follows:
if (checkhorizontal(height(player_input)+1,player_input,team_turn) == True) or (checkvertical(height(player_input),player_input,team_turn) == True) or (checkdiagonal(height(player_input),player_input,team_turn) == True):
and in the horizontalcheck function:
def checkhorizontal(y,x,team):
a1 = 0
a2 = 0
a3 = 0
a4 = 0
checking = playspace[y,:]
print(checking)
for i in range(4):
try:
if checking[x+i] == team:
a1 += 1
if checking[x+i-1] == team:
a2 += 1
if checking[x+i-2] ==team:
a3 += 1
if checking[x+i-3] ==team:
a4 += 1
except:
pass
print(a1,a2,a3,a4)
if (a1 == 4) or (a2 == 4) or (a3 == 4) or (a4 == 4):
return True
Ignore the prints, they're for debugging. But I basically removed one dimension and flipped the h-y value to become the y value.
I have a little problem who block me, I've a work where I must to convert a number to Shadocks (base 4 it seems), and I must to make a decrypter.
So I made the first part, but my code won't work on the second.
Here it's :
def Base10toShadocks(n):
q = n
r = 0
Base4=[]
Shads=["GA","BU","ZO","MEU"]
if q == 0:
Base4.append(0)
else:
while q > 0:
q = n//4
r = n%4
n = q
Base4.append(r)
Base4.reverse()
VocShad = [Shads[i] for i in Base4]
print(VocShad)
def ShadockstoBase10(n):
l=len(n)
Erc_finale=[]
for i in range(l):
Sh=(n[i])
i=i+1
if Sh =="a":
Erc_finale.append(0)
elif Sh =="b":
Erc_finale.append(1)
elif Sh =="o":
Erc_finale.append(2)
elif Sh =="e":
Erc_finale.append(3)
print(Erc_finale)
F=str(Erc_finale)
print(F)
F=F.replace("[","")
F=F.replace("]","")
F=F.replace(",","")
F=F.replace(" ","")
L2=len(F)
F=int(F)
print(L2)
print(F)
r=0
while f < 4 or F ==4:
d=(F%4)-1
F=F//4
print(d)
r=r+d*(4**i)
print(r)
inp = 0
inp2 = 0
print("Tapez \"1\" pour choisir de traduire votre nombre en shadock, ou \"2\" pour inversement")
inp = int(input())
if inp == 1:
print("Quel est le nombre ?")
inp2 = int(input())
if inp2 != None:
Base10toShadocks(inp2)
elif inp == 2:
print("Quel est le nombre ?")
inp2 = str(input())
if inp2 != None:
ShadockstoBase10(inp2)
It blocks at the F=int(F), I don't understand why.
Thanks for your help.
First, some errors in your code:
for i in range(l):
Sh=(n[i])
i=i+1 #### Won't work. range() will override
##### Where do "a","b","o","e" come from
##### Shouldn't it be "G","B","Z","M" ("GA","BU","ZO","MEU")?
if Sh =="a":
Erc_finale.append(0)
elif Sh =="b":
Erc_finale.append(1)
elif Sh =="o":
Erc_finale.append(2)
elif Sh =="e":
Erc_finale.append(3)
print(Erc_finale)
F=str(Erc_finale) ### Not how you join an array into a string
Here's a corrected way:
def ShadockstoBase10(n):
n = n.upper(); # Convert string to upper case
l = len(n)
Erc_finale = "" # Using a string instead of an array to avoid conversion later
i = 0
while i < l: # while loop so we can modify i in the loop
Sh = n[i:i+2] # Get next 2 chars
i += 2 # Skip 2nd char
if Sh == "GA":
Erc_finale += "0"
elif Sh == "BU":
Erc_finale += "1"
elif Sh == "ZO":
Erc_finale += "2"
elif Sh =="ME" and "U" == n[i]:
Erc_finale += "3"
i += 1; # MEU is 3 chars
else:
break; # bad char
return int(Erc_finale, 4) # Let Python do the heavy work
Like everything in Python, there are other ways to do this. I just tried to keep my code similar to yours.
I am trying to convert the code here http://www.geeksforgeeks.org/expression-evaluation/ to python. However, I am running into some trouble and can't figure out.
class evaluateString:
def evalString(self,expression):
valueStack = []
opStack = []
i=0
while(i<len(expression)):
if(expression[i] == ' '):
continue
if(expression[i]>='0' and expression[i] <= '9'):
charNumber = [] #for storing number
while(i<len(expression) and expression[i]>='0' and expression[i] <= '9'):
charNumber.append(expression[i])
i+=1
valueStack.append(int(''.join(charNumber)))
elif (expression[i]=='('):
opStack.append(expression[i])
elif (expression[i]==')'):
while(opStack[-1]!='('):
valueStack.append(self.applyOperation(opStack.pop(),valueStack.pop(),valueStack.pop()))
opStack.pop()
elif(expression[i]=='+'or expression[i]=='-'or expression[i]=='*'or expression[i]=='/'):
while( (len(opStack)!=0) and ( self.opPrecedence(expression[i],opStack[-1]) ) ):
valueStack.append(self.applyOperation(opStack.pop(),valueStack.pop(),valueStack.pop()))
opStack.append(expression[i])
i = i + 1
while(len(opStack)!=0):
valueStack.append(self.applyOperation(opStack.pop(),valueStack.pop(),valueStack.pop()))
return valueStack.pop()
def applyOperation(self,op,a,b):
if op=='+':
return a+b
elif op=='-':
return a-b
elif op=='*':
return a*b
elif op=='/':
return a/b
else:
return 0
def opPrecedence(self,op1,op2):
if (op2 == '(' or op2 == ')'):
return False
if ((op1 == '*' or op1 == '/') and (op2 == '+' or op2 == '-')):
return False
else:
return True
a = evaluateString()
print(a.evalString("(5+7)"))
I am able to get the right numbers in the valueStack. However, there seems to be problem in the last two elseif. Can someone point me in the right direction?
I have done some fixes and it works for some operations. But I haven't tested it for all cases. Also, operations are only integers, no floats (e.g. check last output below).
class evaluateString:
def evalString(self,expression):
valueStack = []
opStack = []
i=0
while(i<len(expression)):
if(expression[i] == ' '):
continue
if(expression[i]>='0' and expression[i] <= '9'):
charNumber = [] #for storing number
j = i
while(j<len(expression) and expression[j]>='0' and expression[j] <= '9'):
charNumber.append(expression[j])
j += 1
i = (j-1)
valueStack.append(int(''.join(charNumber)))
elif (expression[i]=='('):
opStack.append(expression[i])
elif (expression[i]==')'):
while(opStack[-1]!='('):
valueStack.append(self.applyOperation(opStack.pop(),valueStack.pop(),valueStack.pop()))
opStack.pop()
elif(expression[i]=='+'or expression[i]=='-'or expression[i]=='*'or expression[i]=='/'):
while( (len(opStack)!=0) and ( self.opPrecedence(expression[i],opStack[-1]) ) ):
valueStack.append(self.applyOperation(opStack.pop(),valueStack.pop(),valueStack.pop()))
opStack.append(expression[i])
i = i + 1
while(len(opStack)!=0):
valueStack.append(self.applyOperation(opStack.pop(),valueStack.pop(),valueStack.pop()))
return valueStack.pop()
def applyOperation(self,op,a,b):
if op=='+':
return a+b
elif op=='-':
return b-a
elif op=='*':
return a*b
elif op=='/':
return b/a
else:
return 0
def opPrecedence(self,op1,op2):
if (op2 == '(' or op2 == ')'):
return False
if ((op1 == '*' or op1 == '/') and (op2 == '+' or op2 == '-')):
return False
else:
return True
a = evaluateString()
print(a.evalString("8*12")) #prints 96
print(a.evalString("(122-434)")) #prints -312
print(a.evalString("(232+12)/2")) #print 122
print(a.evalString("232/12+2")) #prints 21
In python eval() will evaluate infix expressions
print(eval("(5+7)/2"))
it will print the evaluated infix expression value as 6.