简体   繁体   English

如何打破用户输入的循环

[英]How to break a loop over user input

I've recently started studying python and I have this issue with a problem.我最近开始研究 python 并且我遇到了这个问题。 I need to break a loop over user input.我需要打破用户输入的循环。 Pretty much what i need right now is: To break the grams_per_cat input loop when it reaches the cat_count.我现在需要的几乎是:当它达到 cat_count 时打破grams_per_cat 输入循环。 Pretty much the excercise is cat_count is the number of cats, grams per cat is how much a cat eats per day for each cat.几乎练习是 cat_count 是猫的数量,每只猫的克数是每只猫每天吃多少。 So when it hits for example cat_count is 6 so after 6 inputs i want to break the input loop.所以当它击中时,例如 cat_count 是 6 所以在 6 个输入之后我想打破输入循环。

cat_count = int(input())

while True:
    grams_per_cat = int(input())

Define a counter and use it to break on a certain condition:定义一个计数器并在特定条件下使用它来中断:

cat_count = int(input())
# Our counter
i = 0
while True:
    if i >= cat_count:
       # Interrupt the loop if we reached cat_count
       break
    grams_per_cat = int(input())
    # Increase counter
    i += 1

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM