Python 获取原始输入以评估数据,然后打印回某些内容
我正在尝试制作我的第一段代码,它将是一个随机数生成器,然后减去这些数字。到目前为止,我有:Python 获取原始输入以评估数据,然后打印回某些内容,python,python-2.7,Python,Python 2.7,我正在尝试制作我的第一段代码,它将是一个随机数生成器,然后减去这些数字。到目前为止,我有: def rand2(): rand2 = random.choice('123456789') return int(rand2) def rand3(): rand3 = random.choice('987654321') return int(rand3) 然后,我有一个函数将这些函数组合在一起: def r
def rand2():
rand2 = random.choice('123456789')
return int(rand2)
def rand3():
rand3 = random.choice('987654321')
return int(rand3)
然后,我有一个函数将这些函数组合在一起:
def rand():
print rand3()
print '-'
print rand2()
ans()
我试图通过添加ans()函数来生成一个解算器。它看起来是这样的:
def ans():
ans = int(raw_input("Answer: "))
if ans == rand3() - rand2():
print("Correct")
然而,当返回正确时,这并不评估返回正确的数据。关于获取原始输入以评估输入数据的任何提示或建议?
rand2
和rand3
在每次调用时都会返回不同的值,因此您必须保存它们的返回值,类似这样的操作应该可以:
def rand():
r3 = rand3()
r2 = rand2()
print r3
print '-'
print r2
ans(r3, r2)
def ans(r3, r2):
ans = int(raw_input("Answer: "))
if ans == r3 - r2:
print("Correct")
只需调用一次随机函数,并将这些数字作为参数传递。例如:
import random
# Variable names changed. Having a variable the same name as a function
# is confusing and can lead to side-effects in some circumstances
def rand2():
rand2v = random.choice('123456789')
return int(rand2v)
def rand3():
rand3v = random.choice('987654321')
return int(rand3v)
# This functions takes as parameters the two random numbers
def ans(r2, r3):
ans = int(raw_input("Answer: "))
if ans == r3 - r2:
print("Correct")
def rand():
# This is the only place we create random numbers
r2 = rand2()
r3 = rand3()
# The print can be doe in one line
print r3, '-', r2
# Pass the numbers to ans()
ans(r2, r3)
rand()
对
rand3
和rand2
的每次调用都会返回不同的随机值。您需要将这些结果分配给变量,而不是再次调用。