Python Forum
first function - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: first function (/thread-38692.html)

Pages: 1 2 3 4


RE: first function - rob101 - Nov-21-2022

Don't put yourself down: you know how to code a function, that takes an argument and returns a value. You also know how to catch the correct exception (as I've said, it's except ValueError:) so the building blocks are there.

Just as you've already done, give it a go.

Sites that I like:

https://www.w3schools.com/python/
https://www.pythontutorial.net/


RE: first function - astral_travel - Nov-21-2022

okay,
what i don't understand - is how do i make a generalization of that function so it can be implemented throughout the program ? how can it be connected to each of the instances ?


RE: first function - rob101 - Nov-21-2022

Okay, well you could do something like this:

def get_int(n):
    try:
        n = int(n)
        return n
    except ValueError:
        return False


while True:
    number = get_int(input("Number: "))

    if number:
        # do whatever
        print(number, type(number))
    else:
        print("Error in number input")
But I've no doubt that it could be improved upon. e.g: the if number: fails. It does not class a zero as an integer.

Another way to do that, would be to include the input() function:

def get_int(prompt):
    n = input(prompt)
    try:
        n = int(n)
        return n
    except ValueError:
        return False


while True:
    number = get_int("Number: ")



RE: first function - deanhystad - Nov-21-2022

I think the abstraction is wrong. input_int should return an int, not int or False. Returning a value or a special flag value is how a C programmer would write the function, back in the 70's. The abstraction is described as "A function that returns an integer input", not "A function that returns an integer input, or False if the input is not a valid integer string". A better abstraction lets the calling code assume the return value is correct. No more while loops and checking, just getting down and doing what you want to do:
def input_int(prompt="Enter integer: "):
    """Return integer input"""
    while True:
        value = input(prompt)
        try:
            return int(value)
        except ValueError:
            print(value, "is not an integer")

print("The product is", input_int() * input_int())
Output:
Enter integer: 5 Enter integer: 5 The product is 25
That little function can handle a lot of input cases, but maybe not yours. Maybe you want a version with an escape word. The function returns an integer input but provides a way for the user to not comply. This example returns an int unless the user enters a special escape word. If that happens, the function raises a ValueError. The caller is still written in a way that assumes the user will provide valid input, but it wraps that code in a handler that catches the exit.
def input_int(prompt="Enter integer: ", exit_str=None):
    """Returns an integer input.

    prompt : Optional prompt printed to aid input
    exit_str : Escape word that terminates input.  Raises ValueError when encountered.
    while True:
        value = input(prompt)
        if value == exit_str:
            raise ValueError(exit_str)
        try:
            return int(value)
        except ValueError:
            print(value, "is not an integer")

try:
    print("The product is", input_int(exit_str="quit") * input_int(exit_str="quit"))
except ValueError as msg:
    print("Got", msg)
Output:
Enter integer: 5 Enter integer: a a is not an integer Enter integer: exit exit is not an integer Enter integer: quit Got quit
The same function can be used to enter numbers until a blank input.
try:
    values = []
    while True:
        values.append(input_int("Enter integer or blank ", exit_str=''))
except ValueError:
    print(values)
Output:
Enter integer or blank 1 Enter integer or blank 2 Enter integer or blank 3 Enter integer or blank 4 Enter integer or blank 5 Enter integer or blank [1, 2, 3, 4, 5]



RE: first function - Larz60+ - Nov-22-2022

You can find quite a few different stock market graphical analysis python scripts by following the links here:
Google: 'Stock market Graphical analysis python examples'
click on images, and visit sites that interest you.

here's one for example: https://towardsdatascience.com/stock-market-analysis-in-python-part-1-getting-data-by-web-scraping-cb0589aca178


RE: first function - rob101 - Nov-22-2022

(Nov-21-2022, 11:38 PM)deanhystad Wrote: I think the abstraction is wrong. input_int should return an int, not int or False. Returning a value or a special flag value is how a C programmer would write the function, back in the 70's. The abstraction is described as "A function that returns an integer input", not "A function that returns an integer input, or False if the input is not a valid integer string". A better abstraction lets the calling code assume the return value is correct. No more while loops and checking, just getting down and doing what you want to do:
def input_int(prompt="Enter integer: "):
    """Return integer input"""
    while True:
        value = input(prompt)
        try:
            return int(value)
        except ValueError:
            print(value, "is not an integer")

print("The product is", input_int() * input_int())
Output:
Enter integer: 5 Enter integer: 5 The product is 25
That little function can handle a lot of input cases, but maybe not yours. Maybe you want a version with an escape word. The function returns an integer input but provides a way for the user to not comply. This example returns an int unless the user enters a special escape word. If that happens, the function raises a ValueError. The caller is still written in a way that assumes the user will provide valid input, but it wraps that code in a handler that catches the exit.
def input_int(prompt="Enter integer: ", exit_str=None):
    """Returns an integer input.

    prompt : Optional prompt printed to aid input
    exit_str : Escape word that terminates input.  Raises ValueError when encountered.
    while True:
        value = input(prompt)
        if value == exit_str:
            raise ValueError(exit_str)
        try:
            return int(value)
        except ValueError:
            print(value, "is not an integer")

try:
    print("The product is", input_int(exit_str="quit") * input_int(exit_str="quit"))
except ValueError as msg:
    print("Got", msg)
Output:
Enter integer: 5 Enter integer: a a is not an integer Enter integer: exit exit is not an integer Enter integer: quit Got quit
The same function can be used to enter numbers until a blank input.
try:
    values = []
    while True:
        values.append(input_int("Enter integer or blank ", exit_str=''))
except ValueError:
    print(values)
Output:
Enter integer or blank 1 Enter integer or blank 2 Enter integer or blank 3 Enter integer or blank 4 Enter integer or blank 5 Enter integer or blank [1, 2, 3, 4, 5]

That's all fair enough (the disparaging comment aside), but now the flexibility is gone, as the function can't now be used for a script that has menu options, which typically require the user to enter 1, or 2 or any other integer, as the prompt and the feedback are clearly inappropriate for such use.


RE: first function - astral_travel - Nov-22-2022

okay, why use ValueError and not TypeError ?


RE: first function - rob101 - Nov-22-2022

Because if you try to type convert a string object that is not a integer number to a int object, the exception that Python throws is builtins.ValueError: invalid literal for int() with base 10


RE: first function - astral_travel - Nov-22-2022

okay, well, still - this is what is written in docs.python.org:

Passing arguments of the wrong type (e.g. passing a list when an int is expected) should result in a TypeError , but passing arguments with the wrong value (e.g. a number outside expected boundaries) should result in a ValueError .
--------------

i think the certain situation you describe is a more specific case,
but in our script here it seems that TypeError is more appropriate, don't you think ?
i mean, we aren't trying to convert anything here, but simply to verify we are getting the right kind of input...


RE: first function - rob101 - Nov-22-2022

(Nov-22-2022, 07:19 PM)astral_travel Wrote: ... but in our script here it seems that TypeError is more appropriate, don't you think ?

No, because it's not the wrong type that we're passing: we're passing a type str (which is correct), which we need to type convert to a int. Only if that conversion can't be done, do we need to catch the exception: it's right type but an inappropriate value.