Break function does not work when the elif line is true - python

start = input('Enter quadratic equation: ')
w = start.split()
while len(w) != 7:
start = input('Enter quadratic equation correctly: ')
w = start.split()
while x < len(w):
if "x" in w[x] and '^2' in w[x]:
a = w[x]
if a == "x^2":
a = 1
else:
a = a.replace('x^2', '')
a = int(a)
if w[x-1] == '-':
a = a * (-1)
else:
a = a
elif 'x' in w[x] and '^' not in w[x]:
b = w[x]
if b == 'x':
b = 1
else:
b = b.replace('x', '')
b = int(b)
if w[x-1] == '-':
b = b * (-1)
else:
b = b
elif w[x].isdigit() and 'x' not in w[x] and w[x] != '0':
c = w[x]
elif w[x] == '-' or '+' or '=':
s = 0
elif not w[x].isdigit() and 'x' not in w[x] and w[x] != '-' or '+' or '=':
print('Mistake')
break #Would not this code here work?
x += 1
I have tried just doing 'else' block, but still it wouldn't work. What I am trying to do is to check whether the input is actually a quadratic equation.

The wrong condition is elif not w[x].isdigit() and 'x' not in w[x] and w[x] != '-' or '+' or '=':, it doesn't do what you want/need
The w[x] != '-' or '+' or '=': part :
is like (w[x]!='-') or ('+') or ('='):
not like w[x] != ('-' or '+' or '='):
What you want is w[x] not in '-+=': and same for the previous one
elif w[x] in '-+=':
s = 0
elif not w[x].isdigit() and 'x' not in w[x] and w[x] not in '-+=':
print('Mistake')
break

Related

TypeError: cannot unpack non-iterable NoneType object Error

