Reputation: 19
I'm new to programming and have started learning with Python. One of the problems in my workbook asks me to keep accepting input until a key is pressed. I came up with two solutions and am wondering if one is preferred over the other. Someone told me I should avoid conditions that create infinite loops, so I'm wondering about Solution 1. Here they are:
Solution 1
while True:
integer = int(input("Please enter an integer (0 exits): "))
if integer != 0:
list.append(integer)
else:
break
Solution 2
integer = int(input(“Enter an integer (0 exits): “))
while integer != 0:
list.append(integer)
integer = int(input(“Enter an integer (0 exits): “))
Upvotes: 1
Views: 125
Reputation: 180532
You can combine a lambda
with iter
to allow you to add a string to your input to give the user message and a try/except
to catch any values entered that cannot be cast to an int outputting an appropriate message to the user, the second arg to iter is a sentinel value which will break the loop once entered. It must be a string as we are not casting until we get to the try/except:
res = []
for val in iter(lambda: input("Please enter an integer (0 exits): "), "0"):
try:
res.append(int(val))
except ValueError:
print("Integers only")
print(res)
We need the lambda as the first arg to iter must be callable so because we have added the user output message we will have already called the function.
Upvotes: 1
Reputation: 22697
More pythonic way:
sentinel = 0
[int(n) for n in iter(input,sentinel)]
Input:
1
2
4
0
Result:
[1,2,4]
You need to be careful with string input like chars or special chars. You need to add some try/catch code to handle those cases.
Upvotes: 1
Reputation: 209
final = []
while True:
try:
integer = int(input("Enter an integer (0 exits): "))
if integer == 0: break
final.append(integer)
except:
print ("Input wasn't a int.")
Tried keeping it as close to your existing solutions and as readable as possible.
Upvotes: 1