我对python非常陌生,我只是尝试了一些简单的程序,我目前正在尝试制作一个程序,在用户输入的间隔内显示所有偶数。我有它工作,但我认为我有一个逻辑错误,我无法弄清楚。 如果我使用间隔2-8我的程序将打印
2
2
4
4
4
4
6
6
6
6
6
6
我的代码是:
startingnumber = int(input("Please enter a starting even number:"))
if startingnumber%2==0:
endingnumber = int(input("Please enter an ending number:"))
else:
print("Please eneter an even number")
for num in range(startingnumber,endingnumber):
for i in range(num):
if (num%2) ==0:
print(num)
有人可以尝试帮助发现我的错误吗? 感谢
答案 0 :(得分:1)
for num in range(startingnumber,endingnumber):
if (num%2) ==0:
print(num)
你有一个你不需要的额外循环。
答案 1 :(得分:1)
Just use a step of 2:
range(start, end, step)
#This is not suggestible way to code in Python, but it gives a better understanding
numbers = range(1,10)
even = []
for i in numbers:
if i%2 == 0:
even.append(i)
print (even)
答案 2 :(得分:0)
而不是做
for num in range(startingnumber,endingnumber):
DO
for num in range(startingnumber+startingnumber%2,endingnumber+1,2):
print(num)