用Python写一个随机数加减乘除
时间: 2024-03-06 21:21:16 浏览: 59
python 实现随机数
可以使用Python内置的random模块来生成随机数,然后通过用户输入来选择加减乘除的操作。
以下是示例代码:
```python
import random
def generate_question():
"""生成随机问题"""
num1 = random.randint(1, 100)
num2 = random.randint(1, 100)
operator = random.choice(['+', '-', '*', '/'])
question = f"{num1} {operator} {num2}"
return question
def evaluate_answer(question, answer):
"""验证答案是否正确"""
result = eval(question)
if abs(result - answer) < 1e-6:
return True
else:
return False
if __name__ == '__main__':
while True:
question = generate_question()
answer = input(f"What is the result of {question}? ")
try:
answer = float(answer)
except ValueError:
print("Invalid input, please try again.")
continue
if evaluate_answer(question, answer):
print("Correct!")
else:
print("Wrong answer, please try again.")
```
运行上述代码后,程序将会不断地生成随机问题,等待用户输入答案。如果答案正确,则输出"Correct!",否则输出"Wrong answer, please try again.",并重新生成一个新的随机问题。
阅读全文