Python Try/Except function

Question:

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()
Asked By: Rachroxit

||

Answers:

Unlike some other languages like C++, you cannot assign a value to a variable, then immediately print it out.

Python, being a higher level language, has named arguments. When you put an equals sign inside a function call, it will interpret the equals sign as a named argument.

Instead, do this (it’s better code practice anyway):

try:
    miles = int(input("Enter amount of miles driven: "))
    print(miles)
except ValueError:
    print("That is not a number.  Please enter a number")
convert_distance()
Answered By: acenturyanabit

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
Answered By: JL Peyret

After more review of my function i was able to find my own error. However, i did also receive some great information from this community. My initial code started the try/except in the wrong location. A simple move corrected it. However, the program came to a stop after the error message was printed. Adding a while loop will now allow the program to run until the user enters the correct information. Also, an answer above makes use of the walrus operator and that is great to know. Shown below is just a different way to run the program without the walrus operator.

def convert_distance():
        kilometers = miles * 1.609
        print(f"At {miles} miles, your distance in kilometers is: {kilometers} km "
miles = float
while miles == float:
    try:
        miles = float(input("Enter number in miles driven: "))
    except ValueError:
        print("That is not a number.  Please enter a number: ")
convert_distance()
Answered By: Rachroxit
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.