如果用户选择再次玩游戏,并选择他们要使用的操作,则程序仍将使用上一个游戏中的操作符号。请参见下面的代码。
import random
print "Welcome!"
def get_choice():
print "What are we practicing? \n1. Addition (+) \n2. Subtraction (-) \n3. Multiplication (*) \n4. Division (/)"
option = raw_input('> ')
while option != '+' and option != '-' and option != '*' and option != '/':
print "You typed %r which is not valid. Please enter \'+, -, *,or /\'" %(option)
option = raw_input('>')
return option
operation = get_choice()
def ask_question (operation):
numbers = []
for y in range(0,2):
x = random.randint(1,100)
numbers.append(x)
num1 = numbers[0]
num2 = numbers[1]
print num1, operation, num2
response = int(raw_input('>'))
return num1, num2, response
num1, num2, response = ask_question(operation)
def check_response(response):
if operation == '+':
answer = num1 + num2
elif operation == '-':
answer = num1 - num2
elif operation == '*':
answer = num1 * num2
else:
answer = num1 / num2
i = 0
if response == answer:
print "Correct!"
elif response != answer:
while i < 2:
print "Wrong! Try again: \n%r + %r" %(num1, num2)
i += 1
response = raw_input()
if response != answer and i >= 2:
print "Sorry. You run out of chances."
check_response(response)
def repeat():
while True:
print "Do you want to play again?"
again = raw_input('>')
if again == 'y' or again == 'Y':
get_choice()
ask_question(operation)
check_response(response)
else:
break
repeat()
请参见下面的示例输出。
欢迎光临! 我们在练习什么? 1.加法(+) 2.减法(-) 3.乘法(*) 4.除法(/)
+ 78 + 28 106 正确! 你想再玩一次吗? ÿ 我们在练习什么? 1.加法(+) 2.减法(-) 3.乘法(*)
4。部门(/)
62 + 85