Home > Enterprise >  How do I append certain characters from a list?
How do I append certain characters from a list?

Time:02-26

With my code shown below I am attempting to prompt the user to give two numbers. From these numbers I have created a list and a range between the numbers. Additionally I want to only keep the even numbers in the list and print these numbers in a list and also show the length of the new list in the output.

Here is my code:

print('Give me a number that you want to be the lowest value:')
low = int(input())
print('Give me a number that you want to be the highest value:')
high = int(input())

plus1 = high 1
numbers = list(range(low, plus1))
for x in numbers:
    if x % 2 == 0:
        numbers.append(x)
        print('Your list is:',int(input(numbers)))
        print('The length of your list is', len(numbers))

Here is my output if low = 1 and high = 9:

[1, 2, 3, 4, 5, 6, 7, 8, 9, 2]

As you can see above the output does not omit the odd numbers from the list.

EDIT: I have found that removing the 'int(input(' from my second to last line gets me the correct even numbers however the list keeps repeating itself.The output if low = 1 and high = 9 looks something like:
2, 4, 6, 8, 2, 4, 6, 8, 2, 4, 6, 8, 2, 4, 6, 8, 2, 4, 6, 8, 2, 4, 6, 8, 2, 4, 6, 8, 2, 4, 6, 8, 2, 4, 6, 8, 2, 4, 6, 8, 2, 4, 6, 8, 2, 4, 6, 8, 2, 4, 6, 8, 2, 4, 6, 8, 2, 4, 6, 8, 2, 4, 6, 8, 2, 4, 6, 8, 2, 4, 6, 8... and its repeats forever.

CodePudding user response:

Try this:

print('Give me a number that you want to be the lowest value:')
low = int(input())
print('Give me a number that you want to be the highest value:')
high = int(input())

plus1 = high 1
numbersOddAndEven = list(range(low, plus1))
numbers = []
for x in numbersOddAndEven:
    if x % 2 == 0:
        numbers.append(x)
print('Your list is:', numbers)
print('The length of your list is', len(numbers))

CodePudding user response:

I hope I'm not just suffering from lack of sleep here... but the first issue I found in your original code is the creation of a number list, ranging from the low input to the high 1 - but then you use that same list to append to.

Am I understanding correctly, and this isn't what you're intending? Seems like you just need to create another variable ... list type, of course. Just like @constantstranger did.

num_mix = list(range(low, plus1))
numbers = []

[EDIT] Sorry... he used different variable names, but yeah... lol Hopefully I explained well enough that you can see and realize what I think the issue could be in your original code!

  • Related