Hi everyone I have this task: Write a python program that takes two numeric inputs x and y.
a) [5 pts] The program should take numeric inputs continuously.
b) [10 pts] The program should ensure the range of x and y is between 0 and 1. If either one of the input values is out of range, smaller than 0 or greater than 1, then the program should quit.
c) [10 pts] Implement XOR gate, where the program returns 1 if both x and y values are different; otherwise, it returns 0.
The program should work for floating-point values.
For example,
If x = .3 and y = .3, then xor output should be 0
If x = .6 and y = .3, then xor output should be 1
If x = .3 and y = .6, then xor output should be 1
If x = .6 and y = .6, then xor output should be 0
So far I have done this but I still keep getting errors
x=float(input("enter x: "))
y=float(input("enter y : "))
while True:
if(x>=0 and x<=1) and (y>=0 and y<=1):
def XOR (x, y):
if x != y:
return 1
else: return 0
print(XOR(x,y))
continue
elif(x>=0 and x<=1) and (y>=0 and y<=1):
break
I get this error
File "<ipython-input-337-80599671f24c>", line 13
elif(x>=0 and x<=1) and (y>=0 and y<=1):
^
IndentationError: unexpected indent
CodePudding user response:
It looks like your indentation is off the continue and print statements should be at the same indentation level as function definition above like:
x=float(input("enter x: "))
y=float(input("enter y : "))
while True:
if(x>=0 and x<=1) and (y>=0 and y<=1):
def XOR (x, y):
if x != y:
return 1
else:
return 0
print(XOR(x,y))
continue
elif(x>=0 and x<=1) and (y>=0 and y<=1):
break
though the XOR function should be defined outside the loop and the continue statement is redundant
def XOR (x, y):
if x != y:
return 1
else:
return 0
x=float(input("enter x: "))
y=float(input("enter y : "))
while True:
if(x>=0 and x<=1) and (y>=0 and y<=1):
print(XOR(x,y))
elif(x>=0 and x<=1) and (y>=0 and y<=1):
break
in order to have the user repeatedly prompted for input the input lines should be within the loop and the elif statement should be an else statement either the condition is met and the function is run and the user prompted for another input or the loop exits
def XOR (x, y):
if x != y:
return 1
else:
return 0
while True:
x=float(input("enter x: "))
y=float(input("enter y : "))
if(x>=0 and x<=1) and (y>=0 and y<=1):
print(XOR(x,y))
else:
break
CodePudding user response:
Define your function outside of the loop and get the input in the loop.
def xor(x, y):
return x != y
while True:
x = float(input("enter x: "))
y = float(input("enter y: "))
if not (0 <= x <= 1 and 0 <= y <= 1):
break
print(xor(x, y))
