[英]How to break a loop with an input?
我是 Python 新手,所以请耐心等待。 我正在尝试编写一个程序,该程序涉及一个函数,该函数以数字 K 作为输入,一次读取 K 个名称,将它们存储到列表中,然后打印它们。
不确定我是否应该使用“for”或“while”循环,所以我首先尝试使用“while”循环。
k = input ("How many names?\n")
def names():
lst = []
while True:
name = input("Enter name:")
if = int(k)
break
return lst
names()
我希望看到的是一个名称列表,该列表将在 K 个名称之后被切断。
我一直收到此错误消息:
File "<ipython-input-21-24a26badc1b5>", line 7
if = int(k)
^
SyntaxError: invalid syntax
Python 中的相等比较是通过一个
==
您还需要某种东西来比较 int(k) 。 如果你想计算循环,你可以做类似的事情
x = 0
while True:
name = input("Enter name:")
lst.append(name)
x+= 1
if x== int(k)
break
while
和for
循环之间的区别是:
for
循环。while
循环。 使用for
循环实现你想要的方法是这样的:
k = input("How many names?\n")
def names():
lst = []
for i in range(int(k)): # creates a list `[0, 1, 2, ..., k-1]` and iterates through it, for `k` total iterations
name = input("Enter name:")
lst.append(name)
return lst
names()
现在,您可以使用while
循环来执行此操作 - 通过事先设置一个像x=0
这样的变量,并在每次迭代时将其增加 1 直到x == k
,但这比for
循环更冗长且难以一目了然是。
@Green Cloak Guy很好地解释了为什么 for 循环适合您的任务。 但是,如果您确实想使用 while 循环,则可以执行以下操作:
def get_names(num_names):
names = []
i = 1
while i <= num_names: # equivalent to `for i in range(1, num_names + 1):`
current_name = input(f"Please enter name {i}: ")
names.append(current_name)
i += 1
return names
def main():
num_names = int(input("How many names are to be entered? "))
names = get_names(num_names)
print(f"The names are: {names}")
if __name__ == '__main__':
main()
示例用法:
How many names are to be entered? 3
Please enter name 1: Adam
Please enter name 2: Bob
Please enter name 3: Charlie
The names are: ['Adam', 'Bob', 'Charlie']
这正是for
循环的 for - 循环“for”一定次数。 while
循环用于无限循环,在这种循环中您会一直循环,直到某些事情不再正确为止。
尽管如此,看到两者可能会有所启发,因此您可以更好地了解差异。 这是for
循环。 它将循环k
次。 有关更多详细信息,请参阅Python wiki 。
k = int(input ("How many names?\n"))
def names():
lst = []
for i in range(k):
name = input("Enter name:")
lst.append(name) # I'm assuming you want to add each name to the end of lst
return lst
names()
这与while
循环相同。 循环一直持续到循环条件不为真,因此您只需要提出一个条件,该条件对前k
循环为真,之后不成立。 这将:
k = int(input ("How many names?\n"))
def names():
lst = []
i = 0
while i < k:
name = input("Enter name:")
lst.append(name) # I'm assuming you want to add each name to the end of lst
i += 1
return lst
names()
请注意,在while
循环中,您必须自己初始化和递增迭代器 ( i
),这就是for
循环更适合的原因。
最后,请注意这两个示例如何使用break
。 break
是结束循环的好方法,但如果没有必要,那么最好不要使用它 - 通常它仅用于通过异常结束循环(即,出于某种原因,这不是主循环条件)。 将它用于正常的循环结束会导致更少的逻辑代码更难遵循。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.