所以我对我的作业有疑问。
计划必须:
* Asks from user the number of clients ( not negative int number )
* Uses while and gets total number of flowers
* Print final sum to screen.
我们有这样的文字: 这是妇女节,鲜花店决定给女性送花。但事实是,只有奇数才能得到它们。 所以第一个得到1,第二个得到任何东西,第三个得到3,第五个得到5,依此类推。如果插入7,则奇数之和为16:1 + 3 + 5 + 7 = 16.如果用户插入8,则sum也是16:1 + 3 + 5 + 7 = 16。 奇数不能大于女性人数。
你必须插入女性人数。
我做到了:
women = int(input("Insert number of buyers: "))
i = 1
sum = 0
while i < women:
i = i + 2
sum = sum + i
print("Total of flowers is: " + str(women))
但它起作用了,我的大脑完全没有想法:(
最终结果必须如下:
Insert number of buyers: 7
Total of flowers is : 16
答案 0 :(得分:3)
您的代码有三个缺陷:
i
之前递增sum
(意味着第一夫人得到3朵花)women=7
循环体将不会执行i==7
,因此它应该是i <= women
)sum
),而是打印输入(women
)这是一个固定版本:
women = int(input("Insert number of buyers: "))
i = 1
sum = 0
while i <= women:
sum = sum + i
i = i + 2
print("Total of flowers is: " + str(sum))
答案 1 :(得分:1)
使用列表解析执行此操作:
women = int(input("Insert number of buyers: "))
flowers = sum(i for i in range(1, women+1) if i%2 == 1)
print("Total of flowers is:", flowers)
或使用range
的步骤参数:
women = int(input("Insert number of buyers: "))
flowers = sum(range(1, women+1, 2))
print("Total of flowers is:", flowers)
或者使用循环,它可能如下所示:
women = int(input("Insert number of buyers: "))
flowers = 0
for i in range(1, women+1):
if i%2 == 1:
flowers += i
print("Total of flowers is:", flowers)
或者使用循环和range
的步骤参数看起来像这样:
women = int(input("Insert number of buyers: "))
flowers = 0
for i in range(1, women+1, 2):
flowers += i
print("Total of flowers is:", flowers)
在将来的生产代码中,您将选择变体1或2。
答案 2 :(得分:1)
在我看来,使用for
循环会更简单。
women = int(input("Insert number of buyers: "))
sum = 0
for i in range(1,women+1):
if i%2 != 0: # If i is odd
sum += 1
print("Total of flowers is: " + str(sum))
或
women = int(input("Insert number of buyers: "))
sum = sum(i for i in range(1,women+1) if i%2 != 0)
print("Total of flowers is: " + str(sum))
答案 3 :(得分:1)
您的简易修订代码:
women = int(input("Insert number of buyers: "));
i = 1;
sum = i;
if women%2==0:
women=women-1;
while i < women:
i = i + 2;
sum = sum + i;
print("Total of flowers is: " + str(sum));