Python 3.6 elif syntax error - python-3.x

using a nested if statement and my indentation seems correct thru out yet still reviving a syntax error.thank you
# FIGHT Dragons
if ch3 in ['y', 'Y', 'Yes', 'YES', 'yes']:
# WITH SWORD
if sword == 1:
print ("You only have a sword to fight with!")
print ("You quickly jab the Dragon in it's chest and gain an advantage")
time.sleep(2)
print ("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~")
print (" Fighting... ")
print (" YOU MUST HIT ABOVE A 5 TO KILL THE DRAGON ")
print ("IF THE DRAGON HITS HIGHER THAN YOU, YOU WILL DIE")
print ("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~")
time.sleep(2)
fdmg1 = int(random.randint(3, 10))
edmg1 = int(random.randint(1, 5))
print ("you hit a", fdmg1)
print ("the dragon hits a", edmg1)
time.sleep(2)
if edmg1 > fdmg1:
print ("The drgon has dealt more damage than you!")
complete = 0
return complete
this is where i run into a syntax error
elif fdmg1 < 5:
print ("You didn't do enough damage to kill the drgon, but you manage to escape")
complete = 1
return complete
else:
print ("You killed the drgon!")
complete = 1
return complete

Your return must be at the end of the if...elif...else statement. This works :
if edmg1 > fdmg1:
print ("The drgon has dealt more damage than you!")
complete = 0
elif fdmg1 < 5:
print ("You didn't do enough damage to kill the drgon, but you manage to escape")
complete = 1
else:
print ("You killed the drgon!")
complete = 1
return complete
Note that if the first if-condition is True, Python won't check for the subsequent ones.

Related

def and return error in python2

Hey I'm working on a console game and I have a problem.Firstly the program should work as follows:
User chooses an attack power,
an attack with magnitude M will be successful with a chance of (100-M)%. That is, higher magnitude means higher risk of missing it. For instance, if M is 30, the chance of succeeding would 70%, whereas M if 10, the probability of succeeding would be 90%.If the attack is succesfull hp will decrease and the program will display hp's of players.I wrote something:
import random
def attack1():
hp2=100
chance_of_damaging=random.randint(0,100)
print "your chance of damaging", chance_of_damaging
while True:
attack_magnitute=input("Choose your attack magnitude between 1 and 50: ")
if attack_magnitute > 50:
print "The attack magnitude must be between 1 and 50."
elif attack_magnitute < 1:
print "The attack magnitude must be between 1 and 50."
else:
break
while True:
if chance_of_damaging > attack_magnitute:
print "attack is succesful"
hp2=hp2-attack_magnitute
return hp2
else:
print "attack is unsuccesful"
return hp2
print attack1()
def attack2():
hp1=100
chance_of_damaging=random.randint(0,100)
print "your chance of damaging", chance_of_damaging
while True:
attack_magnitute=input("Choose your attack magnitude between 1 and 50: ")
if attack_magnitute > 50:
print "The attack magnitude must be between 1 and 50."
elif attack_magnitute < 1:
print "The attack magnitude must be between 1 and 50."
else:
break
while True:
if chance_of_damaging > attack_magnitute:
print "attack is succesful"
hp1=hp1-attack_magnitute
return hp1
else:
print "attack is unsuccesful"
return hp1
print attack2()
The program should continue to run until one of the hp values is equal zero
When I try to call the hp1 or hp2 variable, the value is deleted.
Can someone help me with where I made mistakes?I have to submit my project in 30 hours.Thanks in advance.
Look at the new main funtion at the bottom, the hp values are passed in and returned instead of being reinitialized at the beginning of the attack functions. The loop continues until one of the hps is <= 0
import random
def attack1(current_hp):
hp2=current_hp
chance_of_damaging=random.randint(0,100)
print "your chance of damaging", chance_of_damaging
while True:
attack_magnitute=input("Choose your attack magnitude between 1 and 50: ")
if attack_magnitute > 50:
print "The attack magnitude must be between 1 and 50."
elif attack_magnitute < 1:
print "The attack magnitude must be between 1 and 50."
else:
break
while True:
if chance_of_damaging > attack_magnitute:
print "attack is succesful"
hp2=hp2-attack_magnitute
return hp2
else:
print "attack is unsuccesful"
return hp2
def attack2(current_hp):
hp1=current_hp
chance_of_damaging=random.randint(0,100)
print "your chance of damaging", chance_of_damaging
while True:
attack_magnitute=input("Choose your attack magnitude between 1 and 50: ")
if attack_magnitute > 50:
print "The attack magnitude must be between 1 and 50."
elif attack_magnitute < 1:
print "The attack magnitude must be between 1 and 50."
else:
break
while True:
if chance_of_damaging > attack_magnitute:
print "attack is succesful"
hp1=hp1-attack_magnitute
return hp1
else:
print "attack is unsuccesful"
return hp1
def main():
hp1, hp2 = (100,100)
while hp1 > 0 and hp2 > 0:
hp1 = attack1(hp1)
hp2 = attack2(hp2)
main()
EDIT:
If you want to print out the final state of hp1 and hp2 make your def main() like this:
def main():
hp1, hp2 = (100,100)
while hp1 > 0 and hp2 > 0:
hp1 = attack1(hp1)
hp2 = attack2(hp2)
print "Final State of hp1: " + str(hp1)
print "Final State of hp2: " + str(hp2)

