需要帮助编写这个程序(Python)。 [英] Need help for coding this program (Python).
问题描述
需要python代码分别收集所有偶数,奇数分别显示为两个单独的总数。数字的范围是1-20
我是这种语言的新手,我不断收到语法错误,语句错误等等。所以如果你这样会很棒也可以写关于代码的描述。
提前致谢。
Need python code that collects all even numbers separately, odd numbers separately and displaying into two separate totals. The range of numbers is 1-20
I am new to this language and I keep getting syntax errors, invalid statement errors etc.. So it would be great if you can write a description about the code as well.
Thanks in advance.
even_list = []
odd_list = []
li = range(1,21)
for i in range(len(li)):
if i/2 == 0 :
even_list.append(li[i])
else :
odd_list.append(li[i])
print even_list
print odd_list
这是我做了什么,但我继续得到无效的语法,没有输出
This is what I did but i keep on getting invalid syntax and no output
推荐答案
我是ot一个python专家,但也许
I'm not a python specialist, but maybe
even_list = []
odd_list = []
li = range(1,21)
for i in li:
if i%2 == 0 :
even_list.append(li[i])
else :
odd_list.append(li[i])
print even_list
print odd_list
注意事项:
- 在这里你需要li中的元素,而不是它们的索引;因此 for i in li:
而不是 for i in range(len(li)):
- 测试数字是奇数还是偶数的函数是模数,而不是除数。
希望这会有所帮助。让我们知道这段代码给出了什么。
Considerations:
- here you need the elements in li, not their indices; thus for i in li:
instead of for i in range(len(li)):
- the function to test whether a number is odd or even is modulo, not division.
Hope this helps. Let us know what this piece of code is giving.
这篇关于需要帮助编写这个程序(Python)。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!