how to fix error in python code (elif statement ) - python

This is my code below, it is saying that there is an error but i cannot understand the error (the '^' is pointing at the ':' of the elif statement):
File "", line 47
elif:
^
SyntaxError: invalid syntax
'' print ("there are 27 sticks")
sticks = 27
player1 = True
Ai = False
print ("there are 27 sticks, pick the last one !")
print("1")
print("2")
print("3")
while player1 == True:
inp = int(input("Enter the number of sticks you want to take: "))
if inp == 1:
inp = "1: 1 stick taken"
sticks = sticks -1
print (sticks)
player1 = False
Ai = True
elif inp == 2:
inp = "2 sticks taken"
sticks = sticks - 2
print (sticks)
player1 = False
Ai = True
elif inp == 3:
inp = "3 sticks taken"
sticks = sticks - 3
print (sticks)
player1 = False
Ai = True
else:
print("Invalid input!")
while Ai == True:
if sticks == 7:
InpAi = 3
sticks = sticks - InpAi
print (sticks)
player1 = True
Ai = False
elif:
print ("")
else:
''

Your if tree in the second while loop has the structure if... elif... else but the elif doesn't have a condtion. It's throwing an error because there is no condtion.

You've declared an elif without a variable to check against, you need to put something like
elif something == 'something else':
do this

while Ai == True:
if sticks == 7:
InpAi = 3
sticks = sticks - InpAi
print (sticks)
player1 = True
Ai = False
elif: # <= add condition here if any otherwise remove that line :)
print ("")
else:
''

Related

I can't count the number of tries in this game in pythin

I am a beginner in python and I got a task to make a game of guesses using python. In my assignment, I was told to count the number of tries. But I can't make it work. Any suggestion would be appreciated. (note: the list is for nothing...I was just messing with the code and trying things.)
`
# import random
# a=random.randint(1,30)
a = 23
Dict1 = ["Hello there! How are you?", 0,
"Guess a number Between 1 to 50",
"Your number is too high",
"Your Number is too low",
"Make Your Number A Bit Higher",
"Make Your Number a Bit Lower",
"Congratulations You Have guessed the right number :)"
]
print(Dict1[0])
name = input("What is your Name?\n=")
# print("hi!,{}, Wanna Play a game?".format(name))
print(Dict1[2])
while 1:
inp = float(input("="))
if inp > 50:
print(Dict1[3])
continue
elif inp < 1:
print(Dict1[4])
continue
elif inp < a:
print(Dict1[5])
continue
elif inp > a:
print(Dict1[6])
continue
elif inp == a:
print(Dict1[7])
q = input("Do You Want to Go again? Y or N\n=")
if q.capitalize() == "Y":
print('You have', 5 - 4, "tries left")
print(Dict1[2])
continue
elif q.capitalize() == "N":
break
else:
break
op = inp
while 1:
x = 4
if -137247284234 <= inp <= 25377642:
x = x + 1
print('You have', 5 - x, "tries left")
if x == 5:
break
if x == 5:
print("Game Over")
`
One way to go about it would be to set up a variable to track attempts outside the while loop between a and Dict1
a = 23
attempts = 1
Dict1 = [...]
Then each time they make an attempt, increment in the while loop:
if inp > 50:
print(Dict1[3])
attempts += 1
continue
elif inp < 1:
print(Dict1[4])
attempts += 1
continue
elif inp < a:
print(Dict1[5])
attempts += 1
continue
elif inp > a:
print(Dict1[6])
attempts += 1
continue
EDIT:
Looking more carefully at your code, it seems like you want a countdown. So you could change it to
attempts = 5
and in the while loop
while 1:
...
if q.capitalize() == "Y":
attempts -= 1
print('You have', attempts, "tries left")
print(Dict1[2])
continue

Making Mastermind in Python

