成功满足条件后,如何停止循环迭代?

时间:2020-05-18 01:18:59

标签: python python-3.x

因此,我正在处理Hand Cricket脚本,并且我希望在用户选择的数字与CPU选择的数字相等时停止“ for”循环的迭代,并且如果不相等,则应保持迭代直到不达到最终范围的值

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

1 个答案:

答案 0 :(得分:1)

我可能在您的问题中遗漏了一些东西,但是看起来您已经知道了。 break将迫使for循环退出。因此,如果将中断声明包装在条件门(if语句)中,则可以设置中断必须满足的条件。

想到这样的事情:

# 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))

再一次,看来您已经以某种方式得到了这个答案。您是要问别的吗?