How can I stop if the number is <= 0? [closed] - python

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 3 months ago.
The community reviewed whether to reopen this question 3 months ago and left it closed:
Original close reason(s) were not resolved
Improve this question
I'm trying to stop my program when the Warrior are Priest are both with 0 or < 0 or the vampire goes to 0 our < 0 if not they will not advance for the next round and just finish the battle that way, and set up a winner.
while (warrior[0] and priest[0]) > 0 or vampire[0] > 0: #Loop until all of the group die or the enemy dies
first_turn() #Execute the first turn
if (warrior[0] and priest[0]) > 0 or vampire[0] > 0:
second_turn() #Execute the second turn
if (warrior[0] and priest[0]) > 0 or vampire[0] > 0:
third_turn() #Execute the third turn
if (warrior[0] and priest[0]) > 0 or vampire[0] > 0:
initiative_phase()
else:
break
I've tried the way it is above, but I'm not catching why is it not stopping.

Change the while condition to:
while (warrior[0] > 0 or priest[0] > 0) and vampire[0] > 0:
We added parenthesis Because precedence of logical 'and' is greater than the logical 'or'.
If warrior[0]>0 is true it does not consider whether vampire[0]>0 condition at all.

Seems like you need parentheses.
while ((warrior[0] > 0 or priest[0] > 0) and vampire[0] > 0): #Loop until all of the group die or the enemy dies
execute_turn() #Execute the turn
else: #someone died
break

Related

