I am new to Python, and I was trying to create a simple game. Here I have a function in which I have a list called Health. I am using a for loop to pop all the elements of the list. For some reason, the for loop stops after looping for 5 times i think.
def luminaryMohg():
global battlesFaught
global mohgBeaten
curseImmunity = False
mohgHealth = ['*','*','*','*','*','*','*','*','*','*']
print("\n*****************************************************************\n")
print("""Welcome honored guest!!! To the birthplace of our dynasty.\n""")
print("The fight with Mohg Begins.")
for health in mohgHealth:
print("----------------------------------MOHG's HEALTH-------------------------------------\n")
print("-----------------", mohgHealth, "----------------------\n")
print("1. Hit mohg with a sword.")
input("\nPress Enter to hit")
mohgHealth.pop()
Output:
Welcome honored guest!!! To the birthplace of our dynasty.
The fight with Mohg Begins.
———————————-MOHG’s HEALTH————————————-
—————– [‘‘, ‘‘, ‘‘, ‘‘, ‘‘, ‘‘, ‘‘, ‘‘, ‘‘, ‘‘] ———————-
- Hit mohg with a sword.
Press Enter to hit
—————– [‘‘, ‘‘, ‘‘, ‘‘, ‘‘, ‘‘, ‘‘, ‘‘, ‘*’] ———————-
- Hit mohg with a sword.
Press Enter to hit
—————– [‘‘, ‘‘, ‘‘, ‘‘, ‘‘, ‘‘, ‘‘, ‘‘] ———————-
- Hit mohg with a sword.
Press Enter to hit
—————– [‘‘, ‘‘, ‘‘, ‘‘, ‘‘, ‘‘, ‘*’] ———————-
- Hit mohg with a sword.
Press Enter to hit
—————– [‘‘, ‘‘, ‘‘, ‘‘, ‘‘, ‘‘] ———————-
- Hit mohg with a sword.
Press Enter to hit
PS C:\Users\31dav\OneDrive\Documents>
>Solution :
The issue is that you are modifying a list while iterating over it. This creates surprising behavior for the end user. To demonstrate:
x = list(range(6))
for i in x:
print('Current: ', i)
print('Popped: ', x.pop())
Current: 0
Popped: 5
Current: 1
Popped: 4
Current: 2
Popped: 3
# Fewer elements are left, representing that the iteration stops early
# at the third step, rather than the 6th
print(x)
[0, 1, 2]
Either switch to iterating over a range, or use a while loop to modify the list:
while mohgHealth:
print(...)
_ = mohgHealth.pop()
Or
for i in range(len(mohgHealth)):
_ = mohgHealth.pop()
Since you aren’t doing anything with the result, I wouldn’t worry about using pop and just iterate, when the iteration is complete, you’ve gone through all of the health:
for _ in mohgHealth:
print("hit with sword")
# iteration complete
mohgHealth = []
print("mohgHealth is empty")