[英]To check whether a number is multiple of second number
我想检查一个数字是否是秒的倍数。 以下代码有什么问题?
def is_multiple(x,y):
if x!=0 & (y%x)==0 :
print("true")
else:
print("false")
end
print("A program in python")
x=input("enter a number :")
y=input("enter its multiple :")
is_multiple(x,y)
错误:
TypeError: not all arguments converted during string formatting
您正在使用二进制AND运算符 &
; 你想在这里使用布尔AND运算符 , and
:
x and (y % x) == 0
接下来,您希望将输入转换为整数:
x = int(input("enter a number :"))
y = int(input("enter its multiple :"))
您将在一行上获得该end
表达式的NameError
,完全删除它,Python不需要那些。
您可以测试只是 x
; 在布尔上下文(如if
语句)中,如果为0,则数字被视为false:
if x and y % x == 0:
你的函数is_multiple()
应该只返回一个布尔值; 将打印留给程序执行所有其他输入/输出的部分:
def is_multiple(x, y):
return x and (y % x) == 0
print("A program in python")
x = int(input("enter a number :"))
y = int(input("enter its multiple :"))
if is_multiple(x, y):
print("true")
else:
print("false")
如果使用条件表达式,最后一部分可以简化:
print("A program in python")
x = int(input("enter a number :"))
y = int(input("enter its multiple :"))
print("true" if is_multiple(x, y) else "false")
有些事要提到:
and
条件, and
不是&
(二元运算符) int()
) - 如果输入了数字以外的其他内容,您可能还想要捕获 这应该工作:
def is_multiple(x,y):
if x != 0 and y%x == 0:
print("true")
else:
print("false")
print("A program in python")
x = int(input("enter a number :"))
y = int(input("enter its multiple :"))
is_multiple(x, y)
使用and
运算符而不是按位&
运算符。
您需要使用int()
将值转换为整数
def is_multiple(x,y):
if x!=0 and (y%x)==0 :
print("true")
else:
print("false")
print("A program in python")
x = int(input("enter a number :"))
y = int(input("enter its multiple :"))
is_multiple(x,y)
我试过这个并且也适用于 x 和/或 y 等于 0 的情况。如果有更短的写法,我想知道。
用 (4,12), (12, 4), (2,0), (0,2), (0, 0) 测试
(结果应该是:False True False True True)。
def exo1(x,y):
#x = int(input("input number x: "))
#y = int(input("input number y: "))
if x==0 and y==0:
return True
if x>0 and y==0:
return False
if y>0 and x==0:
return True
if x!=0 and y!=0 and (x%y)==0:
return True
else:
return False
print(exo1())
print(exo1(4,12))
print(exo1(12,4))
print(exo1(2,0))
print(exo1(0,2))
print(exo1(0,0))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.