PyCharm Error - Name rent_monthly can be undefined

I've been trying to fix this error for a while but can find a solution. My error is "rent_monthly can be undefined", this is my code:

rent_choose = ""

while rent_choose not in ("Yearly", "Monthly"):
    rent_choose = input("Do you want Rent values in Yearly or Monthly: ")
if rent_choose == "Yearly":
    while True:
        try:
            rent_yearly = int(input("Input Yearly rent: "))
        except ValueError:
            print("This is not a valid Yearly Rent, please only input valid Yearly Rent")
        else:
            if rent_yearly < 0:
                print(
                    "Please only input a valid Yearly Rent amount, your Rent cannot be negative")
            else: break


if rent_choose == "Monthly":
    while True:
        try:
            rent_monthly = int(input("Input Monthly rent: "))
        except ValueError:
            print("This is not a valid Monthly Rent, please only input valid Monthly Rent")
        else:
            if rent_monthly < 0:
                print(
                    "Please only input a valid Monthly Rent amount, your Rent cannot be negative")
            else: break

rent_yearly = rent_monthly * 12
rent_monthly = rent_yearly / 12

at the end I define what both values mean in comparison to each other as I use it later in my code, but if you run the code and choose "Monthly" as your first option everything will work fine. If you run the code and choose "Yearly" and input an amount at the end it will give the error of "rent_yearly = rent_monthly * 12 NameError: name 'rent_monthly' is not defined" Im not sure why the code works when you choose Monthly but doesn't work when you choose Yearly.

Would appreciate some help, if I missed something please go easy on me since i'm only a beginner.


Solution 1:

If the condition check if rent_choose == "Monthly": fails, rent_monthly will never be assigned a value. Hence, rent_yearly = rent_monthly * 12 will throw a NameError.

You should calculate the other value dependent on the input case:

rent_choose = ""

while rent_choose not in ("Yearly", "Monthly"):
    rent_choose = input("Do you want Rent values in Yearly or Monthly: ")
if rent_choose == "Yearly":
    while True:
        try:
            rent_yearly = int(input("Input Yearly rent: "))
        except ValueError:
            print("This is not a valid Yearly Rent, please only input valid Yearly Rent")
        else:
            if rent_yearly < 0:
                print(
                    "Please only input a valid Yearly Rent amount, your Rent cannot be negative")
            else:
                rent_monthly = rent_yearly / 12
                break


if rent_choose == "Monthly":
    while True:
        try:
            rent_monthly = int(input("Input Monthly rent: "))
        except ValueError:
            print("This is not a valid Monthly Rent, please only input valid Monthly Rent")
        else:
            if rent_monthly < 0:
                print(
                    "Please only input a valid Monthly Rent amount, your Rent cannot be negative")
            else:
                rent_yearly = rent_monthly * 12
                break

Solution 2:

Richard Neumann's answer works, but I propose an alternate solution that simplifies your code a bit more aggressively. The reason why this issue likely arose in the first place is that your control structure is pretty complicated, and you're duplicating code in both if statements.

Here's an alternate solution that moves the logic to receive the input into a function. Some of the print() statements no longer explicitly say "monthly" or "yearly", but adding those back in can be done by adding a parameter to the get_rent_value() function:

def get_rent_value():
    rent = -1
    while rent == -1:
        try:
            rent = int(input("Input rent: "))
            if rent < 0:
                rent = -1
                print("Please only input a valid rent amount, your rent cannot be negative")
        except ValueError:
            print("This is not a valid rent, please only input valid rent")
    return rent

rent_choose = ""

while rent_choose not in ("Yearly", "Monthly"):
    rent_choose = input("Do you want Rent values in Yearly or Monthly: ")

if rent_choose == "Yearly":
    rent_yearly = get_rent_value()
    rent_monthly = rent_yearly / 12
else:
    rent_monthly = get_rent_value()
    rent_yearly = rent_monthly * 12

print(f"Yearly rent: {rent_yearly}")
print(f"Monthly rent: {rent_monthly}")