What is wrong with my elif statement? Invalid Syntax - python-3.3

if option == "1":
with open("sample.txt","r") as f:
print(f.read())
numbers = []
with open("sample2.txt","r") as f:
for i in range(9):
numbers.append(f.readline().strip())
print(numbers)
from random import randint
for i in range(9):
print(numbers[randint(0,8)])
from tkinter import *
def mhello():
mtext = ment.get()
mLabel2 = Label(test, text=mtext).pack()
return
test = Tk()
ment = StringVar()
test.geometry('450x450+500+10')
test.title('Test')
mlabel = Label(test, text='Time to guess').pack()
mbutton = Button(test, text='Click', command = mhello).pack()
mEntry = Entry(test, textvariable=ment).pack()
test.mainloop()
from tkinter import *
def mhello():
my_word = 'HELLO'
mtext = ment.get()
if my_word == mtext:
mLabel2 = Label(test, text='Correct').pack()
else:
mLabel2 = Label(test, text='Incorrect').pack()
return
test = Tk()
ment = StringVar()
test.geometry('450x450+500+300')
test.title('Test')
def label_1():
label_1 = Label(test, text='Hello. Welcome to my game.').pack()
def label_2():
label_2 = Label(test, text='What word am I thinking of?').pack()
button_1 = Button(test, text='Click', command = mhello).pack()
entry_1 = Entry(test, textvariable=ment).pack()
label_1()
test.after(5000, label_2)
test.mainloop()
from tkinter import *
from random import shuffle
game = Tk()
game.geometry('200x200')
game.grid()
game.title("My Game")
board = [1, 2, 3, 4, 5, 6, 7, 8, 9]
def board_1():
board1 = []
k = 0
for i in range(3):
for j in range(3):
board1.append(Label(game, text = board[k]))
board1[k].grid(row = i, column = j)
k +=1
def board_2():
shuffle(board)
board2 = []
k = 0
for i in range(3):
for j in range(3):
board2.append(Label(game, text = board[k]))
board2[k].grid(row = i, column = j)
k +=1
board_1()
game.after(5000, board_2)
game.mainloop()
#2nd Option
elif option == "2":
print ("You have chosen option 2. Well Done, You Can Type! XD")
The bit that has the Syntax Error is the 1st elif statement (2nd Option). Ignore all the code prior to this if necessary (it is there for context). Whenever I run the code it says that there is a syntax error and just positions the typing line (I don't know what it's called) at the end of the word elif.

This is a simple fix, with if else statements you need to have a closing ELSE and in this case there is not so when your program runs it sees that theres a lonely if without its else :)
if option == "1":
elif option == "2":
else:
'do something else in the program if any other value was recieved'
also a switch statement can be used here so it does not keep checking each condition and just goes straight to the correct case :D

The problem is that your block is separated from the first if-statement, where it actually belongs to. As it is, it follows the game.mainloop() statement, and adds an unexpected indentation. Try to rearrange your code like so:
if option == "1":
with open("sample.txt","r") as f:
print(f.read())
numbers = []
with open("sample2.txt","r") as f:
for i in range(9):
numbers.append(f.readline().strip())
print(numbers)
from random import randint
for i in range(9):
print(numbers[randint(0,8)])
elif option == "2":
print ("You have chosen option 2. Well Done, You Can Type! XD")
[ Rest of the code ]

Related

Creating a tkinter quick multiplication game using recursion

I'm trying to create a game that generates 2 random numbers and then the user has to type the correct answer of the product of it, then 1 point is gained. I'm trying to get it to stop once it's been done 10 times however I can't seem to get it to end. I tried using a loop rather than recursion but I also got stuck on that.
import tkinter as tk
from tkinter import *
import random
numbers = [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16]
qm_score = 0
global recursion_count
recursion_count = 0
quickmulti_page = tk.Tk()
quickmulti_page.title =("Quick multiplication")
quickmulti_page.config(background="SlateGray1")
quickmulti_page.geometry("300x200")
def endgame():
print("Youre done")
print(qm_score)
def multiplication():
def multi_answer(event):
recursion_count = recursion_count + 1
if recursion_count == 10:
if user_answer == answer:
qm_score = qm_score + 1
endgame()
else:
endgame()
elif recursioncount > 3:
multiplication()
else:
endgame()
num1 = random.choice(numbers)
num2 = random.choice(numbers)
answer = num1 * num2
qlabel = Label(quickmulti_page, text=(num1,"x", num2), font=100, width=20, height=3).place(x=50,y=40)
user_answer = Entry(quickmulti_page,width=30)
user_answer.place(x=50, y=120)
user_answer.bind('<Return>', multi_answer)

