语法错误:无法分配给函数调用



我在Python中编码时遇到了这个错误:SyntaxError: cannot assign to function call.这是我的代码:

for number in range(1,101):
if int(number) % 3 == 0 and int(number) % 5 == 0:
int(number) = “fizzbuzz”
if int(number) % 3 == 0:
int(number) = “fizz”
if int(number) % 5 == 0:
int(number) = “buzz”
print(int(number))

有人能解释出了什么问题吗?

int()是一个函数,它接受一个输入,并给出一个输出。您要做的是为该函数分配一个值,而不是实际的number变量。这会给你一个错误,因为函数不包含值,而是包含代码块。然而,变量确实包含值(这就是它们的作用(,因此您可以为number变量赋值,一切都会好起来。

尝试用number = "fizzbuzz"替换int(number) = ""fizzbuzz"。这将改变数字本身的值,并且不会试图更改int函数。最重要的是,记住int()是一个函数,而不是一个变量,所以不能给它一个值。

我希望这能有所帮助!

在Python中,int()用于将数字字符串转换为整数:

print(int('25') + 5)

上面的代码将输出30,因为25被转换为整数数据类型,然后python将这两个数字相加。

如果我正确理解你的目标(有点困难,因为你没有指定它(,下面的代码应该是你想要的:

for number in range(1, 101):
# if number is divisible by 3
if number % 3 == 0:
# if at the same time number is divisible by 5
if number % 5 == 0:
print('fizzbuzz')
# else -> means it's only divisible by 3 and not 5
else:
print('fizz')
# else if divisible by 5 (and not 3)
elif number % 5 == 0:
print('buzz')
# if it's not divisible by either, print the number
else:
print(number)

该代码将打印";fizzbuzz";如果number可被3和5整除;汽水";如果它刚好可以被3整除;嗡嗡声";如果它能被5整除。

如果你意识到一个可以被3和5整除的数字意味着它可以被15整除(3*5(,下面是一个更干净的代码版本。

for number in range(1, 101):
if number % 15 == 0:
print('fizzbuzz')
elif number % 3 == 0:
print('fizz')
elif number % 5 == 0:
print('buzz')
else:
print(number)

最新更新