Turn-Based Text-Fighter: Indent Error - python

I am a Python newb.
I keep getting indent errors around the if statements of my code.
The first chunk of if/else statements are read fine.
The second chunk results in indent errors.
When I remove it for debugging.
The third chunk (at the end) also returns indent errors.
...but I'm not sure where to find them?
Any suggestions on what's going wrong?
# Begin Fight/Conditions for Ending
while Player.hp > 0 and Marco.hp > 0:
while playerchoice not in [1,2,3,4]:
playerchoice = input("\n Which move would you like to use: ")
marcochoice = random.choice([1,2,3,4])
# Making the Moves - Player Always Goes First (For now!)
if playerchoice == 1:
Player.jabs(Marco)
#print("\n Player - jabs - Debug")
elif playerchoice == 2:
...
else:
#print("Player - Non-Choice - Debug")
# Marco's Turn!
if Marco.hp > 0:
if marcochoice == 1:
Marco.jabs(Player)
#print("Marco - Jabs - Debug")
...
else:
#print("Marco - Non-Choice - Debug")
else:
pass
# Ending Conditional
if Marco.hp <= 0 and Player.hp <= 0:
print("It's a draw!")
...
else:
print("Something has gone horribly wrong!")

It's not the quotation marks. I made that error when transferring the code to stackoverflow (modified the code for readability/compactness).
The error is with the comments by some of the else statements.
Python never reads/executes anything, so it just assumes whatever follows is supposed to be indented.
Once I put pass underneath the else statements, everything cleared up.

Assuming you try to run this exact code you posted, the problem is the comment after you first 'else:' statement. The same happens here:
for i in range(10):
if i in [0,1,2,3,4,6,7,8,9]:
print("found")
else:
#print("test")
print("that could be it")
To run without problems just uncomment the second print statement.
Hope that helps.

It looks like your forgot the double quote
playerchoice = input("\n Which move would you like to use: ")
The color of the text could have helped you ;)

Related

Don't know why it's rejecting my else statement

drinks = 5
if drinks <= 2:
print("Keep going buddy")
elif drinks == 3:
print("I believe you've had enough, sir")
else:
print("stop")
This was the code I was trying to run, and it keeps giving me a syntax error with the "else" and I don't know why.
Your syntax is wrong. Remove the space before the else:
The syntax of your code is labeled as incorrect because an else statement and clause cannot exist without an if statement and clause preceding it. Since you have an else statement alone inside an elif clause, an error is thrown.
Likely this is just an issue with your indentation, which you need to be very careful about, since Python emphasizes whitespace. Here is the code I believe you meant to type:
drinks = 5
if drinks <= 2:
print("Keep going buddy")
elif drinks == 3:
print("I believe you've had enough, sir")
else:
print("stop")

Does if/else statements require continue?

