Home > other >  My friend told me to make an program on Fault_in_Calculator which calculated user entered digit but
My friend told me to make an program on Fault_in_Calculator which calculated user entered digit but

Time:12-29

a=int(input("Enter 1st number: ")) b=int(input("Enter 2nd number: ")) c=input("Enter the operator: ") n=0

def plus(a,b): n=a b print(n)

def minus(a,b): n=a-b print(n)

def multiply(a,b): n=a*b print(n)

def divide(a,b): n=a/b print(n)

if a%2==0: pass else: a =1

if b%2==0: b =1

if c==" ": d=a b plus(a,b) elif c=="-": d=a-b minus(a,b) elif c=="x" or "X": d=a*b multiply(a,b) elif c=="/": d=a/b divide(a,b) else: print("Input correct operator.")

print(d) if d==n: pass else: print("Oops, I didn't got right answer. Sorry for that, I am closing off.")

Problems:

Divide operator doesn't works properly.

Calculator last sentence is printed all time no matter if it's calculation is right.

CodePudding user response:

There are two Problems in the code (ok the formatting of the code is also a problem. Hopefully you only put it in that format for the question if not pls try to indent the code right and don't put multiple statements in one line)

For the Problems: It always runs the multiply option because the if Statement is wrong.

Instead of elif c=="x" or "X": you have to write elif c=="x" or c=="X": so you missed the variable to check against in the or clause.

The second thing your variable n will not be changed inside the function. Inside the Function it defines a new local (local to the function) variable n if you want to change the outside variable n you have to define it as global inside each of the functions who changes the value of n.

Here is the Code:

a=int(input("Enter 1st number: "))
b=int(input("Enter 2nd number: "))
c=input("Enter the operator: ")
n=0
 
def plus(a,b):
    global n
    n=a b
    print(n)
 
def minus(a,b):
    global n
    n=a-b
    print(n)
 
def multiply(a,b):
    global n
    n=a*b
    print(n)
 
def divide(a,b):
    global n
    n=a/b
    print(n)

if a%2==0:
    pass
else:
    a =1
 
if b%2==0:
    b =1

print(a)
print(b)
 
if c==" ":
    print("Plus")
    d=a b
    plus(a,b)
elif c=="-":
    print("Minus")
    d=a-b
    minus(a,b)
elif c=="x" or "X":
    print("Multiply")
    d=a*b
    multiply(a,b)
elif c=="/":
    print("Divide")
    d=a/b
    divide(a,b)
else:
    print("Input correct operator.")
 
if d==n:
    pass
else:
    print("Oops, I didn't got right answer. Sorry for that, I am closing off.")


CodePudding user response:

If you debug once, you will notice that the value of the variable n does not change until the end of the program. The reason is that n only changes in the scope of each function, but the change to the global variable n is not done!

To change a global variable in a function, do the following:

n=0

def plus(a,b): 
    global n
    n=a b 
    print(n)

At the beginning of each function, declare that n is the global variable n.

  • Related