Solution 1

def parse_number(number):
        return int(number)
    except ValueError:

        return float(number)
    except ValueError:

    raise ValueError("Invalid number")

Parse Number

If you use the input() function, remember how everything entered is received as a string (regardless of if it was a number or not)?

Write a function parse_number to receive a number in string format like '7' and use try/except blocks to try to change its type into an int or a float. If that doesn't work, raise a ValueError.


parse_number("3") # 3

parse_number("3.2") # 3.2

parse_number("invalid") # Raises ValueError

Test Cases

test parse number float - Run Test

def test_parse_number_float():
    assert parse_number("3.2") == 3.2

test parse number invalid - Run Test

import pytest

def test_parse_number_invalid():
    with pytest.raises(ValueError):

test parse number integer - Run Test

def test_parse_number_integer():
    assert parse_number("3") == 3
def parse_number(number): pass