I am a beginner in Python and from what I understand, the continue statement in Python returns the control to the beginning of the while loop.
guesses = [0]
while True:
# we can copy the code from above to take an input
guess = int(input("I'm thinking of a number between 1 and 100.\n What is your guess? "))
if guess < 1 or guess > 100:
print('OUT OF BOUNDS! Please try again: ')
continue
# here we compare the player's guess to our number
if guess == num:
print(f'CONGRATULATIONS, YOU GUESSED IT IN ONLY {len(guesses)} GUESSES!!')
break
# if guess is incorrect, add guess to the list
guesses.append(guess)
# when testing the first guess, guesses[-2]==0, which evaluates to False
# and brings us down to the second section
if guesses[-2]:
if abs(num-guess) < abs(num-guesses[-2]):
print('WARMER!')
else:
print('COLDER!')
else:
if abs(num-guess) <= 10:
print('WARM!')
else:
print('COLD!')
Above is the code for the game called 'guess the number from 1 - 100'.
The first if statement where guess < 1 or guess > 100, it will print "Out of bounds!" and then continue which loops to the top of the code and asks for the user's input again.
But for the 3rd if statement where if guesses[-2]:, it does not require continue for neither if nor else.
Sorry if you do not understand what I am asking. But essentially, I want to know why 'continue' statement is not required after print('WARMER!), print('COLDER!'), print('WARM!') and print('COLD!').
guesses = [0]
while True:
# we can copy the code from above to take an input
guess = int(input("I'm thinking of a number between 1 and 100.\n What is your guess? "))
if guess < 1 or guess > 100:
print('OUT OF BOUNDS! Please try again: ')
continue
# here we compare the player's guess to our number
if guess == num:
print(f'CONGRATULATIONS, YOU GUESSED IT IN ONLY {len(guesses)} GUESSES!!')
break
# if guess is incorrect, add guess to the list
guesses.append(guess)
# when testing the first guess, guesses[-2]==0, which evaluates to False
# and brings us down to the second section
if guesses[-2]:
if abs(num-guess) < abs(num-guesses[-2]):
print('WARMER!')
**continue**
else:
print('COLDER!')
**continue**
else:
if abs(num-guess) <= 10:
print('WARM!')
**continue**
else:
print('COLD!')
**continue**
Note that all four of these print statements are the last of their execution branch.
Meaning, if guesses[-2] evaluates as true, than the else part won't be executed at all. Then, if abs(num-guess) < abs(num-guesses[-2]) evaluates to true, again - its else won't be executed. It means that for this execution branch the print('WARMER!') is the last statement of the loop and hence continue is not needed.
Same logic applies to all other 3 print statements.
In the case "guess < 1 or guess > 100" you want to skip the rest of the loop since you dont want to append the guess to the guesses list. Therefore you use continue.
The 'continue' statement is not required after print('WARMER!) etc because you dont need to skip any code afterwards. In this case because there wont be any lines executed after the print statement anyway.
First of all, if/else doesn't require continue. It's optional.
From what I understand you want to know why you used continue in the first if/else and not in the last if/else.
In the first one, after executing if statement it will transfer the control to while True: but for the last if/else statement it is not needed as the control will automatically go to while True: as it is the end of the loop and even if you had used continue it wouldn't have made a difference.
For further references
If you want to know why the continue is not always in if or else, this is due to the fact that when the operation arrives (true), the loop is exited and the code continues to run.

python - checking string for certain words

What I'm trying to do is that, if I ask a question only answerable by Yes and
No, I want to make sure that yes or no is the answer. Otherwise, it will stop.
print("Looks like it's your first time playing this game.")
time.sleep(1.500)
print("Would you like to install the data?")
answer = input(">").lower
if len(answer) > 1:
if answer == "no":
print("I see. You want to play portably. We will be using a password system.")
time.sleep(1.500)
print("Your progress will be encrypted into a long string. Make sure to remember it!")
else:
print("Didn't understand you.")
elif len(answer) > 2:
if word == "yes":
print("I see. Your progress will be saved. You can back it up when you need to.")
time.sleep(1.500)
else:
print("Didn't understand you.")
First:
answer = input(">").lower
should be
answer = input(">").lower()
Second, len(answer) > 1 is true for both "no" and "yes" (and anything larger than one character, for that matter). The elif block will never be evaluated. Without modifying significantly the logic of your current code, you should do instead:
if answer == 'no':
# do this
elif answer == 'yes':
# do that
else:
print("Didn't understand you.")
Something like:
if word.lower() in ('yes', 'no'):
would be the simplest approach (assuming case doesn't matter).
Side-note:
answer = input(">").lower
Is assigning a reference to the lower method to answer, not calling it. You need to add parens, answer = input(">").lower(). Also, if this is Python 2, you need to use raw_input, not input (In Python 3, input is correct).

If and elif in Python for good programming practices

Hello there I'm currently trying to get a good grasp of the if, elif, else structure in Python. I'm trying some weird combinations in python having a test program to know the output in this if, if, elif, elif, else code. However I'm getting weird results such as this
input = raw_input('Please enter the required digit: ')
intput = int(input)
if intput == 0:
print 'if1'
if intput == 1:
print 'if2'
elif intput == 0:
print 'elif1'
elif intput == 1:
print 'elif2'
else:
print 'else'
if I in put 1 it will print "if2", I thought that it will also print "elif2" and other shenanigans when I try to change the "intput == n" code. So my question is do I have to stick to the if,elif, elif, .... n * elifs, else method which seems to me working alright than working with the wacky if,if.... n * ifs, elif, elif, ...n* elifs, else.
Thanks
The elif tree is designed such that at anywhere along if one of the statement turns out to be True, the rest of the elifs will not be evaluated.
Here's a tutorial that might help you understand if else better.
this may be more clear to understand:
if input == 0:
print "if1"
switch(input):
case 1:
print "if2"
break
case 0:
print "elif1"
break
case 1:
print "elif2"
break
default:
print "else"
break
of course, the code does not work.

trying to loop to the beginning of a function(sort of) in python

I am trying to go back to the top of a function (not restart it, but go to the top) but can not figure out how to do this. Instead of giving you the long code I'm just going to make up an example of what I want:
used = [0,0,0]
def fun():
score = input("please enter a place to put it: ")
if score == "this one":
score [0] = total
if score == "here"
if used[1] == 0:
score[1] = total
used[1] = 1
elif used[1] == 1:
print("Already used")
#### Go back to score so it can let you choice somewhere else.
list = [this one, here]
I need to be able to go back so essentially it forgets you tried to use "here" again without wiping the memory. All though I know they are awful, I basically need a go to but they don't exist in python. Any ideas?
*Edit: Ah sorry, I forgot to mention that when it's already in use, I need to be able to pick somewhere else for it to go (I just didn't want to bog down the code). I added the score == "this one"- so if I tried to put it in "here", "here" was already taken, it would give me the option of redoing score = input("") and then I could take that value and plug it into "this one" instead of "here". Your loop statement will get back to the top, but doesn't let me take the value I just found and put it somewhere else. I hope this is making sense:p
What you are looking for is a while loop. You want to set up your loop to keep going until a place is found. Something like this:
def fun():
found_place = False
while not found_place:
score = input("please enter a place to put it: ")
if score == "here"
if used[1] == 0:
score[1] = total
used[1] = 1
found_place = True
elif used[1] == 1:
print("Already used")
That way, once you've found a place, you set found_place to True which stops the loop. If you haven't found a place, found_place remains False and you go through the loop again.
As Ashwini correctly points out, you should do a while loop
def fun():
end_condition = False
while not end_condition:
score = input("please enter a place to put it: ")
if score == "here":
if used[1] == 0:
score[1] = total
used[1] = 1
elif used[1] == 1:
print("Already used")

Categories