检查一个数是否是第二个数的倍数

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 运算符 &;你想要 boolean AND operator 这里,and:

x and (y % x) == 0

接下来,您想将输入转换为整数:

x = int(input("enter a number :"))
y = int(input("enter its multiple :"))

你会在一行中得到一个 NameError 表示 end 表达式,完全删除它,Python 不需要那些。

你可以测试 just x;在诸如 if 语句的布尔上下文中,如果 0:

则数字被认为是假的
if x and y % x == 0:

你的函数 is_multiple() 应该只是 return 一个布尔值;将打印留给执行所有其他操作的程序部分 input/output:

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 运算符代替按位 & 运算符。

您需要使用 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)

有些事情要提一下:

  1. 条件 and,而不是 &(二元运算符)
  2. 将输入转换为数字(例如使用 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)