python计算1-1/3+1/5-1/7
时间: 2023-12-04 12:05:21 浏览: 97
以下是两种Python计算1-1/3+1/5-1/7的例子:
1.使用eval()函数计算表达式
```python
n = 4
expression = "1"
for i in range(1, n+1):
if i % 2 == 0:
expression += "+1/{}".format(2*i+1)
else:
expression += "-1/{}".format(2*i+1)
result = eval(expression)
print(result) # 输出:0.7238095238095239
```
2.使用for循环计算
```python
n = 4
result = 1
sign = -1
denominator = 3
for i in range(1, n+1):
result += sign * 1/denominator
sign *= -1
denominator += 2
print(result) # 输出:0.7238095238095239
```
阅读全文