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.
Related
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:
''
just started learning python two days ago
and when I write that code:
command = ""
wrong_words_limit = 5
wrong_words_count = 0
started = False
said_already = False
while True:
command = input("> ").lower()
wrong_words_count += 1
if command == "start":
if started:
print("Car Is Already Started!")
else:
started = True
print("Car Started...")
elif command == "stop":
if not started:
print("Car Is Already Stopped!")
else:
started = False
print("Car Stopped...")
elif command == "hello":
if said_already:
print("Hey AGAIN ")
else:
said_already = True
print("Hey! :) ")
elif command == "help":
print("""
Start - to start the car
Stop - to stop the car
quit - to exit
""")
elif command == "quit":
print("Bye!")
break
else:
while wrong_words_count < 5:
print("Sorry i don't understand")
break
I want the game to end after 5 wrong words, like if someone writes - "sksefl"
or something like that 5 times I want the game to end.
what am I doing wrong? I have been on it for the last 2 hours.
thanks!.
(as you can see I tried to do to that at the end of the code)
You would want to do this in the else statement:
wrong_words_count += 1
print("Sorry i don't understand")
if wrong_words_count == wrong_words_limit:
break
This adds one to the wrong_words_count and then checks if wrong_words_count is equal to the limit, and if it is, breaks the while loop.
command = ""
wrong_words_count = 0
started = False
said_already = False
while True:
if wrong_words_count<5:
command = input("> ").lower()
if command == "start":
if started:
print("Car Is Already Started!")
else:
started = True
print("Car Started...")
elif command == "stop":
if not started:
print("Car Is Already Stopped!")
else:
started = False
print("Car Stopped...")
elif command == "hello":
if said_already:
print("Hey AGAIN ")
else:
said_already = True
print("Hey! :) ")
elif command == "help":
print("""
Start - to start the car
Stop - to stop the car
quit - to exit
""")
elif command == "quit":
print("Bye!")
break
elif wrong_words_count==5:
print("Reached limit. Quitting program...")
break
else:
wrong_words_count += 1
print("wrong words number: ",wrong_words_count)
You can use this code too if you don't want to use wrong_words_limit variable.
I'm trying to create a simple two player game like the classic Battleship. Hence I'm beginning to learn Python and I'm keeping it simple. I have created a 5x5 grid and I want the players (2) to be able to place one ship 1x1 anywhere on the board. Then they take turns guessing where the other person placed their ship.
When I compiled my code I got an indent error on line 61 "else: ". I'm aware that the "H" and "M" for hit and miss will overlap since I'm outputting it to the same playing board.
I guess what I need help with is the while loops in my code.
import sys
#////////////////////////////Setting up board////////////////////////////////////
board = []
for x in range(5):
board.append(["O"] * 5)
def print_board(board):
for row in board:
print " ".join(row)
#///////////////////////////Getting input//////////////////////////////////////////
def user_row():
get_row = raw_input("Enter ship row between 1 and 5")
#Not shure if this is the best way of checking that the input is an int
if int(get_row) == False:
print "You must enter an integer between 1 and 5"
get_row = raw_input("Enter ship row...")
if int(get_row) == False:
sys.exit()
def user_col():
get_col = raw_input("Enter ship col between 1 and 5")
if int(get_col) == False:
print "You must enter an integer between 1 and 5"
get_col = raw_input("Enter ship col...")
if int(get_col) == False:
sys.exit()
#/////////////////////////Intro//////////////////////////////////////////////////////
print "Let's play Battleship!"
print "This is your ocean"
print_board(board)
#////////////////////////Placing ships//////////////////////////////////////////////
print "Player 1 your up!"
print "Player 2 look away!"
print "Place your ship..."
#Not shure if this will call the two functions chronologic and store them as index 0 and 1 in my array. That is what I want it to do
user1_ship = [user_row(), user_col()]
print_board(board)
print "Player 2 your up!"
print "Player 1 look away!"
print "Place your ship..."
user_2 = [user_row(), user_col()]
#///////////////////////guesswork?//////////////////////////////////////////////////
#Maybe while loops inside while loops is not the best way of running the code over and over until someone sinks the other persons ship
#What Im expecting is the first inside while loop to break the outer loop if the player hits the other players ship otherwise break itself. Likewise with the second inner loop.
while True:
while True:
print "Player 1 your turn"
user1_guess = [user_row(), user_col()]
if user1_guess == user2_ship:
board[user1_guess[0]][user1_guess[1]] == "H"
print "PLAYER 1 WINS!"
break
else:
board[user1_guess[0]][user1_guess[1]] == "M"
print "You missed"
break
while True:
print "Player 2 your turn"
user2_guess = [user_row(), user_col()]
if user2_guess == user1_ship:
board[user2_guess[0]][user2_guess[1]] == "H"
print "PLAYER 2 WINS!"
break
else:
board[user2_guess[0]][user2_guess[1]] == "M"
print "You missed"
break
Your indentation is incorrect... Look at this:
while True:
while True:
print "Player 1 your turn"
user1_guess = [user_row(), user_col()]
if user1_guess == user2_ship:
board[user1_guess[0]][user1_guess[1]] == "H"
print "PLAYER 1 WINS!"
break
The break statement must have the same indentation as the print statement like this:
while True:
while True:
print "Player 1 your turn"
user1_guess = [user_row(), user_col()]
if user1_guess == user2_ship:
board[user1_guess[0]][user1_guess[1]] == "H"
print "PLAYER 1 WINS!"
break
If you have some time, please read a Python Styleguide to improve the quality of your code.
Whenever an output should result in a change of shield, the program just says 'You have 5 shields' followed by 'You Win'. I think I might have made a mistake when passing over the variables from one function to the next. Thank you in advance for the help!
def main():
while TakeTurn(word,shield) == False:
if shield == 1:
word1 = "shield"
else:
word1 = "shields"
print ("You have", shield, word1,)
if shield < 1:
print ("Sorry! You ran out of shields! You lose!")
else:
print ("You win")
#This function is the actual 'game' and will deterine what happens to the character
def TakeTurn(word1,shield1):
time.sleep(1.5)
#This means that when the user reaches 0 shields, they lose.
if shield1 < 1:
return True
#Whatever the user inputs will not actually affect the outcome
print ("You have reached", word1 ,"junction.\nDo you want to turn left (L), turn right (R) or go straight ahead(S)?")
turning = input()
#This is a simple instruction that means that the first time you come to a junction, it will say 'a junction' but the second time it will say 'another junction'
word1 = "another"
#This 'if' statement means that the program will only continue if the user has inputed the letters 'L', 'R' or 'S'
elif turning not in ["L","R","S","l","r","s"] :
time.sleep (0.7)
print ("Sorry, I didn't understand that")
TakeTurn()
else:
choice = randint (1,10)
#This is just going to display a random message which will affect the outcome
time.sleep (1)
if choice == 1:
print ("You have found the exit!")
return True
elif choice == 2:
print ("You have found a shield!")
time.sleep(1)
shield1 = shield1 +1
return False
elif choice == 3:
print ("You have found two shields!")
time.sleep(1)
shield1 = shield1 +2
return False
elif choice == 4:
print ("You have found three shields!")
time.sleep(1)
shield1 = shield1 +3
return False
elif choice == 5:
print ("A fairy has jumped into your pants!")
time.sleep(2)
print ("You lose two shields")
time.sleep(1)
shield1 = shield1 -2
return False
elif choice == 6:
treasurechest(shield1)
return False
elif choice == 7:
print ("You have tripped over a log!")
time.sleep(2)
print ("You lose a shield")
time.sleep(1)
shield1 = shield1 -1
return False
elif choice == 8:
print ("An angry teenager is staring at you in the eye.")
time.sleep(2.5)
print ("He uses laziness...")
time.sleep(1.5)
print ("It's super effective!")
time.sleep(1)
print ("You lose three shields")
time.sleep(1)
shield1 = shield1 -3
return False
elif choice == 9:
print ("You have encountered an ogre...")
time.sleep(1.5)
print ("He bashes you over the head with a steel bar")
time.sleep(2)
print ("You lose two shields")
time.sleep(1)
shield1 = shield1 -2
return False
else:
print ("A goblin aproaches and says the following:")
time.sleep(2)
goblin(shield1)
return False
You should refactor main and TakeTurn to make shield and word explicit arguments and return values. This prevents relying on scope for access to variables, without having to use global (which is usually a bad sign):
def main(shield, word):
while True:
shield, word, finished = TakeTurn(shield, word)
if finished:
break
word1 = "shield" if shield == 1 else "shields"
print ("You have {0} {1}".format(shield, word1))
if shield < 1:
print ("Sorry! You ran out of shields! You lose!")
else:
print ("You win")
And have TakeTurn return multiple values accordingly, e.g.:
elif choice == 3:
print ("You have found two shields!")
time.sleep(1)
shield1 = shield1 + 2
return shield1, word1, False
You could make things neater by making choices a list of dictionaries and picking randomly from it:
choices = [{"texts": [("You have found two shields!", 1)],
"shield change": 2, "return": False},
{"texts": [("You have encountered an ogre...", 1.5),
("He bashes you over the head with a steel bar", 2),
("You lose two shields", 1)],
"shield change": -2, "return": False},
...]
Then your main section, instead of all the elifs, becomes simply:
choice = random.choice(choices)
for text, sleep_time in choice['texts']:
print(text)
time.sleep(sleep_time)
shield1 += choice['shield change']
return shield1, word1, choice['return']
Newbie python here. How can I break out of the second while loop if a user selects "Q" for "Quit?"
If I hit "m," it goes to the main menu and there I can quit hitting the "Q" key.
while loop == 1:
choice = main_menu()
if choice == "1":
os.system("clear")
while loop == 1:
choice = app_menu()
if choice == "1":
source = '%s/%s/external' % (app_help_path,app_version_10)
target = '%s/%s' % (target_app_help_path,app_version_10)
elif choice == "2":
source = '%s/%s/external' % (app_help_path,app_version_8)
target = '%s/%s' % (target_app_help_path,app_version_8)
elif choice.lower() == "m":
break
loop = 0
elif choice.lower() == "q":
break
loop = 0
sendfiles(source, target)
# Internal files
elif choice == "q":
loop = 0
App menu method:
def app_menu()
print "Select APP version"
print "-------------------"
print "1) 11"
print "2) 10"
print "3) 8"
print "m) Main Menu"
print "q) Quit"
print
return raw_input("Select an option: ")
You nearly have it; you just need to swap these two lines.
elif choice.lower() == "m":
break
loop = 0
elif choice.lower() == "m":
loop = 0
break
You break out of the nested loop before setting loop. :)
Change
break
loop = 0
to
loop = 0
break
in your elif blocks.
Use an exception.
class Quit( Exception ): pass
running= True
while running:
choice = main_menu()
if choice == "1":
os.system("clear")
try:
while True:
choice = app_menu()
if choice == "1":
elif choice == "2":
elif choice.lower() == "m":
break
# No statement after break is ever executed.
elif choice.lower() == "q":
raise Quit
sendfiles(source, target)
except Quit:
running= False
elif choice == "q":
running= False
Use two distinct variables for both loops, eg loop1 and loop2.
When you first press m in the inner loop you just break outside, and then you can handle q separately.
By the way you shouldn't need the inner variable to keep looping, just go with an infinite loop until key 'm' is pressed. Then you break out from inner loop while keeping first one.
Rename your top loop to something like mainloop, and set mainloop = 0 when q is received.
while mainloop == 1:
choice = main_menu()
if choice == "1":
os.system("clear")
while loop == 1:
choice = app_menu()
if choice == "1":
source = '%s/%s/external' % (app_help_path,app_version_10)
target = '%s/%s' % (target_app_help_path,app_version_10)
elif choice == "2":
source = '%s/%s/external' % (app_help_path,app_version_8)
target = '%s/%s' % (target_app_help_path,app_version_8)
elif choice.lower() == "m":
loop = 0
break
elif choice.lower() == "q":
mainloop = 0break
break
sendfiles(source, target)
# Internal files
elif choice == "q":
mainloop = 0
You could put this into a function and return:
import os.path
def do_whatever():
while True:
choice = main_menu()
if choice == "1":
os.system("clear")
while True:
choice = app_menu()
if choice in ("1", "2"):
app_version = app_version_10 if choice == "1" else app_version_8
source = os.path.join(app_help_path, app_version, "external")
target = os.path.join(target_app_help_path, app_version)
sendfiles(source, target)
elif choice.lower() == "m":
break
elif choice.lower() == "q":
return
Admittedly, I don't quite get when you want to break the inner loop and when you want to quit both loops, but this will give you the idea.