I don't understand why this code doesn't work :( [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 3 years ago.
Improve this question
I am trying to not accept the username if it is not between 3 and 9 characters.
print (""+winner+", please input your first name, maximum of 10 characters.")
winnername = str(input())
length = (int(len(winnername)))
if 3 > length > 10:
loop5 = 1
while loop5 == 1:
print ("name is too short")
winnername = input()
length = len(winnername)
if (length) <3 and (length) <10:
break
print ("name accept")
I would expect it to loop and ask the user for another input if the provided input doesn't meet the requirements outlined in the above text.
if 3 > length > 10: is checking to make sure that length is LESS than 3 and Greater than 10, which is impossible.
Therefore the check should be if 2 < length < 10: (this will be true for lengths 3 to 9)
Let me fix your code, elegant and clean:
while True:
# I don't know if `winner` is defined
firstname = input(""+winner+", please input your first name, maximum of 10 characters.")
if 3 < len(firstname) < 10:
break
print("name is too short or too long")
print('name accepted')
The problem is 3 > length > 10 will never be executed because 3 will never be greater > than 10
Regarding your first sentence, as far as I can see form the code you are actually trying to allow maximum number of characters to be 10, not 9.
Below is a possible solution for what you're trying to achieve. The below script will keep asking user until name length is within allowed range.
print ("'+winner+', please input your first name, maximum of 10 characters.")
while True:
winnername = str(input())
if(len(winnername) < 3):
print("Name is too short")
elif(len(winnername) > 10):
print("Name is too long")
else:
break
print ("Name accepted")
You may also consider to perform some validation of winnername first (do not allow spaces or any other special characters).
winner = "Mustermann"
# Build a string called "prompt"
prompt = winner + ", please input your first name, between 3 and and 10 characters."
loopLimit = 5 # Make this a variable, so it's easy to change later
loop = 0 # Start at zero
winnername = "" # Set it less than three to start, so the while loop will pick it up
# Put the while loop here, and use it as the length check
# Use an or to explicitely join them
while True: # Set an infinite loop
loop += 1 # Increment the loop here.
# Add the string to the input command. The "input" will use the prompt
# You don't need the "str()", since input is always a string
winnername = input(prompt)
length = len(winnername)
# Separate the checks, to give a better error message
if (length < 3):
print ("Name is too short!") # Loop will continue
elif (length > 10):
print("Name is too long!") # Loop will continue
else: # This means name is OK. So finish
print("Name accepted!")
break # Will end the loop, and the script, since no code follows the loop
if loop >= loopLimit:
# Raise an error to kill the script
raise RuntimeError("You have reached the allowed number of tries for entering you name!")

Why does this loop only once? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 5 years ago.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Improve this question
while count > 0:
if count = 0:
return n
elif count < 0:
print(" ") # prints empty if n is below 0
else:
count = count - 1
collect += math.ceil((n - 5)/2)
return collect
The inputs are (1003, 3) - result is 499, which means it just loop once and subtracts 5 and then divides by 2, then it stops. Anyone know why?
Your inner conditionals don't make sense with the while. And you have a return statement in the loop, so yes, it only looped once.
Start with this
import math
n, count = (1003, 3)
print("N = " + str(n))
while count > 0:
n = math.ceil((n - 5) / 2) # Update this to do whatever your logic is
print(count, n)
count -= 1
if n < 0:
print("N is negative")
else:
print("N = " + str(n))
You have several problems.
First, your syntax isn't indented evenly.
Second, your if statement have = instead of ==. The first one for assigning values to variables, the second is for checking equality.
Third, you have a return statement that's going to exit from whatever function this loop is inside.

Issue with if-else statements [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 6 years ago.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Improve this question
This is what I've input:
def greater_less_equal_5(answer):
if 6 > 5:
return 1
elif 4 < 5:
return -1
else:
return 0
print greater_less_equal_5(4)
print greater_less_equal_5(5)
print greater_less_equal_5(6)
and gave me this note
Oops, try again. It looks like your function output 1 instead of -1
when answer is 3. Make sure you filled in the if and elif statements
correctly!
and this is what came up in the upper right display:
>1
>1
>1
>None
No matter how I change around the numbers and the >/< I've even tried == and != it still outputs 1 1 1 None.
I've searched around for any possible tips and seen others stuck on the same problem as me and when I tried their solves I then get:
def greater_less_equal_5(answer):
if > 5:
return 1
elif < 5:
return -1
else:
return 0
print greater_less_equal_5(4)
print greater_less_equal_5(5)
print greater_less_equal_5(6)
and the output is:
File "python", line 2
if > 5:
^
SyntaxError: invalid syntax
Is this test rigged to always output a failed result to make me pay for pro and ask for their help?
And the hint given for this is:
Make sure the if and elif statements end with colons :
Your code should look something like:
if EXPRESSION:
do something
elif OTHER EXPRESSION:
do something
else:
do something
Am I just missing something horribly basic?
You are indeed missing something basic - namely, that the output of your function doesn't depend on answer at all. No matter what you feed in as answer, because 6 > 5 is always True, it will always return the result of that case.
What you need is
def greater_less_equal_5(answer):
if answer > 5:
return 1
elif answer < 5:
return -1
elif answer == 5:
return 0
You're missing 'answer' variable for expression, which you pass into your function
def greater_less_equal_5(answer):
if answer > 5:
return 1
elif answer < 5:
return -1
else:
return 0
print greater_less_equal_5(4)
print greater_less_equal_5(5)
print greater_less_equal_5(6)

Loop being ignored by Python [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 8 years ago.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Improve this question
I'm a beginner to python, and when trying to see if I could make a simple program myself, I ran into this problem:
class y:
def out(self):
print("restarting")
choice = y
choice.out
while choice == y: # loop until user stops
while j >= 0: # loop until j < 0
print('lives:', j)
j = j - 1
print('out of lives!')
print('restart?')
choice = input(' Y or N ') # Ask user to restart or not
Everything works once, but Python seems to ignore the first loop (while choice == y). Have I forgotten a step, or am I doing this wrong altogether?
I don't think you need a class y here. If you just want to loop until choice isn't the character "y", then you can use ordinary strings.
choice = "y"
while choice == "y": # loop until user stops
j = 3
while j >= 0: # loop until j < 0
print('lives:', j)
j = j - 1
print('out of lives!')
print('restart?')
choice = input(' Y or N ') # Ask user to restart or not
Result:
lives: 3
lives: 2
lives: 1
lives: 0
out of lives!
restart?
Y or N y
lives: 3
lives: 2
lives: 1
lives: 0
out of lives!
restart?
Y or N n
The program loops until the user enters a value other than "y".

Looping problems with python [closed]

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 10 years ago.
I'm trying to loop a battle menu. Although it's not finished yet, I'm having problems looping it. I would like the menu to keep looping until myhp, or hp is lower than 0. so i used "while myhp > 0 or hp > 0:"
it does not work, what am I doing wrong?
def fightmode(name, hp, dmg, gold):
print '\n\n\nYou are in a fight with %s' %name
print '%s has %sHP' %(name, hp)
while myhp > 0 or hp > 0:
hp = hp - mydmg
print '\n\t1. Attack \n\t2. Guard \n\t3. Run away.'
opt1= ''
allowed = ["1", "2", "3"]
while opt1 not in allowed:
opt1 = raw_input("\nWhat will you do? ")
if opt1 == "1":
print "You have inflicted %d damage on %s. %s's HP is %s" %(mydmg, name, name, hp)
if myhp > 0 :
print"myhp"
if hp > 0 :
print"theirhp"
nevermind, I think I got it. I changed "or" to "and" and it seems like it's working.
Was this the right method?
Right now you need myhp OR hp to be true for the while loop to continue going.
So if one of them drops to 0 and thus "goes False" the other one is still going to be true and keep the loop going.
So how can you do something about that?? (You already guessed right... Use and instead!)
So while myhp > 0 or hp > 0: should be while myhp > 0 and hp > 0: (Note that the or is exchanged for and!)
Because while loop lopping until Boolean expression is true and stops after expression get false
So you need to write while myhp < 0 or hp < 0:

Categories