Looping problems with python [closed] - python

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:

Related

I am learning python and can't figure out what I am doing wrong in this problem for my homework [closed]

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 8 days ago.
Improve this question
I have this homework problem that I just can't figure out how to fix. I looked around a bit to see if anyone else had asked about it but could not find anything that worked better than what I was trying. Here is the problem.
"This is a slight adaptation of the problem 51134 in myprogramming lab. Here is the modified problem for homework
You work for a bakery that sells two items: muffins and cupcakes. The number of muffins and cupcakes in your shop at any given time is stored in the variables muffins and cupcakes which you will define, and the store has 10 muffins and 10 cupcakes.
Write a program that takes strings from standard input indicating what your customers are buying ("muffin" for a muffin, "cupcake" for a cupcake). If they buy a muffin, decrease muffins by one, and if they buy a cupcake, decrease cupcakes by 1. If there is no more of that baked good left, print ("Out of stock").
Once you are done selling, input "0", and have the program print out the number of muffins and cupcakes remaining, in the form "muffins: 9 cupcakes: 3" (if there were 9 muffins and 3 cupcakes left, for example)."
And here is the code I came up with but doesn't seem to be working.
muffins = 10
cupcakes = 10
a = input("Enter the item: ")
while a != '0' or (muffins==0 and cupcakes==0):
if a == 'muffin':
if muffins>0:
muffins-=1
else:
print("Zero muffins.")
if a == 'cupcake':
if cupcakes>0:
cupcakes-=1
else:
print("Zero cupcakes.")
a = input("Enter the item: ")
if muffins==0 and cupcakes==0:
print("Out of stock")
break
print("muffins: %d cupcakes: %d" %(muffins, cupcakes))
I would really appreciate if I could get some help figuring this out. Thank you.
Hey #BurnsRobison you have coded well but there are minor changes required to get the output as expected. please find the modified snippet
muffins = 10
cupcakes = 10
while (muffins!=0 and cupcakes!=0):
a = input("Enter the item: ")
if a == '0':
print("Order Completed!")
break
if a == 'muffin':
if muffins>0:
muffins-=1
else:
print("Zero muffins.")
elif a == 'cupcake':
if cupcakes>0:
cupcakes-=1
else:
print("Zero cupcakes.")
else:
print("Please select either muffin or cupcake")
if muffins==0 and cupcakes==0:
print("Out of stock")
break
print("muffins: %d cupcakes: %d" %(muffins, cupcakes))
One problem with the code is even if muffins or cupcakes become 0, the input is being asked, and only if we give the answer, the loop breaks out. And the second problem is optimization of code to effectively use variables. I've corrected the use in the answer so just check it
try this one
muffins = 10
cupcakes = 10
a = ''
while a != '0':
a = input("Enter the item: ")
if a == 'muffin':
if muffins > 0:
muffins -= 1
else:
print("Out of stock")
if a == 'cupcake':
if cupcakes > 0:
cupcakes -= 1
else:
print("Out of stock")
print("muffins: %d cupcakes: %d" % (muffins, cupcakes))

What is wrong with my code? I am a newbie and I don't know why it isn't working. (Python)

Sorry, I've only been using python for about an hour, I'm using PyCharm if that has to do with the problem, I don't think it does though.
Here is my code:
userAge = input("Hi, how old are you?\n")
longRussiaString = (
"When will you guys stop telling me about how you had to walk uphill both ways for 10 miles to"
"get to school amidst the icy tundra of Russia? We get it!")
def reply_detect():
if userAge != 0 - 5:
pass
else:
print("Wait a minute... Stop lying! I know your brain is too small for this!")
if userAge != 6 - 18:
pass
else:
print("You're too young to be interested in this. Unless your dad forced you to just like me :(")
if userAge != 19 - 24:
pass
else:
print("""Good luck dealing with those "taxes" things or whatever. Wait, you haven't heard of those?""")
if userAge != 25 - 40:
pass
else:
print("You post-millennial scumbags... No, just kidding, you guys are the ones carrying our society.")
if userAge != 41 - 55:
pass
else:
print(longRussiaString)
def age_reply():
print(f"So, you're {userAge} years old, huh?")
reply_detect()
age_reply()
I tried to inverse the if loops making a second function to neaten things up a bit, and lots of other things, what happens is that it shows the "So, you're {userAge} years old part, but it ends there and doesn't show me the rest, which is the function "reply_detect".
Thanks!
It seems you're looking to see if a number occurs in a range. This can be accomplished very directly in Python. Just remember that the end of the range is exclusive: 0 to 5 is covered by range(0, 6).
>>> n = 16
>>> n in range(0, 17)
True
>>> n in range(0, 6)
False
>>> n not in range(0, 6)
True
>>>
you are using a test of 0 - 5 but to python this means zero minus five which is negative five, just as you would do in a calculator. Instead you mean if userAge >= 0 and userAge <= 5 and so on for the remaining tests.

