如何重新編寫此程序以避免使用我的全局num1和num2?我有一個額外的信貸分配在我的編程類重寫了幾個程序,而無需使用全局變量,但是這其中有我難倒...避免在python中使用全局變量
# Define the main function
def main():
randomNumbers()
print "Please add the following numbers:"
print " ", num1
print "+ ", num2
print "------"
correctAnswer = num1 + num2
userAnswer = int(raw_input(" "))
if userAnswer == correctAnswer:
print "Great job!"
else:
# Return the correct answer for the user
print "You're wrong! The correct answer was %s!" % correctAnswer
# Define a function to generate random numbers
def randomNumbers():
import random # Imports the random module
# Generates two random numbers to be added
global num1
global num2
num1 = random.randrange(100,1000)
num2 = random.randrange(100,1000)
# Call the main function
main()
想通弄明白了!非常感謝!
# Define the main function
def main():
num1, num2 = randomNumbers()
print "Please add the following numbers:"
print " ", num1
print "+ ", num2
print "------"
correctAnswer = num1 + num2
userAnswer = int(raw_input(" "))
if userAnswer == correctAnswer:
print "Great job!"
else:
# Return the correct answer for the user
print "You're wrong! The correct answer was %s!" % correctAnswer
# Define a function to generate random numbers
def randomNumbers():
import random # Imports the random module
rand1 = random.randrange(100,1000)
rand2 = random.randrange(100,1000)
return rand1, rand2
# Call the main function
main()
把隨機調用在主函數中,忘了隨機函數 – 2014-09-25 23:17:26