I am simply wondering how I can make my game of Mastermind work, more specifically how I would go about making "finish" global, how I would call these functions so that the program works correctly, and overall tips that would help enhance my code. I would also like to know how to make it so the program doesn't 'reroll' the computer-generated number every single loop. This was just a difficult problem for me and I can't seem to understand how to close it out with the correct function calls and niche aspects such as that. Thank you.
run = True
def get_guess():
while run:
guess = input("Provide four unique numbers: ")
count = 0
if len(guess) == 4:
guessdupe = guess[0] == guess[1] or guess[0] == guess[2] or guess[0] == guess[3] or guess[1] == guess[2] or guess[1] == guess[3] or guess[2] == guess[3]
else:
guessdupe = False
try:
try:
for i in range(4):
if int(guess[i]) <= 7 and int(guess[i]) >= 1 and len(guess) == 4:
count += 1
if len(guess) != 4:
print "Your guess must consist of 4 numbers!"
if guessdupe:
count -= 1
print "You can only use each number once!"
except ValueError:
print "You can only use numbers 1-7 as guesses"
except IndexError:
print "You can only use numbers 1-7 as guesses"
if count == 4:
break
return guess
def check_values(computer_list, user_list):
final_list = [''] * 4
for i in range(4):
if user_list[i] in computer_list:
if user_list[i] == computer_list[i]:
final_list[i] = "RED"
else:
final_list[i] = "WHITE"
else:
final_list[i] = "BLACK"
random.shuffle(final_list)
print final_list
return final_list
def check_win(response_list):
if response_list[0] == "RED" and response_list[1] == "RED" and response_list[2] == "RED" and response_list[3] == "RED":
print "Congratulations! You've won the game!"
global finish
finish = True
def create_comp_list():
while run:
compList = [random.randint(1, 7), random.randint(1, 7), random.randint(1, 7), random.randint(1, 7)]
listBool = compList[0] == compList[1] or compList[0] == compList[2] or compList[0] == compList[3] or compList[1] == compList[2] or compList[1] == compList[3] or compList[2] == compList[3]
if listBool:
continue
else:
return compList
def play_game():
for i in range(5):
print create_comp_list()
print get_guess()
check_win(check_values(create_comp_list(), get_guess()))
if finish:
break
play_game()```

Value error when making a rock, paper, scissors game

I have just started programming in Python. I am currently trying to build a rock, paper, scissors game. The user is asked to pick a number representing one of the three options. Whereas the pc picks a random number. However, i get a value error for the input line. The same line worked fine in a different context (no while loop) but I fail to see what I did wrong. Any help would be greatly appreciated.
I have tried to turn the string into a float and then into an integer. That did not work. Moreover, I have replaced the player input number y a random number to test the rest of the code. This worked just fine.
This is the error message I get:
answerplayer = int (input('What is your choice? ')) #Error
ValueError: invalid literal for int() with base 10: "runfile
The code:
import random
win = False
while win == False:
print ('Rock, Paper, Scissors. 0: Rock; 1: Scissors; 2: Paper')
print ('Make your choice')
answerplayer = int (input('What is your choice? ')) #Error
answer = random.randrange (3)
print (answerplayer)
print (answer)
if answer == 0 and answerplayer == 0 :
print ('TIE')
elif answer == 0 and answerplayer == 1 :
print ('PC Win')
win = True
elif answer == 0 and answerplayer == 2 :
print ('Player Win')
win = True
elif answer == 1 and answerplayer == 0 :
print ('Player Win')
win = True
elif answer == 1 and answerplayer == 1 :
print ('TIE')
elif answer == 1 and answerplayer == 2 :
print ('PC Win')
win = True
elif answer == 2 and answerplayer == 0 :
print ('Player Win')
win = True
elif answer == 2 and answerplayer == 1 :
print ('PC Win')
win = True
elif answer == 2 and answerplayer == 2 :
print ('TIE')
else:
print ('Player Win')
win = True
print ('done')
The code is fine. User input must be something that int() can convert to integer however.
Passes: 1 2 3.444
Fails: sqfe zero
you can solve with:
while win == False:
print ('Rock, Paper, Scissors. 0: Rock; 1: Scissors; 2: Paper')
print ('Make your choice')
answerplayer = input('What is your choice? ')
if not answerplayer.isnumeric() :
print ('No number')
break
answerplayer = int(answerplayer)
answer = random.randrange (3)
print (answerplayer)
print (answer)

Python 3 IndentationError

In spite of seeing a lot of posts about the python indentation error and trying out a lot of solutions, I still get this error:
import random
import copy
import sys
the_board = [" "]*10
def printboard(board):
print(board[7] + " " + "|" + board[8] + " " + "|" + board[9])
print("--------")
print(board[4] + " " + "|" + board[5] + " " + "|" + board[6])
print("--------")
print(board[1] + " " + "|" + board[2] + " " + "|" + board[3])
def choose_player():
while True:
player = input("What do you want to be; X or O?")
if player == "X":
print("You chose X")
comp = "O"
break
elif player == "O":
print("You chose O")
comp = "X"
break
else:
print("Invalid Selection")
continue
return [player, comp]
def virtual_toss():
print("Tossing to see who goes first.....")
x = random.randint(0,1)
if x== 0:
print("AI goes first")
move = "comp"
if x == 1:
print("Human goes first")
move = "hum"
return move
def win(board,le):
if (board[7] == le and board[8] == le and board[9]==le) or (board[4] == le and board[5]==le and board[6] == le)or (board[1] == le and board[2]==le and board[3] == le)or (board[7] == le and board[5]==le and board[3] == le)or (board[9] == le and board[5]==le and board[1] == le)or (board[7] == le and board[4]==le and board[1] == le)or (board[8] == le and board[5]==le and board[2] == le)or (board[9] == le and board[6]==le and board[3] == le):
return True
else:
return False
def make_move(board,number,symbol):
board[number] = symbol
def board_full(board):
count = 0
for item in board:
if item in ["X","O"]:
count+= 1
if count ==9 :
return True
else:
return False
def valid_move(board,num):
if board[num] == " ":
return True
else:
return False
def player_move(board):
number = int(input("Enter the number"))
return number
def copy_board(board):
copied_board = copy.copy(board)
return copied_board
def check_corner(board):
if (board[7] == " ") or (board[9] == " ") or (board[1] == " ") or (board[3] == " "):
return True
else:
return False
def check_center(board):
if (board[5] == " "):
return True
else:
return False
while True:
count = 0
loop_break = 0
print("welcome to TIC TAC TOE")
pla,comp = choose_player()
turn = virtual_toss()
while True:
printboard(the_board)
if turn == "hum":
if board_full() == True:
again = input ("Game is a tie. Want to try again? Y for yes and N for No")
if again == "Y":
loop_break = 6
break
else:
system.exit()
if loop_break == 6:
continue
while True:
number = player_move(the_board)
if (valid_move(the_board,number) == True) and not(board_full == False):
make_move(the_board,number,pla)
break
else:
print("Invalid Move, try again!")
continue
if (win(the_board,pla) == True):
print ("Yay, you won!!!")
printboard(the_board)
count = 1
break
else:
turn = "comp"
printboard(the_board)
continue
else:
if board_full() == True:
again = input ("Game is a tie. Want to try again? Y for yes and N for No")
if again == "Y":
loop_break = 6
break
else:
system.exit()
if loop_break = 6:
continue
copy_board(the_board)
for i in range(0,9):
make_move(copied_board,i,pla)
if(win(copied_board,pla) == True):
make_move(the_board,comp)
turn = "hum"
loop_break = 1
break
else:
continue
if loop_break = 1:
continue
if (check_corner(the_board) == True) or (check_center(the_board)==True):
for i in [7,9,1,3,5]:
if(valid_move(copied_board,i)==True):
make_move(copied_board,i,comp)
if(win(copied_board,comp)==True):
make_move(the_board,i,comp)
print("The AI beat you")
loop_break = 2
count = 1
break
else:
make_move(the_board,i,comp)
turn = "hum"
loop_break = 3
break
if loop_break == 2:
break
elif loop_break == 3:
continue
else:
for i in [8,4,6,2]:
if(valid_move(copied_board,i)==True):
make_move(copied_board,i,comp)
if(win(copied_board,comp)):
make_move(the_board,i,comp)
print("The AI beat you")
count = 1
loop_break = 4
break
else:
make_move(the_board,i,comp)
turn = "hum"
loop_break = 5
break
if loop_break == 4:
break
elif loop_break == 5:
continue
if count == 1:
again = input("Would you like to play again? y/n")
if again == "y":
continue
else:
system.exit()
I know that this is quite a long code, but I will point out the particular area where the error lies. You see, I am getting the following error message:
Traceback (most recent call last):
File "python", line 106
if (win(the_board,pla) == True):
^
IndentationError: unindent does not match any outer indentation level
More specifically, this part of the code:
while True:
number = player_move(the_board)
if (valid_move(the_board,number) == True) and not(board_full == False):
make_move(the_board,number,pla)
break
else:
print("Invalid Move, try again!")
continue
if (win(the_board,pla) == True):
print ("Yay, you won!!!")
printboard(the_board)
count = 1
break
Any help? I cannot get the code to work by any means!!
Try unindenting the previous seven lines of code by one level (the code in that while loop). This should make the indents work correctly. Also, it seems that there is an extra space before the if statement that is causing you errors. Remove this space as well. This would make that part of the code like this:
while True:
number = player_move(the_board)
if (valid_move(the_board,number) == True) and not(board_full == False):
make_move(the_board,number,pla)
break
else:
print("Invalid Move, try again!")
continue
if (win(the_board,pla) == True):
print ("Yay, you won!!!")
printboard(the_board)
count = 1
break
You need to indent the block under while (True): consistently. E.g.:
while True:
number = player_move(the_board)
if (valid_move(the_board,number) == True) and not(board_full == False):
make_move(the_board,number,pla)
break
else:
print("Invalid Move, try again!")
continue
if (win(the_board,pla) == True):
print ("Yay, you won!!!")
printboard(the_board)
count = 1
break
else:
turn = "comp"
printboard(the_board)
continue
The problem is, the if statement is one indentation back from the rest of the code. You want to align all the code and the error should go away.
while True:
number = player_move(the_board)
if (valid_move(the_board,number) == True) and not(board_full == False):
make_move(the_board,number,pla)
break
else:
print("Invalid Move, try again!")
continue
if (win(the_board,pla) == True):
print ("Yay, you won!!!")
printboard(the_board)
count = 1
break

Unexplained Invalid Syntax in Python 3.4.2

Whenever I press F5 to run my code, an error message pops up that reads 'invalid syntax', and the space after 'True' in the following line:
while not chosen4 == True
I have no idea what is causing this error.
The rest of the source code is below:
import time
playAgain = False
while not playAgain == True:
gameOver = False
print ("""Press ENTER to begin!
""")
input()
print("""text""")
time.sleep (2)
print ("""text""")
time.sleep (7)
print ("""text""")
print("""(Press a number and then ENTER!)""")
while not gameOver == True:
direction = input ("Your chosen action: ")
print("You chose {0}!".format(direction))
time.sleep (2)
if direction == "1":
print ("""text""")
time.sleep (6)
print ("""text""")
chosen1 = False
while not chosen1 == True:
direction1 = input ("Your chosen action: ")
print ("You chose {0}!".format(direction1))
time.sleep (2)
if direction1 == "3":
print ("""text""")
time.sleep (2)
print("""text""")
time.sleep (8)
print("""text""")
gameOver = True
break
elif direction1 == "4":
print("""text""")
time.sleep (3)
chosen4 = False
while not chosen4 == True
#The above line is where the 'invalid syntax' is.
direction4 = input ("Your chosen action: ")
print "You chose {0}!".format(chosen4)
time.sleep (2)
if chosen4 chosen4 == "7":
print ("text")
gameOver = True
break
elif chosen4 == "8":
print ("text")
gameOver = True
break
else:
tryagain
else:
print ("""text""")
time.sleep (3)
elif direction == "2":
print ("""text""")
time.sleep (2)
print("""text""")
time.sleep (3)
print("""text""")
chosen2 = False
while not chosen2 == True:
direction2 = input ("Your chosen action: ")
print ("You chose {0}!".format(direction2))
time.sleep (2)
if direction2 == "5":
print ("""text""")
time.sleep (8)
gameOver = True
break
elif direction2 == "6":
print ("""text""")
break
else:
print ("""text""")
elif direction == "0":
print ("""text""")
else:
print ("""text""")
if gameOver == True:
input()
You're missing the :
The body of the loop will need to be indented too
This indentation problem jumped out at me too
elif direction1 == "4":
print("""text""")
Missing colon on while not chosen4 == True, it should be while not chosen4 == True:.
You are missing indentation at elif direction1 == "4": on the print statement below.
Also this is not an error but instead of doing while not chosen2 == True: change it to while chosen == False: or while chosen != True: as it helps clean it up.

Categories

Resources