Akshat Kulshreshtha
Akshat Kulshreshtha

Reputation: 47

How to stop for loop from iterating when condition is successfully met?

So, I'm working on Hand Cricket script & i want to stop "for" loop from iterating when a user's choice of number & CPU's choice of number are equal & if it's unequal it should keep iterating until it doesnt reach the final range's value

for i in range(1,7):
    print("Ball %d"%i)
    user_choice =int(input("Enter a number between 1 to 6 --> "))
    cpu_choice=random.randint(1,6)

    if user_choice < 7:
        print("CPU picked --> ",cpu_choice)
        run=cpu_choice+run

    if user_choice == cpu_choice:
        print("User is OUT!!")
        run -= cpu_choice
        print("Runs = %d \t Over = %d.%d\n"%(run,i//6,i%6))
        break
        print("Runs = %d \t Over = %d.%d\n"%(run,i//6,i%6))

    else:
        print("\nWRONG CHOICE!! %d ball is cancelled.\n"%i)
        break

Upvotes: 0

Views: 65

Answers (1)

engineerjoe440
engineerjoe440

Reputation: 11

I might be missing something in your question, but it looks like you've already got it. break will force the for loop to exit. So if you wrap your break-statement in a conditional gate (if statement), you can set the criteria that must be met for the break.

Something like this comes to mind:

# Calculate the CPU's Random Integer ONCE
cpu_choice=random.randint(1,6)

# Iteratively Ask User for Input and Validate
for i in range(1,7):
    # Capture Input from User
    user_choice =int(input("Enter a number between 1 to 6 --> "))
    # Verify Input in Specific Range
    if user_choice not in range(1,7):
        print("{} is not in the valid range. Try again.".format(user_choice))
    else:
        # Check if User Input Matches CPU's Selection
        if user_choice == cpu_choice:
            print("You've got the right number! The number was: {}".format(user_choice))

            break  # break out of the `for` loop!

        # Not Correct Input from User
        else:
            print("{} is not the correct number. Try again.".format(user_choice))

Again, it seems like you've already come to this answer in a way. Are you asking something else instead?

Upvotes: 1

Related Questions