Character Countdown

I'm trying to create a function. Function; it will simply be designed to increase the last letter sequence from its position in the alphabet or letter list.
import time
def CountDown(text,reply=3):
abc = list("ABCDEFGHIJ")
c = 1
text_list = list(text)
while 1:
Index = abc.index(text_list[-c])
if not list(filter(lambda a: a!=abc[-1], text_list)):
return "".join(text_list)
if text_list[-c] == abc[-1]:
text_list[-c] = abc[0]
c += 1
continue
else:
s=1
while 1:
text_list[-c] = abc[(Index+s) if (Index+s)<len(abc) else 0]
if text_list.count(abc[(Index+s) if (Index+s)<len(abc) else 0])+1<reply:
break
s+=1
text_list[-c] = abc[(Index+s) if (Index+s)<len(abc) else 0]
return "".join(text_list)
if __name__ == "__main__":
code="ABHD"
while 1:
code=CountDown(code)
time.sleep(0.5)
print(code)
OUTPUT:
ABHE
ABHF
ABHG
ABHI
ABHJ
ABIA
ABIC
ABID
ABIE
ABIF
ABIG
ABIH
ABIJ
ABJA
ABJC
ABJD
ABJE
ABJF
ABJG
ABJH
ABJI
....(idling)
The code doesn't give an output after a while. I think there is something wrong.
How can I fix this code sample?

how to create an impossible sudoku detector?

