检查随机数是否是8的倍数(python)

时间:2017-11-30 19:18:31

标签: python math

我刚刚开始学习Python,我想知道一个随机数是8的倍数,试过但却失败了......在学校里挣扎着数学并试着在我去的时候捡起它。 :/

到处寻找,找到C的答案但不是Python的答案

代码

import random

Numbers = [15, 100, 50, 70, 5, 10, 12, 20, 123, 72, 81, 76, 25, 19, 40, 17, 16, 32]

print("\n\n")

def getRandomSelection(numbers):
  one = (random.choice(numbers))
  two = (random.choice(numbers))
  if two == one:
    while two == one:
      two = (random.choice(Numbers))

return one, two

print("\n\n")

def MutipleOfEight(numList):

  one = int(getRandomSelection(Numbers))
  print("First Number: " + str(one))
  if (one % 8 == 0): #To check if it's multiple of 8
    print(str(one) + "is a multiple of 8")
  else:
    print(str(one) + "is not a multiple of 8")

它获取数字并返回它们,在简单的数学函数上测试它,只是不知道如何做多次... ...感谢任何帮助! :)

是的,我用谷歌搜索了如何找到倍数,但我仍然没有得到它。 :/

3 个答案:

答案 0 :(得分:2)

这里有一些问题;

  • 返回语句的范围不正确,您应该从方法调用中返回值,因为返回是在主体中。 (这可能在发布到StackOverflow时成为一个问题)

  • 您将返回值转换为int

在方法定义中,您返回tuple

return one, two

但是在获取值时,您将其转换为int

one = int(getRandomSelection(Numbers))

相反,实际上是获取tuple

( one, two ) = getRandomSelection(Numbers)
  • 您的MutipleOfEight定义需要一个数字列表,但这不是您实际使用的列表:

    def MutipleOfEight(numList):    one = int(getRandomSelection(Numbers))

应该成为:

 def MutipleOfEight(numList):
   ( one, two ) = getRandomSelection(numList)

最后,你实际上从未调用过main方法;在脚本的最后;添加此行以实际运行它:

MultipleOfEight(Numbers)

使用 Numbers (您在顶部定义的主列表)调用此方法。

答案 1 :(得分:1)

getRandomSelection返回两个数字的元组,因此int(getRandomSelection(Numbers))失败。您可以one, two = getRandomSelection(Numbers),而无需转换为int。你的数学看起来是正确的。

答案 2 :(得分:0)

其他人已经指出了错误,所以如果你想看看,我会为你重新制作代码。

import random

Numbers = [15, 100, 50, 70, 5, 10, 12, 20, 123, 72, 81, 76, 25, 19, 40, 17, 16, 32]

def getRandomSelection(numbersList):
  one = (random.choice(numbersList))
  two = (random.choice(numbersList))
  while two == one:
    two = (random.choice(numbersList))

  return one, two

def MutipleOfEight(numbersList):
  one,two = getRandomSelection(numbersList) # You can use this to get both numbers from the other function
  print("First Number: " + str(one))
  if (one % 8 == 0): #To check if it's multiple of 8
    print(str(one) + " is a multiple of 8")
  else:
    print(str(one) + " is not a multiple of 8")

  print("\n\n")

  print("Second Number: " + str(two))
  if (two % 8 == 0): #To check if it's multiple of 8
    print(str(two) + " is a multiple of 8")
  else:
    print(str(two) + " is not a multiple of 8")

MutipleOfEight(Numbers)