How to break only one nested loop?

My code appears like this:
shop = input("Do you want to enter the shop?")
if shop == "y":
print ("["+shopownername+"]: Welcome to my store.")
sleep(1)
print ("["+shopownername+"]: Here are the items for sale:")
for x in shopitems:
print (x)
sleep(1)
print ("You have "+str(gold)+" gold.")
sleep(1)
choice = 0
while choice != "exit":
choice = input("What would you like to buy? Type 'exit' and enter to leave.")
if choice == "a":
purchase = "a"
confirm = input("Are you sure you want to buy "+purchase+"? (y/n)")
if confirm == "y":
if "a" in weapons:
print ("You already have that.")
break
elif gold < shopitems[purchase]:
print ("You do not have enough gold for that.")
break
else:
gold = gold - shopitems[purchase]
weapons.append("a")
print ("You have purchased the "+purchase+".")
print ("You now have "+str(gold)+" gold.")
break
elif choice == "b":
purchase = "b"
confirm = input("Are you sure you want to buy "+purchase+"? (y/n)")
if confirm == "y":
if "b" in weapons:
print ("You already have that.")
break
elif gold < shopitems[purchase]:
print ("You do not have enough gold for that.")
break
else:
gold = gold - shopitems[purchase]
weapons.append("b")
print ("You have purchased the "+purchase+".")
print ("You now have "+str(gold)+" gold.")
break
else:
print ("["+shopownername+"]: Thank you for coming.")
else:
print ("You did not enter the shop.")
What it is supposed to do is that in any case until you exit the shop, you will be able to buy items. However, in this system, it breaks the while as well, and proceeds to the next piece of code. What I should be able to do is try to buy a, and no matter if I cannot afford it, already own it, or have bought it, can both attempt to buy b or try to re-buy a.
What should I do?

Simple calculator works in Python 2 but not 3