I'm making a sudoku solver on pygame, using backtracking. It's working, both the backtracking and the gui, however, when the user tries to solve an impossible puzzle, the game freezes.
I want to make a modification to my algorithm that, when the puzzle is impossible, the algorithm detects it, warning the user and reseting the board.
For now, this is the main code for the board class.
class Board:
solvedBoard = [[0 for i in range(9)] for j in range(9)]
gameRunning = True
def __init__(self):
self.tabuleiro = [[0 for i in range(9)] for j in range(9)]
def reset(self):
self.tabuleiro = [[0 for i in range(9)] for j in range(9)]
self.gameRunning = True
def show(self):
for i in self.tabuleiro:
for j in i:
print(j, end = ' ')
print('')
def setCell(self, linha, coluna, valor):
self.tabuleiro[linha][coluna] = valor
def isFull(self):
for i in range(9):
for j in range(9):
if self.tabuleiro[i][j] == 0:
return False
return True
def numberPossibilities(self, linha, coluna):
possible = [1 for i in range(10)]
#horizontal check
for col in range(9):
if self.tabuleiro[linha][col]:
possible[self.tabuleiro[linha][col]] = 0
#vertical check
for line in range(9):
if self.tabuleiro[line][coluna]:
possible[self.tabuleiro[line][coluna]] = 0
#mini square check
linhaSquare = (linha // 3) * 3
colunaSquare = (coluna // 3) * 3
for l in range(linhaSquare, linhaSquare + 3):
for c in range(colunaSquare, colunaSquare + 3):
if self.tabuleiro[l][c]:
possible[self.tabuleiro[l][c]] = 0
toTry = []
for k in range(1, 10):
if possible[k]:
toTry.append(k)
return toTry
def solve(self):
self.show()
print('')
if self.isFull():
for i in range(9):
for j in range(9):
self.solvedBoard[i][j] = self.tabuleiro[i][j]
self.gameRunning = False
self.tabuleiro = self.solvedBoard
elif self.gameRunning:
found = False
linha = 0
coluna = 0
for i in range(9):
for j in range(9):
if (not self.tabuleiro[i][j]):
linha = i
coluna = j
found = True
break
if found:
break
numbers = self.numberPossibilities(linha, coluna)
print(*numbers)
print('')
tamanho = len(numbers)
for k in range(tamanho):
if (not self.gameRunning):
self.tabuleiro = self.solvedBoard
break
self.tabuleiro[linha][coluna] = numbers[k]
self.solve()
if (self.gameRunning):
self.tabuleiro[linha][coluna] = 0
Note that the "show" function is only for debugging. I have an actual drawGrid function for handling the GUI.
My idea is to detect the first cell that needs to be changed, and, when the backtracking eventually comes back to It, with no other options to continue, It resets the board and then turns on a flag called "Impossible". Next iteration, the board detects that "Impossible" is on and resets the board, besides breaking the recursion.
However, that's seems too complicated, and I'm not sure how to do It without damaging code readability
What do you think? And also, Thanks in advance! This community is helping me a lot of this project :)

Tic-tac-toe using python tkinter

Tic-tac-toe game using python tkinter is not working correctly.
Tic-tac-toe structure is correct. I just want to change the click event.
Only button9 output shown when click to any button
Every time I click any button this output is shown
from tkinter import *
bclick = True
tk = Tk()
tk.title("Tic Tac toe")
tk.geometry("300x400")
n = 9
btns = []
def ttt(button):
global bclick
print(button)
if button["text"] == "" and bclick == True:
print("if")
button.config(text="X")
bclick = False
elif button["text"] == "" and bclick == False:
print("else")
button["text"] = "0"
bclick = True
for i in range(9):
btns.append(Button(font=('Times 20 bold'), bg='white', fg='black', height=2, width=4))
row = 1
column = 0
index = 1
print(btns)
buttons = StringVar()
for i in btns:
i.grid(row=row, column=column)
i.config(command=lambda: ttt(i))
print(i, i["command"])
column += 1
if index % 3 == 0:
row += 1
column = 0
index += 1
tk.mainloop()
Common misstake. The lambda function is using the last value assigned to i so every lambda will use i=.!button9. change the lambda function to:
i.config(command=lambda current_button=i: ttt(current_button))
which will make lambda use the value of i when the lambda was created.

Why is this BFS queue returning None?

I am currently attempting the Hackerrank problem called Castle on the Grid,
in which I have implemented a BFS in Python 3 as follows:
#!/bin/python3
import math
import os
import random
import re
import sys
from collections import deque
def minimumMoves(grid, startX, startY, goalX, goalY):
n = len(grid)
queue = deque()
queue.append((startY,startX))
goal = (goalY,goalX)
turnsMatrix = [[0]*n]*n
while queue:
current = queue.popleft()
(Y0, X0) = current
print(current)
d = turnsMatrix[Y0][X0]
if current == goal:
return(d)
for X in range(X0-1,-1,-1):
if grid[Y0][X] == 'X':
break
elif turnsMatrix[Y0][X] == 0:
turnsMatrix[Y0][X] = d + 1
queue.append((Y0,X))
for Y in range(Y0-1,-1,-1):
if grid[Y][X0] == 'X':
break
elif turnsMatrix[Y][X0] == 0:
turnsMatrix[Y][X0] = d + 1
queue.append((Y,X0))
for X in range(X0+1,n):
if grid[Y0][X] == 'X':
break
elif turnsMatrix[Y0][X] == 0:
turnsMatrix[Y0][X] = d + 1
queue.append((Y0,X))
for Y in range(Y0+1,n):
if grid[Y][X0] == 'X':
break
elif turnsMatrix[Y][X0] == 0:
turnsMatrix[Y][X0] = d + 1
queue.append((Y,X0))
if __name__ == '__main__':
fptr = open(os.environ['OUTPUT_PATH'], 'w')
n = int(input())
grid = []
for _ in range(n):
grid_item = input()
grid.append(grid_item)
startXStartY = input().split()
startX = int(startXStartY[0])
startY = int(startXStartY[1])
goalX = int(startXStartY[2])
goalY = int(startXStartY[3])
result = minimumMoves(grid, startX, startY, goalX, goalY)
fptr.write(str(result) + '\n')
fptr.close()
However, despite only one return statement which is supposed to return an int d, my code returns a None. I know that the deque eventually becomes empty and returns None, but I am having trouble figuring out why things stop appending to the queue.
For the test case
3
.X.
.X.
...
0 0 0 2
I noticed that what would happen is:
1) castle moves right and breaks at X.
2) castle moves down one cell, and the turns matrix becomes
[[1, 0, 0], [1, 0, 0], [1, 0, 0]].
3) queue becomes deque([(1, 0)]).
4) A None is returned.
What is going on? I've been staring at my code for days and I'm going crazy... please help, thank you!

Resources