即使在选择再次播放后选择了其他运算符,该代码也会使用上次播放中选择的运算符。
我再次检查了功能,但仍然找不到确切的问题所在。
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()
欢迎光临!我们在练习什么?
加法(+)
减(-)
乘法(*)
除法(/)
*
18 * 4
72对!你想再玩一次吗?
y
我们在练习什么?
加法(+)
减(-)
乘法(*)
除法(/)
+
94 * 83
答案 0 :(得分:0)
它卡在一个操作上的原因是,在get_choice()
中调用它时,您没有从repeat()
捕获任何返回值。我将raw_input()
调整为input()
,以便可以使用它(我在python 3.X上,并且您也应该升级,因为2.X将于今年停产!),它现在看来对我来说很好:
def repeat():
while True:
print("Do you want to play again?")
again = input('>')
if again == 'y' or again == 'Y':
operation = get_choice() # you need to assign "operator" to the return value
ask_question(operation)
check_response(response)
else:
break
repeat()
示例输出:
Welcome!
What are we practicing?
1. Addition (+)
2. Subtraction (-)
3. Multiplication (*)
4. Division (/)
> +
82 + 72
>154
Correct!
Do you want to play again?
>y
What are we practicing?
1. Addition (+)
2. Subtraction (-)
3. Multiplication (*)
4. Division (/)
> -
57 - 28 # the sign did in fact change to -
>