gpt4 book ai didi

python - 如何用一个 for 循环而不是 if 条件来求和偶数和奇数?

转载 作者:行者123 更新时间:2023-12-03 07:33:00 25 4
gpt4 key购买 nike

我正在大学上一门编程课,问题表中的一个练习是编写以下代码:

number = int(input())
x = 0
y = 0
for n in range(number):
if n % 2 == 0:
x += n
else:
y += n
print(x)
print(y)
只使用一个“for”循环,不使用“while”或“if”。

The purpose of the code is to find the sum of the even and the sum ofthe odd numbers from zero to the number inputted and print it to thescreen.


请注意,此时我们不应该知道
职能。
我已经尝试了很长时间,似乎无法找到一种不使用“if”语句来知道循环变量是偶数还是奇数的方法。

最佳答案

for n in range(number):
x += (1 - n % 2) * n
y += (n % 2) * n

关于python - 如何用一个 for 循环而不是 if 条件来求和偶数和奇数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65018676/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com