[英]How to stop for loop from iterating when condition is successfully met?
所以,我正在編寫手板球腳本,我想在用戶選擇的數字和 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
我可能在你的問題中遺漏了一些東西,但看起來你已經明白了。 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))
同樣,您似乎已經以某種方式得出了這個答案。 你是在問別的嗎?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.