So if I am understanding you correctly, you are trying to use !x
to mean, “While x is an integer,” append x to nums and get another number. So there are a few problems here. First, if you want the while loop to stop once a non-number is entered, you need to set some end condition to the while loop. Here is one way to do it:
nums = []
number = True
while number:
x = input("Enter a number. To exit, enter a letter: ")
if not x.isdigit():
break
nums.append(int(x))
print(nums)
In the above, the user enters something in input and that gets assigned to x (as a string). I then use the string method .isdigit()
to determine whether x is a positive, whole integer. If x is not a positive, whole integer, then the code runs the break
statement and exits the while loop, taking the code to the print statement. So in the above, the end condition occurs when x is not a positive, whole integer. Your code, as it stands, does not have an end condition. I think you may have been trying to do that with the !x
since !=
means, “Not equal to,” but !x
is not valid syntax and does not mean, “If x is not an integer.”
You could also do something similar using an if-else statement, such as:
while number:
x = input("Enter a number. To exit, enter a letter: ")
if x.isdigit():
nums.append(x)
else:
number = False
So if x is a positive, whole integer, append it to nums, otherwise set number to False and end the while loop.
Also note that if you want to include negative numbers and/or floats, using .isdigit
won’t work, so you’d need to do something else if you wanted your code to handle those. But I the fundamental problem with your current while loop is that it does not have any end condition.
The other thing to be aware of in your code is that you’ll get an error if you use x = int(input()
and the user puts in something other than an integer.