Variable not increasing when using += [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 7 months ago.
Improve this question
I have been working on this project and I am trying to make a hunger system.
I have the remove hunger after a certain amount of time set up but when I use my "eating system" it just wont increase. I use hunger += 50 to add but it just stays at 50...
Here is my code if you wanna take a look
This is the start of the loop, I'm not sure if I should have the hunger variable inside or outside of the loop...
def ifhealthlessthan50():
while health >0:
hunger = 50
this is the periodic hunger loss system...
def hungerSystemThread():
global hunger
while True:
time.sleep(65)
hunger = hunger - 15
print("\nYOU HAVE LOST SOME OF YOUR HUNGER\n>")
ifhealthlessthan50()
if hunger <= 0:
print("YOU HAVE RUN OUT OF HUNGER AND DIED!")
intro()
this is the eating system...
elif choice2.lower() == 'eat':
eatingsystem = input("WHAT WOULD YOU LIKE TO EAT?\n> ")
if hunger <= 99:
if eatingsystem.lower() == "apple":
if things['APPLE'] > 1:
print("eating...")
time.sleep(3)
hunger += 50
things['APPLE'] -= 1
print("ONE APPLE EATEN")
ifhealthlessthan50()
elif hunger >= 100:
print("YOU CANNOT EAT!")
ifhealthlessthan50()
keep in mind, the ifhealthlessthan50() doesn't actually mean if the health is less than 50, its just the def() that I got too far along to change, its basically the whole loop that the entire code is in.
every time you call ifhealthlessthan50(), you reset the health to 50.
Even though you are increasing the hunger correctly with hunger += 50, you immediately set it back to 50 with the call to the function, as the while condition is true.
Perhaps you need to review your logic and clarify what you want the while health > 0: loop to do. If ifhealthlessthan50(), is your main game loop, you need not reset the value of hunger every time you call it.

My "while loop" not working as expected

I am a new coder, sorry if my question is bad or I am not following proper etiquette!
I am designing a basic program that rolls dice. It is supposed to roll dice until the total points of either the computer or the user equals 100. However, even though my point totaler is working, the loop won't end. Anyone know why this is? Thank you!
def main():
GAME_END_POINTS = 100
COMPUTER_HOLD = 10
is_user_turn = True
user_pt = 0
computer_pt = 0
welcome()
while computer_pt < GAME_END_POINTS or user_pt < GAME_END_POINTS:
print_current_player(is_user_turn)
if is_user_turn is True:
user_pt = user_pt + take_turn(is_user_turn, COMPUTER_HOLD)
elif is_user_turn is False:
computer_pt = computer_pt + take_turn(is_user_turn, COMPUTER_HOLD)
report_points(user_pt, computer_pt)
is_user_turn = get_next_player(is_user_turn)
The condition is always True because either the computer or the user will have a points total less than 100.
Instead of or use and:
while computer_pt < GAME_END_POINTS and user_pt < GAME_END_POINTS:
Now the loop will continue only when both the user and the computer have a points total less than 100. As soon as one of them has more than 100 the condition will be be False and the loop will terminate.
You while loop will only end if both computer_pt >= GAME_END_POINTS and user_pt >= GAME_END_POINTS. Are you sure that those two variables satisfy those two conditions?
you can print computer_pt and user_pt in the loop to see what happened in this two variable, then you will find the answer by your self.
Print variable in loop is a common way to debug your code.

Python - UnboundLocalError: local variable 'health' referenced before assignment

Despite importing the variable 'health' from a different module, the function below provides the error shown in the title. 'Health' is also globalised and I have removed both the globalisation and the importation of the variable and I still receive the same error.
Below is the function that is causing the issue.
def combat():
enemy_health = (random.choice(random_enemy_Health))
enemy_attack = (random.choice(random_enemy_Attack))
print("\nYou are fighting a" ,random.choice(enemies), "with an attack amount of" ,enemy_attack, "and a health amount of" ,enemy_health,".")
while health > 0 and enemy_health > 0:
if turn == 1:
while loop == False:
response=input()
try:
move = response("Do you want to attack or flee? Type '1' to attack and '2' to flee.")
move = int(move)
if move == 1:
enemy_health = enemy_health - attack
print("You attacked!")
loop = True
elif move == 2:
hub_travel()
print("You fled the battle, come back once you are stronger!")
loop = True
else:
print("Invalid number, try again")
continue
except:
print("Invalid number, try again")
continue
turn = 2
if turn == 2:
AImove = randint(1,2)
if AImove == 1:
print ("Enemy attacked!")
health = health - enemy_attack
turn = 1
continue
print ("game over!")
if enemy_health == 0:
print("The enemy has been defeated!")
gold += random.choice(gold_dropped)
The error occurs on this line in particular:
while health > 0 and enemy_health > 0:
If I were you, instead of relying on globals, I would use parameters. This advice may help you to track some errors.
Globals variables is a possibility in programs that have a few lines of code. But, when you application grows, it is a bit hard to track the current value of some variable, because it can be used in several functions or methods (probably, you need a mental mapping to find out the current value). So, this is one of the reasons why you must prefer to use local variables or parameters instead of globals.
This change would allow your function to work the way you want:
def combat(health):
...
Of course, you'd have to find the places where you call the function and pass in the value for health. I don't know if the code at that point has access to that information.
This is probably the simplest fix that could possibly address this issue. It is certainly not the best fix, but this is not a good place for an architecture tutorial.

Categories