0

How to fix this error please check code below i'm just bignner, im trying to make 2 choices one with normal numbers and the other choice is fraction numbers:-

   if choice == 1:
        a = float(input("Enter First Number: "))
    try:
        val = float(a)
    except ValueError:
        print("Please enter only numbers!!")
        continue
    b = float(input("Enter Second Number: "))
    try:
        val = str(b)
    except ValueError:
        print("Please enter only numbers!!")
        continue
    slo= add(a,b)
    print("=", int(slo))

    if choice == 2:
        a = float(input("Enter First Number: "))
        try:
            val = float(a)
        except ValueError:
            print("Please enter only numbers!!")
            continue
        b = float(input("Enter Second Number: "))
        try:
            val = str(b)
        except ValueError:
            print("Please enter only numbers!!")
            continue
        def fraction(a, b):
            fr = Fraction(a, b)
            return '{}/{}'.format(fr.numerator, fr.denominator)
  • 1
    Hello @Lisco. This is a matter of scopes :) A variable lives in a scope. This means that a variable defined in one function can't be referenced in another function. In your case 'a' is assigned in your if, which is a smaller scope than the next time you're referencing it, getting your error. If you want you can declare 'a' before your first if, letting it live in a larger scope where all inner scopes can still reference it. – f2lollpll Dec 04 '21 at 19:43
  • Yes Absloutly, Thanks a lot for the explanation. – Lisco Sanchez Dec 04 '21 at 20:13
  • 2
    Global scope: The names that you define in this scope are available to all your code. Local scope: The names that you define in this scope are only available or visible to the code within the scope. – Lisco Sanchez Dec 04 '21 at 20:28
  • Correct, @Lisco :) Also be aware that there are often multiple levels of local scopes within each other. – f2lollpll Dec 05 '21 at 08:02

0 Answers0