I looked at the other answers but they didn't seem to work for me, or I could just be doing something wrong, or not understanding what I am supposed to do in the context of this code. On line 78, it talks about how there is a Nonetype value, even though I assigned a value to both variables no matter what.
Here is a link to a similar problem (I think):
[https://stackoverflow.com/questions/53680913/typeerror-cannot-unpack-non-iterable-nonetype-object][1]
Here is where I think the faulty code lies:
def check_win(turn, gamestate):
if turn == 1:
if gamestate[0] == gamestate[1] == gamestate[2] != '-' or gamestate[3] == gamestate[4] == gamestate[5] != '-' or gamestate[6] == gamestate[7] == gamestate[8] != '-':
winner = 1
win = True
return winner, win
elif gamestate[0] == gamestate[3] == gamestate[6] != '-' or gamestate[1] == gamestate[4] == gamestate[7] != '-' or gamestate[2] == gamestate[5] == gamestate[8] != '-':
winner = 1
win = True
return winner, win
elif gamestate[0] == gamestate[4] == gamestate[8] != '-' or gamestate[2] == gamestate[4] == gamestate[6] != '-':
winner = 1
win = True
return winner, win
elif turn == 2:
if gamestate[0] == gamestate[1] == gamestate[2] or gamestate[3] == gamestate[4] == gamestate[5] or gamestate[6] == gamestate[7] == gamestate[8]:
winner = 2
win = True
return winner, win
elif gamestate[0] == gamestate[3] == gamestate[6] or gamestate[1] == gamestate[4] == gamestate[7] or gamestate[2] == gamestate[5] == gamestate[8]:
winner = 2
win = True
return winner, win
elif gamestate[0] == gamestate[4] == gamestate[8] or gamestate[2] == gamestate[4] == gamestate[6]:
winner = 2
win = True
return winner, win
else:
winner = 'None'
win = False
return winner, win
Later on when I try to alter those values in another function:
winner, win = check_win(turn, gamestate) <--- Where error was found
Here is the code in its entirety :
print('Tic Tac Toe:')
pos = 0
turn = 1
gamestate = ['-', '-', '-', '-', '-', '-', '-', '-', '-']
def display_board(gamestate):
print(gamestate[0:3])
print(gamestate[3:6])
print(gamestate[6:9])
def move_validity(pos, gamestate):
if str(gamestate[int(pos)]) != '-':
print('Invalid move.')
valid = False
return valid
else:
valid = True
return valid
def update(gamestate, pos):
if turn == 1:
gamestate[int(pos)] = 'X'
if turn == 2:
gamestate[int(pos)] = 'O'
else:
print('ERROR')
def check_win(turn, gamestate):
if turn == 1:
if gamestate[0] == gamestate[1] == gamestate[2] != '-' or gamestate[3] == gamestate[4] == gamestate[5] != '-' or gamestate[6] == gamestate[7] == gamestate[8] != '-':
winner = 1
win = True
return winner, win
elif gamestate[0] == gamestate[3] == gamestate[6] != '-' or gamestate[1] == gamestate[4] == gamestate[7] != '-' or gamestate[2] == gamestate[5] == gamestate[8] != '-':
winner = 1
win = True
return winner, win
elif gamestate[0] == gamestate[4] == gamestate[8] != '-' or gamestate[2] == gamestate[4] == gamestate[6] != '-':
winner = 1
win = True
return winner, win
elif turn == 2:
if gamestate[0] == gamestate[1] == gamestate[2] or gamestate[3] == gamestate[4] == gamestate[5] or gamestate[6] == gamestate[7] == gamestate[8]:
winner = 2
win = True
return winner, win
elif gamestate[0] == gamestate[3] == gamestate[6] or gamestate[1] == gamestate[4] == gamestate[7] or gamestate[2] == gamestate[5] == gamestate[8]:
winner = 2
win = True
return winner, win
elif gamestate[0] == gamestate[4] == gamestate[8] or gamestate[2] == gamestate[4] == gamestate[6]:
winner = 2
win = True
return winner, win
else:
winner = 'None'
win = False
return winner, win
def restart():
gamestate = ['-', '-', '-', '-', '-', '-', '-', '-', '-']
turn = 1
win = False
return gamestate, turn, win
def choose_position():
pos = input('Player ' + str(turn) + ': ')
if int(pos) < 0 or int(pos) > 8:
print('Invalid move')
else:
return pos
def Tic_Tac_Toe():
while True:
global pos
global turn
if turn == 1:
pos = choose_position()
valid = move_validity(pos, gamestate)
if valid == True:
update(gamestate, pos)
if valid == False:
break
winner, win = check_win(turn, gamestate)
if win == True:
print(str(winner) + ' wins!')
break
if '-' not in gamestate:
print('Tie game.')
break
if turn == 2:
pos = choose_position()
if move_validity(pos, gamestate) == True:
continue
if move_validity(pos, gamestate) == False:
break
update(gamestate, pos)
winner, win = check_win(turn, gamestate)
if win == True:
print(str(winner) + ' wins!')
break
turn = 1
if '-' not in gamestate:
print('Tie game.')
break
display_board(gamestate)
display_board(gamestate)
Tic_Tac_Toe()
restart_case = input('y/n Would you like to play? ')
if restart_case == 'y':
gameboard, turn, win = restart()
Thank you so much, and sorry if the solution was a small typo, I am really new to this and have spent way too much time on this. :D
There are certain cases where you don't return anything in the function check_win.
For example, when turn == 1, you have an if, elif, elif block within that, but nothing for else. So, when turn == 1, if none of the if statements within the block for that are true, your function will return nothing. There is a similar problem for turn == 2. You may want to add the code you have in the else block for that function as an else block for both turn == 1 and turn == 2, as this will fix your problem.

Separating out 'While' function

I currently have defined my object (is_matched) that contains a while loop and also the checking of a string. I am trying to pull out the while loop into it's own object but am having trouble completing the coding. I also need the while loop to continue running until a user enters 'q' into the input.
def is_matched():
while True:
expr = input("Enter string (q to quit): ")
if expr == "q":
break
stack = Stack()
for i in expr:
if i == '{' or i == '(' or i == '[':
stack.push(i)
elif i == '}':
if len(expr) != 0:
c = stack.top()
if c == '{':
stack.pop()
else:
return "Unbalanced"
elif i == ')':
if len(expr) != 0:
c = stack.top()
if c == '(':
stack.pop()
else:
return "Unbalanced"
elif i == ']':
if len(expr) != 0:
c = stack.top()
if c == '[':
stack.pop()
else:
return "Unbalanced"
else:
return "Unbalanced"
if len(stack) != 0:
return "Unblanced"
return "Balanced"
result = is_matched()
print(result)
I am trying to pull out the while loop from above and enter into its own object as follows:
def main():
while True:
expr = input("Enter string (q to quit): ")
if expr == "q":
break
else:
return is_matched()
your is_matched function will take one argument which will be the expression to evaluate.
def is_matched(expr):
stack = Stack()
for i in expr:
if i == '{' or i == '(' or i == '[':
stack.push(i)
elif i == '}':
if len(expr) != 0:
c = stack.top()
if c == '{':
stack.pop()
else:
return "Unbalanced"
elif i == ')':
if len(expr) != 0:
c = stack.top()
if c == '(':
stack.pop()
else:
return "Unbalanced"
elif i == ']':
if len(expr) != 0:
c = stack.top()
if c == '[':
stack.pop()
else:
return "Unbalanced"
else:
return "Unbalanced"
if len(stack) != 0:
return "Unblanced"
return "Balanced"
main function.
def main():
while True:
expr = input("Enter string (q to quit): ")
if expr == "q":
break
else:
print(is_matched(expr))

Python wont execute past any elif statements past the 1st one

I'm in the process of writing a rudimentary Connect 4 game, with the board built into the command line, etc. My problem is that I cant get the code to execute past the 2nd elif statement. I set it up so that if a certain cell in the grid does not have an underscore, it should proceed to place the piece in the next row. However, the following move always only replaces whatever piece is in the cell in row 2. I've tried starting from rows other than the bottom 2 rows, just to try to troubleshoot, but it never gets past the 1st elif statement. Can anyone tell me where I'm going wrong with my elifs?
board = []
for x in range(0, 6):
board.append(["_"] * 7)
def print_board(board):
for i in range(1,7):
print(i, end=" ")
print(7)
for row in board:
print("|".join(row))
print_board(board)
for turn in range(42):
print('Turn', turn+1)
if turn % 2 == 0:
player1 = int(input('Player 1, choose your column: '))
while player1 not in range(1,8):
player1 = int(input('You must enter a column number from 1-7: '))
if board[5][player1-1] == '_':
board[5][player1-1] = 'O'
elif board[5][player1-1] != '_':
board[4][player1-1] = 'O'
elif board[4][player1-1] != '_':
board[3][player1-1] = 'O'
elif board[3][player1-1] != '_':
board[2][player1-1] = 'O'
elif board[2][player1-1] != '_':
board[1][player1-1] = 'O'
elif board[1][player1-1] != '_':
board[0][player1-1] = 'O'
print_board(board)
elif turn % 2 != 0:
player2 = int(input('Player 2, choose your column: '))
while player2 not in range(1,8):
player2 = int(input('You must enter a column number from 1-7: '))
if board[5][player2-1] == '_':
board[5][player2-1] = 'X'
elif board[5][player2-1] != '_':
board[4][player2-1] = 'X'
elif board[4][player2-1] != '_':
board[3][player2-1] = 'X'
elif board[3][player2-1] != '_':
board[2][player2-1] = 'X'
elif board[2][player2-1] != '_':
board[1][player2-1] = 'X'
elif board[1][player2-1] != '_':
board[0][player2-1] = 'X'
print_board(board)
You should test the cells using ==, not !=. Also, you should change the same cell you test on, not the one below it:
board = []
for x in range(0, 6):
board.append(["_"] * 7)
def print_board(board):
for i in range(1,7):
print(i, end=" ")
print(7)
for row in board:
print("|".join(row))
print_board(board)
for turn in range(42):
print('Turn', turn+1)
if turn % 2 == 0:
player1 = int(input('Player 1, choose your column: '))
while player1 not in range(1,8):
player1 = int(input('You must enter a column number from 1-7: '))
if board[5][player1-1] == '_':
board[5][player1-1] = 'O'
elif board[4][player1-1] == '_':
board[4][player1-1] = 'O'
elif board[3][player1-1] == '_':
board[3][player1-1] = 'O'
elif board[2][player1-1] == '_':
board[2][player1-1] = 'O'
elif board[1][player1-1] == '_':
board[1][player1-1] = 'O'
elif board[0][player1-1] == '_':
board[0][player1-1] = 'O'
print_board(board)
elif turn % 2 != 0:
player2 = int(input('Player 2, choose your column: '))
while player2 not in range(1,8):
player2 = int(input('You must enter a column number from 1-7: '))
if board[5][player2-1] == '_':
board[5][player2-1] = 'X'
elif board[4][player2-1] == '_':
board[4][player2-1] = 'X'
elif board[3][player2-1] == '_':
board[3][player2-1] = 'X'
elif board[2][player2-1] == '_':
board[2][player2-1] = 'X'
elif board[1][player2-1] == '_':
board[1][player2-1] = 'X'
elif board[0][player2-1] == '_':
board[0][player2-1] = 'X'
print_board(board)

why label is not being configured in function?

my score label or chances count is not configured when i run the function. can anyone help on this? the question label changes perfectly but the score label does not change and i am unable to understand why is that so.
def checkans(self):
chances = 0
score = 0
count = 0
while chances == 3:
break
else:
operations=['+', '-', '*']
a = random.randint(1,15)
b = random.randint(1,15)
random.shuffle(operations)
op = operations[0]
self.label.configure(text=(a,op,b))
if op == '+':
ans = a + b
if op == '-':
ans = a - b
if op == '*':
ans = a * b
self.e.focus_set()
if self.e.get() == ans:
score += 1
self.scorelabel.configure(text=('score', score))
else:
chances += 1
Try this:
def checkans(self):
chances = 0
score = 0
count = 0
while chances < 3:
operations=['+', '-', '*']
a = random.randint(1,15)
b = random.randint(1,15)
random.shuffle(operations)
op = operations[0]
self.label.configure(text=(a,op,b))
if op == '+':
ans = a + b
if op == '-':
ans = a - b
if op == '*':
ans = a * b
self.e.focus_set()
if self.e.get() == ans:
score += 1
self.scorelabel.configure(text=('score', score))
else:
chances += 1
When you use while with else the else only executes once.

Project Euler: Sum varying by a significant margin

I'm currently trying to solve problem 22 on Project Euler...which is as follows:
**Using names.txt (right click and 'Save Link/Target As...'), a 46K text file containing over five-thousand first names, begin by sorting it into alphabetical order. Then working out the alphabetical value for each name, multiply this value by its alphabetical position in the list to obtain a name score.
For example, when the list is sorted into alphabetical order, COLIN, which is worth 3 + 15 + 12 + 9 + 14 = 53, is the 938th name in the list. So, COLIN would obtain a score of 938 × 53 = 49714.
What is the total of all the name scores in the file?**
Here's the code that I wrote to solve this problem:
f = open("F:\gnames.txt", "r")
strr = f.read()
w = strr.replace('"', "")
li = w.split(',')
dic = {}
sum = 0
for ee in li:
for e in ee:
if (e == "A"):
sum+=1
elif (e == "B"):
sum+=2
elif (e == "C"):
sum+=3
elif (e == "D"):
sum+=4
elif (e == "E"):
sum+=5
elif (e == "F"):
sum+=6
elif (e == "G"):
sum+=7
elif (e == "H"):
sum+=8
elif (e == "I"):
sum+=9
elif (e == "J"):
sum+=10
elif (e == "K"):
sum+=11
elif (e == "L"):
sum+=12
elif (e == "M"):
sum+=13
elif (e == "N"):
sum+=14
elif (e == "O"):
sum+=15
elif (e == "P"):
sum+=16
elif (e == "Q"):
sum+=17
elif (e == "R"):
sum+=18
elif (e == "S"):
sum+=19
elif (e == "T"):
sum+=20
elif (e == "U"):
sum+=21
elif (e == "V"):
sum+=22
elif (e == "W"):
sum+=23
elif (e == "X"):
sum+=24
elif (e == "Y"):
sum+=25
else:
sum+=26
dic[ee] = sum
sum = 0
x = sorted(dic.items(), key=lambda t: t[1])
main_sum = 0
index = 0
for c in x:
t = c[1]*index
main_sum = main_sum + t
index+=1
print main_sum
The actual answer is 871198282. However, my code gives the answer as 995996966, which is off by 124798684 compared to the actual answer. What seems to be the problem with my code?
I think your issue is in the line x = sorted(dic.items(), key=lambda t: t[1]). This sorts the dictionary items by the scores, not alphabetically by the names. Change t[1] to t[0] in the lambda and I suspect you'll get a better result.
Another possible issue (it's a little ambiguous) is your indexing when you go to add up the scores. You're starting index at zero, but the instructions suggest that the 938th name should be multiplied by 938, not by its zero-based index, which would be 937. You probably need to start with index = 1.

Categories

Resources