Python 3:用户输入随机数以查看是否为5的倍数。然后得到所有5的倍数的总和

时间:2017-07-08 02:38:07

标签: python

我整天都花在这段代码上。它失败了。

def output (n):
  n = int(input('Enter a number: ')

while n != 0:
    if n % 5 == 0:
      print(n, 'Yes')
    n = int(input('Enter a number: ')
    if n == 0
      output = range(1, int(input('Enter a number: '))+1)
      print (output)
output (n)

问题是:

  1. 让用户输入整数以确定是否为5的多个。

  2. 如果是,那么保持计数将保持所有数字的总和为5的倍数。

  3. 使用函数循环完成任务,当输入值0时,循环将终止。

  4. 当循环终止时,返回多个5的数字的数量。

  5. 完成后,下一步: 将变量sum_multiple_five传递给另一个名为print_result()的函数 打印相同的消息,但现在打印将在其自己的功能中完成。

2 个答案:

答案 0 :(得分:0)

def test(n):
    if not n%5:
        print (n,'Yes')
        return n
    else:
        print (n,'No')
        return 0

total = 0
while True:
    n = int(input('Enter a number: '))
    if not n:
        break
    total+=test(n)

print(total)

答案 1 :(得分:-1)

def sum_multiple_five(n):
  count = 0 
  if n == 0: #initial check if the first input is 0 if it is return count as 0 
    return count
  while n != 0: # not leaving this while loop until n is 0
    if n % 5 == 0: #if divisible by 5 increment count by 1 otherwise get new input
      count = count + 1
    n = int(input('Enter a number: ')) # Update n's value from user input. This is important because n is what the while loop is checking.

  return count #when the while loop exit as user input 0 we return count 

def print_result(answer):
  # print(answer)
  print( str(answer) + " numbers were multiple of 5s")


def init():
  n = int(input('Enter a number: ')) #get user input and store it in variable n
  print_result(sum_multiple_five(n)) #call sum_multiple_five() function and use n as an input. then give the returned int to print_result function


init() #call the function init()

结果:

Enter a number:  10
Enter a number:  10
Enter a number:  100
Enter a number:  50
Enter a number:  5
Enter a number:  9
Enter a number:  7
Enter a number:  10
Enter a number:  4
Enter a number:  15
Enter a number:  5
Enter a number:  8
Enter a number:  2
Enter a number:  0
8 numbers were multiple of 5s