How to make an exception "ValueError" replace an item in a list

I am trying to write a piece of code that will go through a list of numbers (dividing by vertical bars), which, if the user enters a non-number, throws an exception and replaces the specified object with 0. It is designed to display the list in descending order (from largest to smallest ) with vertical stripes between them. This is my code at the moment, but I cannot get it to work.

    numbers = input("Please enter several integer numbers separated by 
    vertical bars. ").split('|')
    for item in numbers:
        try:
            numbers = [int(item) for item in numbers]
        except ValueError:
            item = item.replace(item,'0')
    numbers = sorted(numbers, reverse = True)
    print(' | '.join(str(num) for num in numbers))
+4
source share
3 answers
numbers = input("Please enter several integer numbers separated by vertical bars. ")
numbers = numbers.split('|')
temp = []
for item in numbers:
    try:
        temp.append(int(item))
    except ValueError:
        temp.append(0)
numbers = temp

Please note that here we do not change numberswhile we repeat it. Another way to accomplish the same task is with something like

def eval_number(s):
    try:
        return int(s)
    except ValueError:
        return 0

numbers = input("Please enter several integer numbers separated by vertical bars. ")
numbers = numbers.split('|')
numbers = list(map(eval_number, numbers))
+1
source

- :

fixed_numbers=[]
for n in numbers:
try:
    fixed_numbers.append(int(n))
except ValueError:
    fixed_numbers.append(0)

try , . :

try:
    numbers = [int(n) for index, n in enumerate(numbers)]
except ValueError:
    numbers[index] = 0

, ,

0

If you want to actually replace the items in the list, you need to assign an indexed item.

I would separate the manipulation function and the replacement cycle:

def int_or_zero(s):
    try:
        return int(s)
    except ValueError:
        return 0

for i in range(len(numbers)):
    numbers[i] = int_or_zero(numbers[i])
0
source

Source: https://habr.com/ru/post/1689993/


All Articles