This calculator works in Python 2:
print ("First calculator!")
print ("")
firstnum=input ("Insert the first number: ")
print ("")
print ("Available operations:\n 1:Addition\n 2:Subtraction\n 3:Multiplication\n 4:Division\n")
operation=input ("Insert the number of operation: ")
if int(operation) >4:
print ("You mistyped")
exit(0)
print ("")
secondnum=input ("Insert the second number: ")
if operation == 1:
print ("The result is:", firstnum+secondnum)
if operation == 2:
print ("The result is:", firstnum-secondnum)
if operation == 3:
print ("The result is:", firstnum*secondnum)
if operation == 4:
print ("The result is:", firstnum/secondnum)
But in Python 3 the script does nothing after accepting input.
--UPDATE--
After fixing thanks the help of #moses-koledoye, I'll post the final source code, it could be help for some other newbie.
print ("First calculator!")
print ("")
firstnum=input ("Insert the first number: ")
print ("")
print ("Available operations:\n 1:Addition\n 2:Subtraction\n 3:Multiplication\n 4:Division\n")
operation=input ("Insert the number of operation: ")
if int(operation) >4:
print ("You mistyped")
exit(0)
print ("")
secondnum=input ("Insert the second number: ")
firstnum=int(firstnum)
secondnum=int(secondnum)
print ("")
if operation == "1":
print ("The result is:", firstnum+secondnum)
elif operation == "2":
print ("The result is:", firstnum-secondnum)
elif operation == "3":
print ("The result is:", firstnum*secondnum)
elif operation == "4":
print ("The result is:", firstnum/secondnum)
You're comparing strings with integers:
if operation == 1 # '1' == 1
will always be False, so none of the if blocks is executed.
Do a string-string comparison instead:
if operation == '1'
And when the if block conditions are fixed, others bugs will show up:
firstnum + secondnum
This will concat your strings and not perform a numerical operation as you intend, while operation -, * and / will raise TypeError. You should cast your operands, firstnum and secondnum to the appropriate type: float or int.
Besides, you could also chain all the if clauses into one if-elif clause

How to use a while loop to make code continue?

Sorry, I tried researching about while loops and the examples that I found didn't help me very much. I am having a hard time understanding the concept outside of peoples examples. I am new to python and most tutorials use a while loop in a different scenario. So here is my code:
# This is a guess the number game.
import random
# Ask the user what their name is
print ('Hello. What is your name?')
name = input ()
# Ask the user if they would like to play a game.
# If user confirms, game continues
# If user denies, game ends
print ('Hi ' + name + ' It is nice to meet you.')
print ('Would you like to play a game with me?')
answer = input()
confirm = ['Yes', 'yes',' Y', 'y', 'Yea', 'yea', 'Yeah', 'yeah', 'Yup', 'yup']
deny = ['No', 'no', 'N', 'n', 'Nope', 'nope', 'Nah', 'nah']
if answer in confirm:
print ('Great! Let\'s get started!')
elif answer in deny:
print ('I am sorry to hear that. Maybe next time? Goodbye') + exit()
print ('I am thinking of a number between 1 and 20.')
print ('Can you guess what the number is?')
secretNumber = random.randint (1, 20)
print('DEBUG: The secret number is ' + str(secretNumber)) # DEBUG
for guessesTaken in range (1, 7):
print ('Take a guess.')
guess = int(input())
if guess < secretNumber:
print ('Your guess is to low.')
elif guess > secretNumber:
print ('Your guess is to high!')
else:
break # This condition is for the correct guess!
if guess == secretNumber:
print ('Good job, ' + name + '! You guessed the number in ' + str(guessesTaken) + ' guesses.')
else:
print ('Wrong. The number I was thinking of was ' + str(secretNumber))
print ('Would you like to play again?')
play_again = input()
if play_again in confirm:
print('# Put code to make game restart')
elif play_again in deny:
print ('Thanks for playing!')
exit()
I would like to use a while loop (because I think thats what I need, please enlighten me if not) at the "if play_again in confirm:" statement to make it return back to the "I am thinking of a number between 1 and 20" line. That way a user can continue to play the game if they choose.
Thankyou in advance. I am also using newest Python.
Your code with while loop added:
# This is a guess the number game.
import random
# Ask the user what their name is
print ('Hello. What is your name?')
name = input ()
# Ask the user if they would like to play a game.
# If user confirms, game continues
# If user denies, game ends
print ('Hi ' + name + ' It is nice to meet you.')
print ('Would you like to play a game with me?')
answer = input()
confirm = ['Yes', 'yes',' Y', 'y', 'Yea', 'yea', 'Yeah', 'yeah', 'Yup', 'yup']
deny = ['No', 'no', 'N', 'n', 'Nope', 'nope', 'Nah', 'nah']
if answer in confirm:
print ('Great! Let\'s get started!')
elif answer in deny:
print ('I am sorry to hear that. Maybe next time? Goodbye') + exit()
while True:
print ('I am thinking of a number between 1 and 20.')
print ('Can you guess what the number is?')
secretNumber = random.randint (1, 20)
print('DEBUG: The secret number is ' + str(secretNumber)) # DEBUG
for guessesTaken in range (1, 7):
print ('Take a guess.')
guess = int(input())
if guess < secretNumber:
print ('Your guess is to low.')
elif guess > secretNumber:
print ('Your guess is to high!')
else:
break # This condition is for the correct guess!
if guess == secretNumber:
print ('Good job, ' + name + '! You guessed the number in ' + str(guessesTaken) + ' guesses.')
else:
print ('Wrong. The number I was thinking of was ' + str(secretNumber))
print ('Would you like to play again?')
play_again = input()
if play_again in confirm:
#print('# Put code to make game restart')
continue
elif play_again in deny:
print ('Thanks for playing!')
break
exit()
Here is a simplified version of what you are trying to do, using a while loop.
import random as rand
target = rand.randint(1,100)
found = False
while not found:
print ("***Random Number Guess***")
guess = int(input("What is your guess?"))
if guess == target:
print("Good guess, you found it!")
repeat = input("Play again? y/n")
if repeat == 'n':
found = True
elif repeat == 'y':
target = rand.randint(1,100)
found = False
else:
if guess < target:
print("too low")
else:
print("too high")

