2

So im trying to make a small game, but when i try to add one more to the loop, it dosent continue the loop. Is there any other way I could do this?

import random

chosenCard = 2

correctCard = 2


remove = random.randint(1, 3)
print(remove)

loop = 1

for i in range(loop):
    if remove == correctCard or remove == chosenCard:
        loop += 1
        print("remove == correctCard or remove == chosenCard --- Adding loop +1", loop)



print("Chosen", chosenCard)
print("Correct", correctCard)
print("remove", remove)
4
  • And I have tested this while variable remove is 2. Commented May 5, 2021 at 14:06
  • 2
    What about while instead of a loop? Commented May 5, 2021 at 14:08
  • 6
    Once the range is evaluated it returns a range object from 0 to loop at the moment of evaluation. Changing the value of loop afterwards doesn't affect the range object... You might be better using a while loop instead... Commented May 5, 2021 at 14:13
  • 1
    @vojtam Wow, didn't even have a thought of using while. thanks. Solved. Commented May 5, 2021 at 14:13

2 Answers 2

1

You should use a while loop.

while loop > 0:
    if remove == correctCard or remove == chosenCard:
        loop += 1
        print("remove == correctCard or remove == chosenCard --- Adding loop +1", loop)
    loop -= 1
Sign up to request clarification or add additional context in comments.

Comments

0

This does not work, because, changing a variable does not change an object created with it. Say you are in the shop and your wife wrote you a shopping list with 2 apples. If your wife then remembers that her mother comes for a visit, she can think that she needs 3 apples, but that does not change the number on your shopping list. The same is the case in your code. At the time the range is created, loop has a value of 1. So the range is created with 1 value. Later changing loop does not automatically change the range object. A while loop would be appropriate here:

import random

chosenCard = 2
correctCard = 2
remove = random.randint(1, 3)
loop = 1

while loop > 0
    if remove == correctCard or remove == chosenCard:
        loop += 1
        print("remove == correctCard or remove == chosenCard - Adding loop +1", loop)
    loop -= 1

print("Chosen :", chosenCard)
print("Correct :", correctCard)
print("Remove :", remove)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.