Search code examples
pythontry-except

Python Try/Except function


I just can't find others with the same problem. Im sure they exist but im not having luck and this is my very first time learning a language. My try/except works when i enter the wrong type of value. However, it does not work when i enter the correct type of value. I've read my text and searched vidz. I just need a full picture of how to use try/except within the function im using.

def convert_distance():
    miles = int(input("Enter amount of miles driven: "))
    kilometers = miles * 1.609
    print(f"At {miles} miles, your distance in kilometers is: {kilometers}")
try:
    print(miles = int(input("Enter amount of miles driven: ")))
except ValueError:
    print("That is not a number.  Please enter a number")
convert_distance()

The error i receive occurs at line 6 and states

TypeError: 'miles is an invalid keyword argument for print()

Solution

  • Unlike the other answer, yes, you can assign a value and then pass it on (to the print), since Python 3.8, with the walrus operator.

    Would it be a good idea here? Probably not, that print/prompt is weird to look at.

    I've changed the logic a bit too. It loops until miles is successfully assigned an (int) value, then it calls convert with miles as an argument.

    def convert_distance(miles):
        "dont ask again"
        kilometers = miles * 1.609
        print(f"At {miles} miles, your distance in kilometers is: {kilometers}")
    
    miles = None
    while miles is None:
        try:
            print((miles := int(input("Enter amount of miles driven: "))))
        except ValueError:
            print("That is not a number.  Please enter a number")
    convert_distance(miles)
    
    

    prompts/outputs:

    % py test_413_printwalrus.py 
    Enter amount of miles driven: 2
    2
    At 2 miles, your distance in kilometers is: 3.218
    % py test_413_printwalrus.py 
    Enter amount of miles driven: x
    That is not a number.  Please enter a number
    Enter amount of miles driven: 2
    2
    At 2 miles, your distance in kilometers is: 3.218
    

    What "walrus" does here is to assign the right hand (prompt) side of := to the left (miles) and then return it, being an expression.

    print((x:=1))

    Which is very different from print(x=1) which says pass the keyword argument to the print function (which has no such keyword). Note also the double parentheses.

    And with another little adjustment you can even use an intermediate variable to show the user the incorrectly-entered value.

        try:
            print((miles := int((entered := input("Enter amount of miles driven: ")))))
        except ValueError:
            print(f"{entered} is not a number.  Please enter a number")
    
    
    Enter amount of miles driven: x
    x is not a number.  Please enter a number