Variable not Defined in Python 3.5.1

I am a new coder with Python and I was wondering how I can fix this bug. Every time i put in the correct input in the code that I have, it spits out an error message, like so.
The code
total = 12
print ("I will play a game, you will choose 1, 2, or 3, and I will do the same, and I should always win, do you want to play?")
yesnoA = input("Yes or No?")
if yesnoA == yes:
print ("Yay, your turn!")
turnAA = input('Your First Move')
if turnAA == 1:
print ("I choose 3")
total = total - 4
print ("Total = ",total)
else:
if turnAA == 2:
print ("I choose 2")
total = total - 4
print ("Total = ",total)
else:
if turnAA == 3:
print ("I choose 1")
total = total - 4
print ("Total = ",total)
else:
print ("Cheater, try again")
else:
yesnoB = input("Ok, you sure?")
if yesnoB == yes:
print ("Yay, your turn")
turnAA = input('Your First Move')
if turnAA == 1:
print ("I choose 3")
total = total - 4
print ("Total = ",total)
else:
if turnAA == 2:
print ("I choose 2")
total = total - 4
print ("Total = ",total)
else:
if turnAA == 3:
print ("I choose 1")
total = total - 4
print ("Total = ",total)
else:
print ("Cheater, try again")
else:
print ("Well, goodbye")
The Output
Yes or No?yes
Traceback (most recent call last):
File "C:/Users/*user*/Desktop/Code/Python/Nim Game.py", line 5, in <module>
if yesnoA == yes:
NameError: name 'yes' is not defined
This is in version 3.5.1
You need to either declare a variable yes with a value 'yes', or compare your variable yesnoA with a string 'yes'. Maybe something like this:
if yesnoA.lower() == 'yes': # using lower(), so that user's input is case insensitive
# do the rest of your work
Your code afterwards has some more issues. I will give you a clue. input always returns the user's input as string. So if you need integer from user, you will have to convert the user input into integer using int(your_int_as_string) like so:
turnAA = int(input('Your First Move'))
# turnAA is now an integer, provided the user entered valid integer value
Your take from this question on SO:
Look at the Traceback. It says clearly which line the error is in, and also what the error is. In your case it is NameError
Take a look at docs for NameError
Study this tutorial. It will help you get used to with some basic errors commonly encountered.
You have not defined the variable yes. You should do something like:
yes = "Yes"
At the start of the code
You're attempting to compare yesnoA to a variable named yes, which, indeed was not defined, instead of the string literal 'yes' (note the quotes!). Add the quotes and you should be fine:
if yesnoA == 'yes':
# Here --^---^

Resources