检查一个随机数是否为8(Python)



我刚刚开始学习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("nn")
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("nn")
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")

它得到数字并返回它们,在简单的数学功能上对其进行了测试,只是没有得到如何做倍数的方法...很高兴任何帮助!:)

是的,我搜索了如何找到倍数,但我仍然不明白。:/

您在这里有一些问题;

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

  • 您将返回值投入到int

在您的方法定义中,您返回 tuple

return one, two

但是,当获取值时,您将其投射到int

one = int(getRandomSelection(Numbers))

相反,实际上获取tuple

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

    def mutiperofeight(numList): 一个= int(getRandomSelection(numbers))

应该成为:

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

最后,您从未真正调用主要方法;在脚本的末尾;添加此行实际运行:

MultipleOfEight(Numbers)

使用号码调用此方法,您在顶部定义的主列表。

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

其他人已经指出了这些错误,所以如果您想看一下,我为您重新制定了代码。

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("nn")
  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)

最新更新