#Python 3.7.2
所以我是新手,只是希望我的程序在两个随机数都匹配的情况下运行“ True”,而在两个都不匹配的情况下运行“ False”,这对于每个人来说似乎都是非常基础的,但是我我慢...
def firstSet():
import random
for x in range(1):
return(random.randint(1,10))
def secondSet():import random
for x in range(1):
return(random.randint(1,10))
def view():
return(secondSet(), firstSet())
def theMatch():
if secondSet() == firstSet():
return(True, view())
else:
return(False, view())
print(theMatch())
theMatch()
我希望输出类似于(True, (5, 5))
或(False, (2,3))
,但实际输出通常像(True, (10, 2))
或(False, (7,7))
一样,只是完全随机。我知道有很多方法可以用更简单的方式编写此程序,但只是想知道我哪里出了错。谢谢
答案 0 :(得分:0)
欢迎堆栈溢出。
您的代码无法正常运行的原因是,您实际上多次多次计算“随机”值,包括之后,您检查它们是否匹配,然后在进行重新计算之前您打印。
让我们稍微看一下代码:
当您调用theMatch()时,会发生以下情况:
下面是一个实现所需内容的示例程序(带有注释):
# Grab the random library
import random
# Create a function to calculate a random number
def create_random_number():
# No need for a loop, just use x to denote a random number between 1 and 10
x = random.randint(1,10)
# Return that random number
return x
# This is your main function.
# This is sometimes called a "driver" program
def main():
# Store a random value in the first_val variable
first_val = create_random_number()
# Store a random value in the second_val variable
second_val = create_random_number()
# If they added up, print out what they were, and that it was a true match
if first_val == second_val:
print(first_val, " and ", second_val, " match, this is TRUE")
# If not, print out what they were, and that it was not a match
else:
print(first_val, " and ", second_val, " do not match, this is FALSE")
# Actually execute your main function
main()
希望这有助于回答您的问题。很快,这是因为您正在比较两个值,然后获取 不同 随机值以进行打印(这有助于依次遍历这些函数的逻辑以及正在发生的事情)。
这是注释您的代码以解释正在发生的事情:
def firstSet():
import random
for x in range(1):
return(random.randint(1,10))
def secondSet():import random
for x in range(1):
return(random.randint(1,10))
def view():
return(secondSet(), firstSet())
def theMatch():
# This pair here are the first and second random integers
if secondSet() == firstSet():
# Now, view() gets called which returns the functions, therefore returning a DIFFERENT set of random integers than the ones being tested
return(True, view())
else:
# Now, view() gets called which returns the functions, therefore returning a DIFFERENT set of random integers than the ones being tested
return(False, view())
print(theMatch())
theMatch()
这是您的代码修复程序,似乎对我有用:
def firstSet():
import random
for x in range(1):
return(random.randint(1,10))
def secondSet():
import random
for x in range(1):
return(random.randint(1,10))
def theMatch():
firstVal = firstSet()
secondVal = secondSet()
if secondVal == firstVal:
# Now, view() gets called which returns the functions, therefore returning a DIFFERENT set of random integers than the ones being tested
return(True, secondVal, firstVal)
else:
# Now, view() gets called which returns the functions, therefore returning a DIFFERENT set of random integers than the ones being tested
return(False, secondVal, firstVal)
print(theMatch())
theMatch()