我在Python课堂上有一个作业要做,有人问我:
Make a program that gets 2 numbers from the user, and prints all even numbers in the range of those 2 numbers, you can only use as many for statements as you want, but can't use another loops or if statement.
我明白我需要使用以下代码:
for num in range (x,y+1,2):
print (num)
但是如果没有任何if
语句,我无法检查插入的值x
是偶数还是奇数,如果用户将5
作为x
插入,则所有打印都将是奇数。在
我还试图将每个数字输入到一个元组或数组中,但我仍然无法检查第一个数字是否要开始打印。在
^{pr2}$或者
def printEvenFor(x,y):
for i in range (x,y+1,2):
print(i,",")
我希望printEvenFor(5,12)
的输出是6,8,10,12
,但它是{
一种方法是使用while,它将起始和结束范围
您可以通过使用底数除法和乘法使x为偶数:
x将被四舍五入到前一个偶数整数,如果是偶数,则保持不变。在
如果要将其四舍五入为以下偶数整数,则需要执行以下操作:
^{pr2}$这可以通过使用移位运算符进一步改进:
示例:
第二种可能更适合你
您可以使用提醒来获取正确的范围:
输出:
^{pr2}$相关问题 更多 >
编程相关推荐