I'm new to Python, so please bear with me. I'm trying to write a program involving a function that takes a number K as an input, reads K names one at a time, stores them into a list, and then prints them.
Not sure whether or not I should use a "for" or "while" loop, so I'm trying with "while" loop first.
k = input ("How many names?\n")
def names():
lst = []
while True:
name = input("Enter name:")
if = int(k)
break
return lst
names()
What I'm hoping to see is a list of names, and that list would be cut off after K number of names.
I've been receiving this error message:
File "<ipython-input-21-24a26badc1b5>", line 7
if = int(k)
^
SyntaxError: invalid syntax
Equality comparisons in Python are done with a
==
You also need some sort of thing to compare int(k) to. If you're trying to count loops you could do something like
x = 0
while True:
name = input("Enter name:")
lst.append(name)
x+= 1
if x== int(k)
break
The difference between while
and for
loops is thus:
for
loop.while
loop. The way to implement what you want using a for
loop is this:
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()
Now, you could do this using a while
loop - by setting a variable like x=0
beforehand, and increasing it by one for every iteration until x == k
, but that's more verbose and harder to see at a glance than a for
loop is.
@Green Cloak Guy explained very well why a for loop would be appropriate for your task. However if you do want to use a while loop you could do something like this:
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()
Example Usage:
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']
That's exactly what a for
loop is for - looping "for" a certain number of times. A while
loop is for indefinite loops where you keep looping until something is no longer true.
Still, it might be instructive to see both, so you can better understand the difference. Here's the for
loop. It will loop k
times. See the Python wiki for more details.
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()
And here's the same thing as a while
loop. The loop continues until the loop condition is not true, so you just need to come up with a conditional that is true for the first k
loops, and not thereafter. This will do:
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()
Notice how in a while
loop you have to initialise and increment the iterator ( i
) yourself, which is why a for
loop is more suitable.
Finally, notice how neither example uses break
. break
is a fine way to end a loop, but if it's not necessary then you're better off not using it - generally it is only used to end a loop by exception (that is, for some reason that is not the main loop conditional). Using it for normal loop endings leads to less logical code that is harder to follow.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.