## 1、 Problem description

define function，calculate the input parameters and return the result.

- The data is stored in txt as a matrix of 10 rows and 10 columns.
- Write a function and pass in parameters: file path, first data row and column index, second data row and column index and operator.
- Return calculation results
- If no file path is passed in, a random integer array with a value of 10 * 10 ranging from [6, 66] is randomly generated and stored in txt for subsequent data reading and testing.

## 2、 Python program

Import the required dependent libraries and log output configurations

```
# -*- coding: UTF-8 -*-
"""
@Author: ye Tingyun
@ official account: practice Python
@CSDN ：https://yetingyun.blog.csdn.net/
"""
import numpy as np
import logging
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s: %(message)s')
```

Generate data

```
def generate_fake_data():
"""
: params: None
: Return: none
: function: if no file path is passed in, randomly generate a random integer array with 10 * 10 values ranging from [6, 66]
Save TXT for subsequent data reading and testing
"""
#Create a 10 * 10 random number array with a normal distribution with a mean of 8 and a standard deviation of 1
# data = np.random.normal(8, 1, (10, 10))
#Create a random integer array with 10 * 10 values ranging from [6, 66]
data = np.random.randint(6, 66, (10, 10))
print(data)
with open("./data/random_data.txt", "w") as f:
for i in data:
for j in i:
f.write(str(j) + '\t')
f.write("\n")
```

Load data and calculate and return results.

```
def load_data_and_calculate(point1, point2, operation,
file="./data/random_data.txt"):
"""
: param file: the file path is the default parameter: the parameter that can be passed or omitted when calling the function. If it is not passed, the default value test will be used
: param point1: row column index tuple type of the first data
: param point2: row column index tuple type of the second data
: param operation: operator
: Return: the result of the operation
"""
If file = = ". / data / random_data. TXT": # if it is still the default parameter, it means that there is no file path passed in
generate_fake_data()
else:
pass
Data = NP. Fromfile (file, Sep = '\ t', dtype = NP. Float32) # read the fromfile method of TXT data numpy
new_ Data = data.reshape ([10, 10]) # (100,) reshape is (10, 10) 10 rows and 10 columns
print(new_data)
#Two data in the two-dimensional array are obtained according to the index, and possible index out of bounds exceptions are captured
num1, num2 = None, None
try:
num1 = new_data[point1[0]][point1[1]]
num2 = new_data[point2[0]][point2[1]]
Print (F "the two numbers obtained according to the row and column index are: {num1} {num2}") # print view
except IndexError:
Logging.info (F "the row column index exceeds the dataset boundary, and the current dataset shape is: {new_data. Shape}")
#Perform operations to catch possible exceptions
try:
#The eval function returns the result of the expression passed in a string
result = eval(f"{num1}{operation}{num2}")
print(f"result： {num1} {operation.strip()} {num2} = {result}\n")
return result
except ZeroDivisionError:
Logging. Error (F "divisor num2 cannot be zero!")
except SyntaxError:
if operator in ['x', 'X']:
Logging.error (F "please use * instead of {operation} during multiplication")
else:
Logging. Error (F "illegal operator entered: ({operation})")
```

Pass in parameters and call the function.

```
file_path = "./data/testData.txt"
#Enter the first data row column index
X1, Y1 = map (int, input ("please enter the row and column coordinates of the first data (e.g. 6,8):"). Split ('))
#Enter the second data row column index
X2, y2 = map (int, input ("please enter the row and column coordinates of the first data (e.g. 3,5):"). Split ('))
#Input operation symbol
Operator = input ("please enter operators (such as +, -, *, // /,%...):")
#Pass in arguments
my_result = load_data_and_calculate((x1, y1), (x2, y2), operator, file_path)
#Output with two decimal places reserved
Print ("after {} operation, the result is: {:. 2F}". Format (operator, my_result))
```

The results are as follows:

This is the end of this article on the case explanation of Python’s calculation results based on input parameters. For more information about Python’s calculation results based on input parameters, please search the previous articles of developeppaer or continue to browse the relevant articles below. I hope you will support developeppaer in the future!