'My current code isn't working on this in python

Python question

This is my current code:

n = int(input())
lst = []
for i in range(0, n):
    lst.append(input())
    if n == 'y':
        break
  

lst.sort()

print(lst)

k =len(lst)//2

if k==0 :
    print(lst[k+1])

else :
    print(lst[k])

this is the output it's giving me:

['3', '3', '6', '7']
6

and I need the output to be: [3, 3, 4, 6, 7] 4



Solution 1:[1]

You need to check for the quit before adding it to the list. You also try to check for the number of integers you are given at the beginning - this is not what you want. The numbers given are terminated by the q.

lst = []
while True:
    number = input()
    if number == 'q':
        break
    lst.append(int(number))

The slicing at the end is also incorrect. Let's break this down. You say

k = len(lst) // 2

if k == 0:
    print(lst[k+1])
else:
    print(lst[k])

If we have 3, 3, 6, 7, the length is 4, so k = 2. Then, k != 0 so we print out the element at index 2, which is 6. However, if k = 0, which is the case when the list has 1 element, you want to be accessing index 0, not 1.


This code

lst = []
while True:
    number = input()
    if number == 'q':
        break
    lst.append(int(number))

lst.sort()

k = len(lst) // 2

print(lst)
print(lst[k])

now gives the correct output:

4
3
6
7
3   
q
[3, 3, 4, 6, 7]
4

Solution 2:[2]

I made some changes to your code that should give you the result you'd like to have. See the comments for explanation

n = 50 #to limit the maximum number of inputs
lst = []
for i in range(0, n):
    x = input()
    if x == 'y':
        break
    lst.append(x) # this line should be after the break to avoid 'y' in your list
    
lst.sort()

print(lst)

k =len(lst)//2

if k==0 :
    print(lst[k+1])

else :
    print(lst[k])

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Eric Jin
Solution 2 user133639