输入一个数字并返回1和该数字之间所有偶数整数的乘积

时间:2018-11-28 02:27:47

标签: python python-3.x

我正在寻找有关以下问题的帮助:

到目前为止,我的代码已经使我足够远,不仅可以返回正确的答案,而且还可以返回令人震惊的乘法,即:(1、2、2、8、8、48)。任何人都可以改组或重做代码,以便仅输出答案,谢谢!

counter=1
product=1

userinput=int (input ("What number: "))

for counter in range (1, userinput):
    if counter%2==0:
        product=int (counter*product)
        counter=counter+1

    else:
        counter=counter+1

    print (product)

4 个答案:

答案 0 :(得分:2)

这是因为print在每次迭代中执行,您只需要在循环结束后执行它,这意味着print必须与循环具有相同的缩进级别,

counter=1
product=1

userinput=int (input ("What number: "))

for counter in range (1, userinput):
    if counter%2==0:
        product= int(counter*product)


print(product)

答案 1 :(得分:0)

如果要在完成如下所示的循环之后打印print(product)的缩进级别,则应修复该缩进级别。而且,另一重要的事情是,您不需要处理counter变量,因为它会随着for counter in range(1,counter)的增加而增加:

product=1

userinput=int (input ("What number: "))

for counter in range (1, userinput):
    if counter%2==0:
       product=int (counter*product);

print (product)

答案 2 :(得分:0)

很简单。只需阅读我添加到您的代码和修改中的注释即可。

product=1

userinput=int (input ("What number: "))

if userinput = 1: # add these
    return 0      # lines

for counter in range (1, userinput + 1): # add 1 here
    if counter%2==0:
        product=counter*product # here you didn't need int() at all
    # you also don't need to increment counter because it is getting incremented in the for loop

print (product) # decrement this line to the same level of "for counter ..."

编辑: 如果用户提供0或负数,则可以考虑使用此代码,我认为总体而言这更干净

def main(n):

    product = 1

    if n == 0 or n == 1:
        return 0

    range_step = 1
    if n < 0:
        range_step = -1

    for counter in range(1, n+range_step, range_step):
        if counter == 0:
            continue
        elif counter % 2 == 0:
            product = counter*product

    return product


if __name__ == '__main__':
    userinput = int(input("What number: "))
    product = main(userinput)
    print(product)

答案 3 :(得分:0)

您需要对代码进行两次修改

1.> 更改最后一行的缩进 print (product)

2.>在for循环中,将userinput更改为userinput+1(以获得偶数输入的正确答案。)

检查以下代码。 =)

counter=1
product=1

userinput=int (input ("What number: "))

for counter in range (1, userinput+1): #userinput changed to userinput+1
    if counter%2==0:
        product=int (counter*product)
        counter=counter+1

    else:
        counter=counter+1

print (product) #Indentation of last line changed.