If user entered anything other than an integer it should be ignored, whereas, if it were to be an integer it should be added to the lst
(list)
the function should display the list of integers, ignoring anything that wasn't an integer and display the max and min number.
lst = []
n = int(input("Enter Integers: "))
for index in range(min(n), max(n)):
if index == ' ':
return
for i in range(min(n),max(n)):
elements = int(input())
lst.append(elements)
print(lst)
print(len(lst))
for num in lst:
if num % 2 == 0:
print(num, end= ' ')
I have a function here that prompts users to enter a list of integers, if SPACE is inputted: it should END the input.
I'm quite new at python and not sure how to go about this code.
The expression
input("Enter Integers: ")
evaluates to a string. Since you want to read strings until a space is inserted, you need a infinite loop:
numbers = []
while True:
value = input("Enter an integer: ")
If the user provides a space, stop reading numbers:
numbers = []
while True:
value = input("Enter an integer: ")
if value == ' ':
# Exit the loop
break
If you want to convert it to an integer, use the int
function and append it to numbers
:
numbers = []
while True:
value = input("Enter an integer: ")
if value == ' ':
break
numbers.append(int(value))
You can also add a validation, if the user provides a value that isn't a number:
numbers = []
while True:
value = input("Enter an integer: ")
if value == ' ':
break
try:
number = int(value)
except ValueError:
print('The value is not a number!')
# Continue looping
continue
numbers.append(number)
Your code there is somewhat misleading and adds confusion to the question. My solution below is based off the question before the code.
lst = []
print("Enter Integers:")
while True:
n = input()
try:
# Try converting to an int, if can't ignore it
lst.append(int(n))
except ValueError:
pass
# If space input, break the loop
if n == ' ':
break
print("Integer list: ")
print(lst)
if len(lst) > 0:
print("Min: " + str(min(lst)))
print("Max: " + str(max(lst)))
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.